repo_name
stringlengths
5
108
path
stringlengths
6
333
size
stringlengths
1
6
content
stringlengths
4
977k
license
stringclasses
15 values
alkacon/opencms-core
src/org/opencms/acacia/shared/CmsEntity.java
27138
/* * 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(); } } }
lgpl-2.1
needle4j/needle4j
src/test/java/org/needle4j/postconstruct/injection/ComponentWithPrivatePostConstruct.java
326
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(); } }
lgpl-2.1
kitsushadow/ForgeCraft
old_src/1.10.2/1-7-10Resources/src/main/java/com/kitsu/medievalcraft/item/craftingtools/filters/FineFilter.java
745
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; } }
lgpl-2.1
stijnhero/Forgery
src/main/java/com/stijnhero/forgery/common/block/BlockChimney.java
1674
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; } }
lgpl-2.1
windauer/exist
exist-core/src/main/java/org/exist/dom/memtree/MemTreeBuilder.java
17300
/* * 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; } }
lgpl-2.1
jbossws/jbossws-cxf
modules/testsuite/shared-tests/src/test/java/org/jboss/test/ws/jaxws/jbws1702/SampleWSBareSEI.java
1676
/* * JBoss, Home of Professional Open Source. * Copyright 2006, Red Hat Middleware LLC, 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.test.ws.jaxws.jbws1702; import org.jboss.test.ws.jaxws.jbws1702.types.ResponseWrapperB; import org.jboss.test.ws.jaxws.jbws1702.types.ResponseWrapperC; import javax.jws.WebMethod; import javax.jws.WebService; import javax.jws.soap.SOAPBinding; /** * @author Heiko.Braun@jboss.com */ @WebService @SOAPBinding( style = SOAPBinding.Style.DOCUMENT, use = SOAPBinding.Use.LITERAL, parameterStyle = SOAPBinding.ParameterStyle.BARE ) public interface SampleWSBareSEI { @WebMethod(action="getClassCAsClassB") ResponseWrapperB getClassCAsClassB(); @WebMethod(action="getClassC") ResponseWrapperC getClassC(); }
lgpl-2.1
daxum/TemporalConvergence
src/main/java/daxum/temporalconvergence/item/ItemPhaseClothHelmet.java
1360
/*************************************************************************** * 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); } }
lgpl-2.1
geotools/geotools
modules/ogc/net.opengis.wmts/src/net/opengis/gml311/MultiPointDomainType.java
1714
/** */ 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
lgpl-2.1
EgorZhuk/pentaho-reporting
engine/extensions-mondrian/src/main/java/org/pentaho/reporting/engine/classic/extensions/datasources/mondrian/AbstractMDXDataFactory.java
37834
/*! * 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 ) ); } }
lgpl-2.1
statsbiblioteket/sbutil
sbutil-qa/src/main/java/dk/statsbiblioteket/util/qa/QAInfo.java
5049
/* $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; }
lgpl-2.1
kevin-chen-hw/LDAE
com.huawei.soa.ldae/src/main/java/org/hibernate/type/descriptor/java/ByteArrayTypeDescriptor.java
4548
/* * 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; } }
lgpl-2.1
HickGamer/Better-Utilites
Reference Code/Neotech Code/java/com/teambrmodding/neotech/client/gui/machines/processors/GuiSolidifier.java
8916
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()); } }); } } }
lgpl-2.1
kevin-chen-hw/LDAE
com.huawei.soa.ldae/src/main/java/org/hibernate/collection/spi/PersistentCollection.java
13745
/* * 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); }
lgpl-2.1
thilokru/Controller-Support
src/main/java/com/mhfs/controller/hotplug/DaemonManager.java
2505
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(); } } }
lgpl-2.1
mcarniel/oswing
srclnf/org/openswing/swing/table/client/MacPaginationVerticalScrollBarUI.java
9721
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; } } } }
lgpl-2.1
dpoldrugo/proxyma
proxyma-core/src/main/java/m/c/m/proxyma/rewrite/CookieRewriteEngine.java
3420
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#%#"; }
lgpl-2.1
geotools/geotools
modules/ogc/net.opengis.wfs/src/net/opengis/wfs20/validation/TransactionTypeValidator.java
1029
/** * * $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); }
lgpl-2.1
Romenig/ivprog2
src/usp/ime/line/ivprog/model/domain/actions/ReturnSetExpression.java
1489
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; } }
lgpl-2.1
musdasch/VeniceMod
src/main/java/org/venice/venicemod/generations/TitaniumGeneraton.java
535
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 ); } }
lgpl-2.1
zsoltii/dss
dss-spi/src/main/java/eu/europa/esig/dss/x509/ocsp/OfflineOCSPSource.java
3289
/** * 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(); }
lgpl-2.1
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/main/java/org/hibernate/cfg/annotations/reflection/JPAOverriddenAnnotationReader.java
128122
/* * 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(); } }
lgpl-2.1
jeromeOrfila/treckar
src/com/gromstudio/treckar/model/WorldMapArea.java
114
package com.gromstudio.treckar.model; import java.net.URL; public class WorldMapArea { URL mBitmapUrl; }
lgpl-2.1
secure-software-engineering/soot-infoflow
src/soot/jimple/infoflow/solver/fastSolver/IFDSSolver.java
29328
/******************************************************************************* * 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); } }
lgpl-2.1
netarchivesuite/netarchivesuite-svngit-migration
tests/dk/netarkivet/harvester/indexserver/distribute/IndexRequestServerTester.java
15783
/* $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); } }
lgpl-2.1
cacheonix/cacheonix-core
src/org/cacheonix/impl/net/cluster/ClusterView.java
3125
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(); }
lgpl-2.1
nybbs2003/jopenmetaverse
src/main/java/com/ngt/jopenmetaverse/shared/sim/visual/VisualParams.java
93393
/** * A library to interact with Virtual Worlds such as OpenSim * Copyright (C) 2012 Jitendra Chauhan, Email: jitendra.chauhan@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., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA */ package com.ngt.jopenmetaverse.shared.sim.visual; import java.util.Map; import java.util.Map.Entry; import java.util.TreeMap; import com.ngt.jopenmetaverse.shared.types.Color4; public class VisualParams { /// <summary> /// Operation to apply when applying color to texture /// </summary> public static enum VisualColorOperation { Add, Blend, Multiply } /// <summary> /// Information needed to translate visual param value to RGBA color /// </summary> public static class VisualColorParam { public VisualColorOperation Operation; public Color4[] Colors; /// <summary> /// Construct VisualColorParam /// </summary> /// <param name="operation">Operation to apply when applying color to texture</param> /// <param name="colors">Colors</param> public VisualColorParam(VisualColorOperation operation, Color4[] colors) { Operation = operation; Colors = colors; } } /// <summary> /// Represents alpha blending and bump infor for a visual parameter /// such as sleive length /// </summary> public static class VisualAlphaParam { /// <summary>Stregth of the alpha to apply</summary> public float Domain; /// <summary>File containing the alpha channel</summary> public String TGAFile; /// <summary>Skip blending if parameter value is 0</summary> public boolean SkipIfZero; /// <summary>Use miltiply insted of alpha blending</summary> public boolean MultiplyBlend; /// <summary> /// Create new alhpa information for a visual param /// </summary> /// <param name="domain">Stregth of the alpha to apply</param> /// <param name="tgaFile">File containing the alpha channel</param> /// <param name="skipIfZero">Skip blending if parameter value is 0</param> /// <param name="multiplyBlend">Use miltiply insted of alpha blending</param> public VisualAlphaParam(float domain, String tgaFile, boolean skipIfZero, boolean multiplyBlend) { Domain = domain; TGAFile = tgaFile; SkipIfZero = skipIfZero; MultiplyBlend = multiplyBlend; } } /// <summary> /// A single visual characteristic of an avatar mesh, such as eyebrow height /// </summary> public static class VisualParam { /// <summary>Index of this visual param</summary> public int ParamID; /// <summary>Internal name</summary> public String Name; /// <summary>Group ID this parameter belongs to</summary> public int Group; /// <summary>Name of the wearable this parameter belongs to</summary> public String Wearable; /// <summary>Displayable label of this characteristic</summary> public String Label; /// <summary>Displayable label for the minimum value of this characteristic</summary> public String LabelMin; /// <summary>Displayable label for the maximum value of this characteristic</summary> public String LabelMax; /// <summary>Default value</summary> public float DefaultValue; /// <summary>Minimum value</summary> public float MinValue; /// <summary>Maximum value</summary> public float MaxValue; /// <summary>Is this param used for creation of bump layer?</summary> public boolean IsBumpAttribute; /// <summary>Alpha blending/bump info</summary> public VisualAlphaParam AlphaParams; /// <summary>Color information</summary> public VisualColorParam ColorParams; /// <summary>Array of param IDs that are drivers for this parameter</summary> public int[] Drivers; /// <summary> /// Set all the values through the constructor /// </summary> /// <param name="paramID">Index of this visual param</param> /// <param name="name">Internal name</param> /// <param name="group"></param> /// <param name="wearable"></param> /// <param name="label">Displayable label of this characteristic</param> /// <param name="labelMin">Displayable label for the minimum value of this characteristic</param> /// <param name="labelMax">Displayable label for the maximum value of this characteristic</param> /// <param name="def">Default value</param> /// <param name="min">Minimum value</param> /// <param name="max">Maximum value</param> /// <param name="isBumpAttribute">Is this param used for creation of bump layer?</param> /// <param name="drivers">Array of param IDs that are drivers for this parameter</param> /// <param name="alpha">Alpha blending/bump info</param> /// <param name="colorParams">Color information</param> public VisualParam(int paramID, String name, int group, String wearable, String label, String labelMin, String labelMax, float def, float min, float max, boolean isBumpAttribute, int[] drivers, VisualAlphaParam alpha, VisualColorParam colorParams) { ParamID = paramID; Name = name; Group = group; Wearable = wearable; Label = label; LabelMin = labelMin; LabelMax = labelMax; DefaultValue = def; MaxValue = max; MinValue = min; IsBumpAttribute = isBumpAttribute; Drivers = drivers; AlphaParams = alpha; ColorParams = colorParams; } } public static Map<Integer, VisualParam> Params = new TreeMap<Integer, VisualParam>(); public static VisualParam Find(String name, String wearable) { for (Entry<Integer, VisualParam> param : Params.entrySet()) if (param.getValue().Name.equals(name) && param.getValue().Wearable.equals(wearable)) return param.getValue(); return null; } static { Params.put(1, new VisualParam(1, "Big_Brow", 0, "shape", "Brow Size", "Small", "Large", -0.3f, -0.3f, 2f, false, null, null, null)); Params.put(2, new VisualParam(2, "Nose_Big_Out", 0, "shape", "Nose Size", "Small", "Large", -0.8f, -0.8f, 2.5f, false, null, null, null)); Params.put(4, new VisualParam(4, "Broad_Nostrils", 0, "shape", "Nostril Width", "Narrow", "Broad", -0.5f, -0.5f, 1f, false, null, null, null)); Params.put(5, new VisualParam(5, "Cleft_Chin", 0, "shape", "Chin Cleft", "Round", "Cleft", -0.1f, -0.1f, 1f, false, null, null, null)); Params.put(6, new VisualParam(6, "Bulbous_Nose_Tip", 0, "shape", "Nose Tip Shape", "Pointy", "Bulbous", -0.3f, -0.3f, 1f, false, null, null, null)); Params.put(7, new VisualParam(7, "Weak_Chin", 0, "shape", "Chin Angle", "Chin Out", "Chin In", -0.5f, -0.5f, 0.5f, false, null, null, null)); Params.put(8, new VisualParam(8, "Double_Chin", 0, "shape", "Chin-Neck", "Tight Chin", "Double Chin", -0.5f, -0.5f, 1.5f, false, null, null, null)); Params.put(10, new VisualParam(10, "Sunken_Cheeks", 0, "shape", "Lower Cheeks", "Well-Fed", "Sunken", -1.5f, -1.5f, 3f, false, null, null, null)); Params.put(11, new VisualParam(11, "Noble_Nose_Bridge", 0, "shape", "Upper Bridge", "Low", "High", -0.5f, -0.5f, 1.5f, false, null, null, null)); Params.put(12, new VisualParam(12, "Jowls", 0, "shape", "", "Less", "More", -0.5f, -0.5f, 2.5f, false, null, null, null)); Params.put(13, new VisualParam(13, "Cleft_Chin_Upper", 0, "shape", "Upper Chin Cleft", "Round", "Cleft", 0f, 0f, 1.5f, false, null, null, null)); Params.put(14, new VisualParam(14, "High_Cheek_Bones", 0, "shape", "Cheek Bones", "Low", "High", -0.5f, -0.5f, 1f, false, null, null, null)); Params.put(15, new VisualParam(15, "Ears_Out", 0, "shape", "Ear Angle", "In", "Out", -0.5f, -0.5f, 1.5f, false, null, null, null)); Params.put(16, new VisualParam(16, "Pointy_Eyebrows", 0, "hair", "Eyebrow Points", "Smooth", "Pointy", -0.5f, -0.5f, 3f, false, new int[] { 870 }, null, null)); Params.put(17, new VisualParam(17, "Square_Jaw", 0, "shape", "Jaw Shape", "Pointy", "Square", -0.5f, -0.5f, 1f, false, null, null, null)); Params.put(18, new VisualParam(18, "Puffy_Upper_Cheeks", 0, "shape", "Upper Cheeks", "Thin", "Puffy", -1.5f, -1.5f, 2.5f, false, null, null, null)); Params.put(19, new VisualParam(19, "Upturned_Nose_Tip", 0, "shape", "Nose Tip Angle", "Downturned", "Upturned", -1.5f, -1.5f, 1f, false, null, null, null)); Params.put(20, new VisualParam(20, "Bulbous_Nose", 0, "shape", "Nose Thickness", "Thin Nose", "Bulbous Nose", -0.5f, -0.5f, 1.5f, false, null, null, null)); Params.put(21, new VisualParam(21, "Upper_Eyelid_Fold", 0, "shape", "Upper Eyelid Fold", "Uncreased", "Creased", -0.2f, -0.2f, 1.3f, false, null, null, null)); Params.put(22, new VisualParam(22, "Attached_Earlobes", 0, "shape", "Attached Earlobes", "Unattached", "Attached", 0f, 0f, 1f, false, null, null, null)); Params.put(23, new VisualParam(23, "Baggy_Eyes", 0, "shape", "Eye Bags", "Smooth", "Baggy", -0.5f, -0.5f, 1.5f, false, null, null, null)); Params.put(24, new VisualParam(24, "Wide_Eyes", 0, "shape", "Eye Opening", "Narrow", "Wide", -1.5f, -1.5f, 2f, false, null, null, null)); Params.put(25, new VisualParam(25, "Wide_Lip_Cleft", 0, "shape", "Lip Cleft", "Narrow", "Wide", -0.8f, -0.8f, 1.5f, false, null, null, null)); Params.put(26, new VisualParam(26, "Lips_Thin", 1, "shape", "", "", "", 0f, 0f, 0.7f, false, null, null, null)); Params.put(27, new VisualParam(27, "Wide_Nose_Bridge", 0, "shape", "Bridge Width", "Narrow", "Wide", -1.3f, -1.3f, 1.2f, false, null, null, null)); Params.put(28, new VisualParam(28, "Lips_Fat", 1, "shape", "", "", "", 0f, 0f, 2f, false, null, null, null)); Params.put(29, new VisualParam(29, "Wide_Upper_Lip", 1, "shape", "", "", "", -0.7f, -0.7f, 1.3f, false, null, null, null)); Params.put(30, new VisualParam(30, "Wide_Lower_Lip", 1, "shape", "", "", "", -0.7f, -0.7f, 1.3f, false, null, null, null)); Params.put(31, new VisualParam(31, "Arced_Eyebrows", 0, "hair", "Eyebrow Arc", "Flat", "Arced", 0.5f, 0f, 2f, false, new int[] { 872 }, null, null)); Params.put(33, new VisualParam(33, "Height", 0, "shape", "Height", "Short", "Tall", -2.3f, -2.3f, 2f, false, null, null, null)); Params.put(34, new VisualParam(34, "Thickness", 0, "shape", "Body Thickness", "Body Thin", "Body Thick", -0.7f, -0.7f, 1.5f, false, null, null, null)); Params.put(35, new VisualParam(35, "Big_Ears", 0, "shape", "Ear Size", "Small", "Large", -1f, -1f, 2f, false, null, null, null)); Params.put(36, new VisualParam(36, "Shoulders", 0, "shape", "Shoulders", "Narrow", "Broad", -0.5f, -1.8f, 1.4f, false, null, null, null)); Params.put(37, new VisualParam(37, "Hip Width", 0, "shape", "Hip Width", "Narrow", "Wide", -3.2f, -3.2f, 2.8f, false, null, null, null)); Params.put(38, new VisualParam(38, "Torso Length", 0, "shape", "", "Short Torso", "Long Torso", -1f, -1f, 1f, false, null, null, null)); Params.put(40, new VisualParam(40, "Male_Head", 1, "shape", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(80, new VisualParam(80, "male", 0, "shape", "", "", "", 0f, 0f, 1f, false, new int[] { 32, 153, 40, 100, 857 }, null, null)); Params.put(93, new VisualParam(93, "Glove Length", 0, "gloves", "", "Short", "Long", 0.8f, 0.01f, 1f, false, new int[] { 1058, 1059 }, null, null)); Params.put(98, new VisualParam(98, "Eye Lightness", 0, "eyes", "", "Darker", "Lighter", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 0), new Color4(255, 255, 255, 255) }))); Params.put(99, new VisualParam(99, "Eye Color", 0, "eyes", "", "Natural", "Unnatural", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(50, 25, 5, 255), new Color4(109, 55, 15, 255), new Color4(150, 93, 49, 255), new Color4(152, 118, 25, 255), new Color4(95, 179, 107, 255), new Color4(87, 192, 191, 255), new Color4(95, 172, 179, 255), new Color4(128, 128, 128, 255), new Color4(0, 0, 0, 255), new Color4(255, 255, 0, 255), new Color4(0, 255, 0, 255), new Color4(0, 255, 255, 255), new Color4(0, 0, 255, 255), new Color4(255, 0, 255, 255), new Color4(255, 0, 0, 255) }))); Params.put(100, new VisualParam(100, "Male_Torso", 1, "shape", "", "Male_Torso", "", 0f, 0f, 1f, false, null, null, null)); Params.put(104, new VisualParam(104, "Big_Belly_Torso", 1, "shape", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(105, new VisualParam(105, "Breast Size", 0, "shape", "", "Small", "Large", 0.5f, 0f, 1f, false, new int[] { 843, 627, 626 }, null, null)); Params.put(106, new VisualParam(106, "Muscular_Torso", 1, "shape", "Torso Muscles", "Regular", "Muscular", 0f, 0f, 1.4f, false, null, null, null)); Params.put(108, new VisualParam(108, "Rainbow Color", 0, "skin", "", "None", "Wild", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 255, 255), new Color4(255, 0, 0, 255), new Color4(255, 255, 0, 255), new Color4(0, 255, 0, 255), new Color4(0, 255, 255, 255), new Color4(0, 0, 255, 255), new Color4(255, 0, 255, 255) }))); Params.put(110, new VisualParam(110, "Red Skin", 0, "skin", "Ruddiness", "Pale", "Ruddy", 0f, 0f, 0.1f, false, null, null, new VisualColorParam(VisualColorOperation.Blend, new Color4[] { new Color4(218, 41, 37, 255) }))); Params.put(111, new VisualParam(111, "Pigment", 0, "skin", "", "Light", "Dark", 0.5f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(252, 215, 200, 255), new Color4(240, 177, 112, 255), new Color4(90, 40, 16, 255), new Color4(29, 9, 6, 255) }))); Params.put(112, new VisualParam(112, "Rainbow Color", 0, "hair", "", "None", "Wild", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 255, 255), new Color4(255, 0, 0, 255), new Color4(255, 255, 0, 255), new Color4(0, 255, 0, 255), new Color4(0, 255, 255, 255), new Color4(0, 0, 255, 255), new Color4(255, 0, 255, 255) }))); Params.put(113, new VisualParam(113, "Red Hair", 0, "hair", "", "No Red", "Very Red", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(118, 47, 19, 255) }))); Params.put(114, new VisualParam(114, "Blonde Hair", 0, "hair", "", "Black", "Blonde", 0.5f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(22, 6, 6, 255), new Color4(29, 9, 6, 255), new Color4(45, 21, 11, 255), new Color4(78, 39, 11, 255), new Color4(90, 53, 16, 255), new Color4(136, 92, 21, 255), new Color4(150, 106, 33, 255), new Color4(198, 156, 74, 255), new Color4(233, 192, 103, 255), new Color4(238, 205, 136, 255) }))); Params.put(115, new VisualParam(115, "White Hair", 0, "hair", "", "No White", "All White", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 255, 255, 255) }))); Params.put(116, new VisualParam(116, "Rosy Complexion", 0, "skin", "", "Less Rosy", "More Rosy", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(198, 71, 71, 0), new Color4(198, 71, 71, 255) }))); Params.put(117, new VisualParam(117, "Lip Pinkness", 0, "skin", "", "Darker", "Pinker", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(220, 115, 115, 0), new Color4(220, 115, 115, 128) }))); Params.put(119, new VisualParam(119, "Eyebrow Size", 0, "hair", "", "Thin Eyebrows", "Bushy Eyebrows", 0.5f, 0f, 1f, false, new int[] { 1000, 1001 }, null, null)); Params.put(130, new VisualParam(130, "Front Fringe", 0, "hair", "", "Short", "Long", 0.45f, 0f, 1f, false, new int[] { 144, 145 }, null, null)); Params.put(131, new VisualParam(131, "Side Fringe", 0, "hair", "", "Short", "Long", 0.5f, 0f, 1f, false, new int[] { 146, 147 }, null, null)); Params.put(132, new VisualParam(132, "Back Fringe", 0, "hair", "", "Short", "Long", 0.39f, 0f, 1f, false, new int[] { 148, 149 }, null, null)); Params.put(133, new VisualParam(133, "Hair Front", 0, "hair", "", "Short", "Long", 0.25f, 0f, 1f, false, new int[] { 172, 171 }, null, null)); Params.put(134, new VisualParam(134, "Hair Sides", 0, "hair", "", "Short", "Long", 0.5f, 0f, 1f, false, new int[] { 174, 173 }, null, null)); Params.put(135, new VisualParam(135, "Hair Back", 0, "hair", "", "Short", "Long", 0.55f, 0f, 1f, false, new int[] { 176, 175 }, null, null)); Params.put(136, new VisualParam(136, "Hair Sweep", 0, "hair", "", "Sweep Forward", "Sweep Back", 0.5f, 0f, 1f, false, new int[] { 179, 178 }, null, null)); Params.put(137, new VisualParam(137, "Hair Tilt", 0, "hair", "", "Left", "Right", 0.5f, 0f, 1f, false, new int[] { 190, 191 }, null, null)); Params.put(140, new VisualParam(140, "Hair_Part_Middle", 0, "hair", "Middle Part", "No Part", "Part", 0f, 0f, 2f, false, null, null, null)); Params.put(141, new VisualParam(141, "Hair_Part_Right", 0, "hair", "Right Part", "No Part", "Part", 0f, 0f, 2f, false, null, null, null)); Params.put(142, new VisualParam(142, "Hair_Part_Left", 0, "hair", "Left Part", "No Part", "Part", 0f, 0f, 2f, false, null, null, null)); Params.put(143, new VisualParam(143, "Hair_Sides_Full", 0, "hair", "Full Hair Sides", "Mowhawk", "Full Sides", 0.125f, -4f, 1.5f, false, null, null, null)); Params.put(144, new VisualParam(144, "Bangs_Front_Up", 1, "hair", "Front Bangs Up", "Bangs", "Bangs Up", 0f, 0f, 1f, false, null, null, null)); Params.put(145, new VisualParam(145, "Bangs_Front_Down", 1, "hair", "Front Bangs Down", "Bangs", "Bangs Down", 0f, 0f, 5f, false, null, null, null)); Params.put(146, new VisualParam(146, "Bangs_Sides_Up", 1, "hair", "Side Bangs Up", "Side Bangs", "Side Bangs Up", 0f, 0f, 1f, false, null, null, null)); Params.put(147, new VisualParam(147, "Bangs_Sides_Down", 1, "hair", "Side Bangs Down", "Side Bangs", "Side Bangs Down", 0f, 0f, 2f, false, null, null, null)); Params.put(148, new VisualParam(148, "Bangs_Back_Up", 1, "hair", "Back Bangs Up", "Back Bangs", "Back Bangs Up", 0f, 0f, 1f, false, null, null, null)); Params.put(149, new VisualParam(149, "Bangs_Back_Down", 1, "hair", "Back Bangs Down", "Back Bangs", "Back Bangs Down", 0f, 0f, 2f, false, null, null, null)); Params.put(150, new VisualParam(150, "Body Definition", 0, "skin", "", "Less", "More", 0f, 0f, 1f, false, new int[] { 125, 126, 160, 161, 874, 878 }, null, null)); Params.put(151, new VisualParam(151, "Big_Butt_Legs", 1, "shape", "Butt Size", "Regular", "Large", 0f, 0f, 1f, false, null, null, null)); Params.put(152, new VisualParam(152, "Muscular_Legs", 1, "shape", "Leg Muscles", "Regular Muscles", "More Muscles", 0f, 0f, 1.5f, false, null, null, null)); Params.put(153, new VisualParam(153, "Male_Legs", 1, "shape", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(155, new VisualParam(155, "Lip Width", 0, "shape", "Lip Width", "Narrow Lips", "Wide Lips", 0f, -0.9f, 1.3f, false, new int[] { 29, 30 }, null, null)); Params.put(156, new VisualParam(156, "Big_Belly_Legs", 1, "shape", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(157, new VisualParam(157, "Belly Size", 0, "shape", "", "Small", "Big", 0f, 0f, 1f, false, new int[] { 104, 156, 849 }, null, null)); Params.put(162, new VisualParam(162, "Facial Definition", 0, "skin", "", "Less", "More", 0f, 0f, 1f, false, new int[] { 158, 159, 873 }, null, null)); Params.put(163, new VisualParam(163, "Wrinkles", 0, "skin", "", "Less", "More", 0f, 0f, 1f, false, new int[] { 118 }, null, null)); Params.put(165, new VisualParam(165, "Freckles", 0, "skin", "", "Less", "More", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.5f, "freckles_alpha.tga", true, false), null)); Params.put(166, new VisualParam(166, "Sideburns", 0, "hair", "", "Short Sideburns", "Mutton Chops", 0f, 0f, 1f, false, new int[] { 1004, 1005 }, null, null)); Params.put(167, new VisualParam(167, "Moustache", 0, "hair", "", "Chaplin", "Handlebars", 0f, 0f, 1f, false, new int[] { 1006, 1007 }, null, null)); Params.put(168, new VisualParam(168, "Soulpatch", 0, "hair", "", "Less soul", "More soul", 0f, 0f, 1f, false, new int[] { 1008, 1009 }, null, null)); Params.put(169, new VisualParam(169, "Chin Curtains", 0, "hair", "", "Less Curtains", "More Curtains", 0f, 0f, 1f, false, new int[] { 1010, 1011 }, null, null)); Params.put(171, new VisualParam(171, "Hair_Front_Down", 1, "hair", "Front Hair Down", "Front Hair", "Front Hair Down", 0f, 0f, 1f, false, null, null, null)); Params.put(172, new VisualParam(172, "Hair_Front_Up", 1, "hair", "Front Hair Up", "Front Hair", "Front Hair Up", 0f, 0f, 1f, false, null, null, null)); Params.put(173, new VisualParam(173, "Hair_Sides_Down", 1, "hair", "Sides Hair Down", "Sides Hair", "Sides Hair Down", 0f, 0f, 1f, false, null, null, null)); Params.put(174, new VisualParam(174, "Hair_Sides_Up", 1, "hair", "Sides Hair Up", "Sides Hair", "Sides Hair Up", 0f, 0f, 1f, false, null, null, null)); Params.put(175, new VisualParam(175, "Hair_Back_Down", 1, "hair", "Back Hair Down", "Back Hair", "Back Hair Down", 0f, 0f, 3f, false, null, null, null)); Params.put(176, new VisualParam(176, "Hair_Back_Up", 1, "hair", "Back Hair Up", "Back Hair", "Back Hair Up", 0f, 0f, 1f, false, null, null, null)); Params.put(177, new VisualParam(177, "Hair_Rumpled", 0, "hair", "Rumpled Hair", "Smooth Hair", "Rumpled Hair", 0f, 0f, 1f, false, null, null, null)); Params.put(178, new VisualParam(178, "Hair_Swept_Back", 1, "hair", "Swept Back Hair", "NotHair", "Swept Back", 0f, 0f, 1f, false, null, null, null)); Params.put(179, new VisualParam(179, "Hair_Swept_Forward", 1, "hair", "Swept Forward Hair", "Hair", "Swept Forward", 0f, 0f, 1f, false, null, null, null)); Params.put(180, new VisualParam(180, "Hair_Volume", 1, "hair", "Hair Volume", "Less", "More", 0f, 0f, 1.3f, false, null, null, null)); Params.put(181, new VisualParam(181, "Hair_Big_Front", 0, "hair", "Big Hair Front", "Less", "More", 0.14f, -1f, 1f, false, null, null, null)); Params.put(182, new VisualParam(182, "Hair_Big_Top", 0, "hair", "Big Hair Top", "Less", "More", 0.7f, -1f, 1f, false, null, null, null)); Params.put(183, new VisualParam(183, "Hair_Big_Back", 0, "hair", "Big Hair Back", "Less", "More", 0.05f, -1f, 1f, false, null, null, null)); Params.put(184, new VisualParam(184, "Hair_Spiked", 0, "hair", "Spiked Hair", "No Spikes", "Big Spikes", 0f, 0f, 1f, false, null, null, null)); Params.put(185, new VisualParam(185, "Deep_Chin", 0, "shape", "Chin Depth", "Shallow", "Deep", -1f, -1f, 1f, false, null, null, null)); Params.put(186, new VisualParam(186, "Egg_Head", 1, "shape", "Egg Head", "Chin Heavy", "Forehead Heavy", -1.3f, -1.3f, 1f, false, null, null, null)); Params.put(187, new VisualParam(187, "Squash_Stretch_Head", 1, "shape", "Squash/Stretch Head", "Squash Head", "Stretch Head", -0.5f, -0.5f, 1f, false, null, null, null)); Params.put(190, new VisualParam(190, "Hair_Tilt_Right", 1, "hair", "Hair Tilted Right", "Hair", "Tilt Right", 0f, 0f, 1f, false, null, null, null)); Params.put(191, new VisualParam(191, "Hair_Tilt_Left", 1, "hair", "Hair Tilted Left", "Hair", "Tilt Left", 0f, 0f, 1f, false, null, null, null)); Params.put(192, new VisualParam(192, "Bangs_Part_Middle", 0, "hair", "Part Bangs", "No Part", "Part Bangs", 0f, 0f, 1f, false, null, null, null)); Params.put(193, new VisualParam(193, "Head Shape", 0, "shape", "Head Shape", "More Square", "More Round", 0.5f, 0f, 1f, false, new int[] { 188, 642, 189, 643 }, null, null)); Params.put(194, new VisualParam(194, "Eye_Spread", 1, "shape", "", "Eyes Together", "Eyes Spread", -2f, -2f, 2f, false, null, null, null)); Params.put(195, new VisualParam(195, "EyeBone_Spread", 1, "shape", "", "Eyes Together", "Eyes Spread", -1f, -1f, 1f, false, null, null, null)); Params.put(196, new VisualParam(196, "Eye Spacing", 0, "shape", "Eye Spacing", "Close Set Eyes", "Far Set Eyes", 0f, -2f, 1f, false, new int[] { 194, 195 }, null, null)); Params.put(197, new VisualParam(197, "Shoe_Heels", 1, "shoes", "", "No Heels", "High Heels", 0f, 0f, 1f, false, null, null, null)); Params.put(198, new VisualParam(198, "Heel Height", 0, "shoes", "", "Low Heels", "High Heels", 0f, 0f, 1f, false, new int[] { 197, 500 }, null, null)); Params.put(400, new VisualParam(400, "Displace_Hair_Facial", 1, "hair", "Hair Thickess", "Cropped Hair", "Bushy Hair", 0f, 0f, 2f, false, null, null, null)); Params.put(500, new VisualParam(500, "Shoe_Heel_Height", 1, "shoes", "Heel Height", "Low Heels", "High Heels", 0f, 0f, 1f, false, null, null, null)); Params.put(501, new VisualParam(501, "Shoe_Platform_Height", 1, "shoes", "Platform Height", "Low Platforms", "High Platforms", 0f, 0f, 1f, false, null, null, null)); Params.put(502, new VisualParam(502, "Shoe_Platform", 1, "shoes", "", "No Heels", "High Heels", 0f, 0f, 1f, false, null, null, null)); Params.put(503, new VisualParam(503, "Platform Height", 0, "shoes", "", "Low Platforms", "High Platforms", 0f, 0f, 1f, false, new int[] { 501, 502 }, null, null)); Params.put(505, new VisualParam(505, "Lip Thickness", 0, "shape", "", "Thin Lips", "Fat Lips", 0.5f, 0f, 1f, false, new int[] { 26, 28 }, null, null)); Params.put(506, new VisualParam(506, "Mouth_Height", 0, "shape", "Mouth Position", "High", "Low", -2f, -2f, 2f, false, null, null, null)); Params.put(507, new VisualParam(507, "Breast_Gravity", 0, "shape", "Breast Buoyancy", "Less Gravity", "More Gravity", 0f, -1.5f, 2f, false, null, null, null)); Params.put(508, new VisualParam(508, "Shoe_Platform_Width", 0, "shoes", "Platform Width", "Narrow", "Wide", -1f, -1f, 2f, false, null, null, null)); Params.put(509, new VisualParam(509, "Shoe_Heel_Point", 1, "shoes", "Heel Shape", "Default Heels", "Pointy Heels", 0f, 0f, 1f, false, null, null, null)); Params.put(510, new VisualParam(510, "Shoe_Heel_Thick", 1, "shoes", "Heel Shape", "default Heels", "Thick Heels", 0f, 0f, 1f, false, null, null, null)); Params.put(511, new VisualParam(511, "Shoe_Toe_Point", 1, "shoes", "Toe Shape", "Default Toe", "Pointy Toe", 0f, 0f, 1f, false, null, null, null)); Params.put(512, new VisualParam(512, "Shoe_Toe_Square", 1, "shoes", "Toe Shape", "Default Toe", "Square Toe", 0f, 0f, 1f, false, null, null, null)); Params.put(513, new VisualParam(513, "Heel Shape", 0, "shoes", "", "Pointy Heels", "Thick Heels", 0.5f, 0f, 1f, false, new int[] { 509, 510 }, null, null)); Params.put(514, new VisualParam(514, "Toe Shape", 0, "shoes", "", "Pointy", "Square", 0.5f, 0f, 1f, false, new int[] { 511, 512 }, null, null)); Params.put(515, new VisualParam(515, "Foot_Size", 0, "shape", "Foot Size", "Small", "Big", -1f, -1f, 3f, false, null, null, null)); Params.put(516, new VisualParam(516, "Displace_Loose_Lowerbody", 1, "pants", "Pants Fit", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(517, new VisualParam(517, "Wide_Nose", 0, "shape", "Nose Width", "Narrow", "Wide", -0.5f, -0.5f, 1f, false, null, null, null)); Params.put(518, new VisualParam(518, "Eyelashes_Long", 0, "shape", "Eyelash Length", "Short", "Long", -0.3f, -0.3f, 1.5f, false, null, null, null)); Params.put(600, new VisualParam(600, "Sleeve Length Cloth", 1, "shirt", "", "", "", 0.7f, 0f, 0.85f, false, null, new VisualAlphaParam(0.01f, "shirt_sleeve_alpha.tga", false, false), null)); Params.put(601, new VisualParam(601, "Shirt Bottom Cloth", 1, "shirt", "", "", "", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_bottom_alpha.tga", false, true), null)); Params.put(602, new VisualParam(602, "Collar Front Height Cloth", 1, "shirt", "", "", "", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_collar_alpha.tga", false, true), null)); Params.put(603, new VisualParam(603, "Sleeve Length", 0, "undershirt", "", "Short", "Long", 0.4f, 0.01f, 1f, false, new int[] { 1042, 1043 }, null, null)); Params.put(604, new VisualParam(604, "Bottom", 0, "undershirt", "", "Short", "Long", 0.85f, 0f, 1f, false, new int[] { 1044, 1045 }, null, null)); Params.put(605, new VisualParam(605, "Collar Front", 0, "undershirt", "", "Low", "High", 0.84f, 0f, 1f, false, new int[] { 1046, 1047 }, null, null)); Params.put(606, new VisualParam(606, "Sleeve Length", 0, "jacket", "", "Short", "Long", 0.8f, 0f, 1f, false, new int[] { 1019, 1039, 1020 }, null, null)); Params.put(607, new VisualParam(607, "Collar Front", 0, "jacket", "", "Low", "High", 0.8f, 0f, 1f, false, new int[] { 1021, 1040, 1022 }, null, null)); Params.put(608, new VisualParam(608, "bottom length lower", 0, "jacket", "Jacket Length", "Short", "Long", 0.8f, 0f, 1f, false, new int[] { 620, 1025, 1037, 621, 1027, 1033 }, null, null)); Params.put(609, new VisualParam(609, "open jacket", 0, "jacket", "Open Front", "Open", "Closed", 0.2f, 0f, 1f, false, new int[] { 622, 1026, 1038, 623, 1028, 1034 }, null, null)); Params.put(614, new VisualParam(614, "Waist Height Cloth", 1, "pants", "", "", "", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "pants_waist_alpha.tga", false, false), null)); Params.put(615, new VisualParam(615, "Pants Length Cloth", 1, "pants", "", "", "", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "pants_length_alpha.tga", false, false), null)); Params.put(616, new VisualParam(616, "Shoe Height", 0, "shoes", "", "Short", "Tall", 0.1f, 0f, 1f, false, new int[] { 1052, 1053 }, null, null)); Params.put(617, new VisualParam(617, "Socks Length", 0, "socks", "", "Short", "Long", 0.35f, 0f, 1f, false, new int[] { 1050, 1051 }, null, null)); Params.put(619, new VisualParam(619, "Pants Length", 0, "underpants", "", "Short", "Long", 0.3f, 0f, 1f, false, new int[] { 1054, 1055 }, null, null)); Params.put(620, new VisualParam(620, "bottom length upper", 1, "jacket", "", "hi cut", "low cut", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "jacket_length_upper_alpha.tga", false, true), null)); Params.put(621, new VisualParam(621, "bottom length lower", 1, "jacket", "", "hi cut", "low cut", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "jacket_length_lower_alpha.tga", false, false), null)); Params.put(622, new VisualParam(622, "open upper", 1, "jacket", "", "closed", "open", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "jacket_open_upper_alpha.tga", false, true), null)); Params.put(623, new VisualParam(623, "open lower", 1, "jacket", "", "open", "closed", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "jacket_open_lower_alpha.tga", false, true), null)); Params.put(624, new VisualParam(624, "Pants Waist", 0, "underpants", "", "Low", "High", 0.8f, 0f, 1f, false, new int[] { 1056, 1057 }, null, null)); Params.put(625, new VisualParam(625, "Leg_Pantflair", 0, "pants", "Cuff Flare", "Tight Cuffs", "Flared Cuffs", 0f, 0f, 1.5f, false, null, null, null)); Params.put(626, new VisualParam(626, "Big_Chest", 1, "shape", "Chest Size", "Small", "Large", 0f, 0f, 1f, false, null, null, null)); Params.put(627, new VisualParam(627, "Small_Chest", 1, "shape", "Chest Size", "Large", "Small", 0f, 0f, 1f, false, null, null, null)); Params.put(628, new VisualParam(628, "Displace_Loose_Upperbody", 1, "shirt", "Shirt Fit", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(629, new VisualParam(629, "Forehead Angle", 0, "shape", "", "More Vertical", "More Sloped", 0.5f, 0f, 1f, false, new int[] { 630, 644, 631, 645 }, null, null)); Params.put(633, new VisualParam(633, "Fat_Head", 1, "shape", "Fat Head", "Skinny", "Fat", 0f, 0f, 1f, false, null, null, null)); Params.put(634, new VisualParam(634, "Fat_Torso", 1, "shape", "Fat Torso", "skinny", "fat", 0f, 0f, 1f, false, null, null, null)); Params.put(635, new VisualParam(635, "Fat_Legs", 1, "shape", "Fat Torso", "skinny", "fat", 0f, 0f, 1f, false, null, null, null)); Params.put(637, new VisualParam(637, "Body Fat", 0, "shape", "", "Less Body Fat", "More Body Fat", 0f, 0f, 1f, false, new int[] { 633, 634, 635, 851 }, null, null)); Params.put(638, new VisualParam(638, "Low_Crotch", 0, "pants", "Pants Crotch", "High and Tight", "Low and Loose", 0f, 0f, 1.3f, false, null, null, null)); Params.put(640, new VisualParam(640, "Hair_Egg_Head", 1, "hair", "", "", "", -1.3f, -1.3f, 1f, false, null, null, null)); Params.put(641, new VisualParam(641, "Hair_Squash_Stretch_Head", 1, "hair", "", "", "", -0.5f, -0.5f, 1f, false, null, null, null)); Params.put(642, new VisualParam(642, "Hair_Square_Head", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(643, new VisualParam(643, "Hair_Round_Head", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(644, new VisualParam(644, "Hair_Forehead_Round", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(645, new VisualParam(645, "Hair_Forehead_Slant", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(646, new VisualParam(646, "Egg_Head", 0, "shape", "Egg Head", "Chin Heavy", "Forehead Heavy", 0f, -1.3f, 1f, false, new int[] { 640, 186 }, null, null)); Params.put(647, new VisualParam(647, "Squash_Stretch_Head", 0, "shape", "Head Stretch", "Squash Head", "Stretch Head", 0f, -0.5f, 1f, false, new int[] { 641, 187 }, null, null)); Params.put(648, new VisualParam(648, "Scrawny_Torso", 1, "shape", "Torso Muscles", "Regular", "Scrawny", 0f, 0f, 1.3f, false, null, null, null)); Params.put(649, new VisualParam(649, "Torso Muscles", 0, "shape", "Torso Muscles", "Less Muscular", "More Muscular", 0.5f, 0f, 1f, false, new int[] { 648, 106 }, null, null)); Params.put(650, new VisualParam(650, "Eyelid_Corner_Up", 0, "shape", "Outer Eye Corner", "Corner Down", "Corner Up", -1.3f, -1.3f, 1.2f, false, null, null, null)); Params.put(651, new VisualParam(651, "Scrawny_Legs", 1, "shape", "Scrawny Leg", "Regular Muscles", "Less Muscles", 0f, 0f, 1.5f, false, null, null, null)); Params.put(652, new VisualParam(652, "Leg Muscles", 0, "shape", "", "Less Muscular", "More Muscular", 0.5f, 0f, 1f, false, new int[] { 651, 152 }, null, null)); Params.put(653, new VisualParam(653, "Tall_Lips", 0, "shape", "Lip Fullness", "Less Full", "More Full", -1f, -1f, 2f, false, null, null, null)); Params.put(654, new VisualParam(654, "Shoe_Toe_Thick", 0, "shoes", "Toe Thickness", "Flat Toe", "Thick Toe", 0f, 0f, 2f, false, null, null, null)); Params.put(655, new VisualParam(655, "Head Size", 1, "shape", "Head Size", "Small Head", "Big Head", -0.25f, -0.25f, 0.1f, false, null, null, null)); Params.put(656, new VisualParam(656, "Crooked_Nose", 0, "shape", "Crooked Nose", "Nose Left", "Nose Right", -2f, -2f, 2f, false, null, null, null)); Params.put(657, new VisualParam(657, "Smile_Mouth", 1, "shape", "Mouth Corner", "Corner Normal", "Corner Up", 0f, 0f, 1.4f, false, null, null, null)); Params.put(658, new VisualParam(658, "Frown_Mouth", 1, "shape", "Mouth Corner", "Corner Normal", "Corner Down", 0f, 0f, 1.2f, false, null, null, null)); Params.put(659, new VisualParam(659, "Mouth Corner", 0, "shape", "", "Corner Down", "Corner Up", 0.5f, 0f, 1f, false, new int[] { 658, 657 }, null, null)); Params.put(660, new VisualParam(660, "Shear_Head", 1, "shape", "Shear Face", "Shear Left", "Shear Right", 0f, -2f, 2f, false, null, null, null)); Params.put(661, new VisualParam(661, "EyeBone_Head_Shear", 1, "shape", "", "Eyes Shear Left Up", "Eyes Shear Right Up", -2f, -2f, 2f, false, null, null, null)); Params.put(662, new VisualParam(662, "Face Shear", 0, "shape", "", "Shear Right Up", "Shear Left Up", 0.5f, 0f, 1f, false, new int[] { 660, 661, 774 }, null, null)); Params.put(663, new VisualParam(663, "Shift_Mouth", 0, "shape", "Shift Mouth", "Shift Left", "Shift Right", 0f, -2f, 2f, false, null, null, null)); Params.put(664, new VisualParam(664, "Pop_Eye", 0, "shape", "Eye Pop", "Pop Right Eye", "Pop Left Eye", 0f, -1.3f, 1.3f, false, null, null, null)); Params.put(665, new VisualParam(665, "Jaw_Jut", 0, "shape", "Jaw Jut", "Overbite", "Underbite", 0f, -2f, 2f, false, null, null, null)); Params.put(674, new VisualParam(674, "Hair_Shear_Back", 0, "hair", "Shear Back", "Full Back", "Sheared Back", -0.3f, -1f, 2f, false, null, null, null)); Params.put(675, new VisualParam(675, "Hand Size", 0, "shape", "", "Small Hands", "Large Hands", -0.3f, -0.3f, 0.3f, false, null, null, null)); Params.put(676, new VisualParam(676, "Love_Handles", 0, "shape", "Love Handles", "Less Love", "More Love", 0f, -1f, 2f, false, new int[] { 855, 856 }, null, null)); Params.put(677, new VisualParam(677, "Scrawny_Torso_Male", 1, "shape", "Torso Scrawny", "Regular", "Scrawny", 0f, 0f, 1.3f, false, null, null, null)); Params.put(678, new VisualParam(678, "Torso Muscles", 0, "shape", "", "Less Muscular", "More Muscular", 0.5f, 0f, 1f, false, new int[] { 677, 106 }, null, null)); Params.put(679, new VisualParam(679, "Eyeball_Size", 1, "shape", "Eyeball Size", "small eye", "big eye", -0.25f, -0.25f, 0.1f, false, null, null, null)); Params.put(681, new VisualParam(681, "Eyeball_Size", 1, "shape", "Eyeball Size", "small eye", "big eye", -0.25f, -0.25f, 0.1f, false, null, null, null)); Params.put(682, new VisualParam(682, "Head Size", 0, "shape", "Head Size", "Small Head", "Big Head", 0.5f, 0f, 1f, false, new int[] { 679, 694, 680, 681, 655 }, null, null)); Params.put(683, new VisualParam(683, "Neck Thickness", 0, "shape", "", "Skinny Neck", "Thick Neck", -0.15f, -0.4f, 0.2f, false, null, null, null)); Params.put(684, new VisualParam(684, "Breast_Female_Cleavage", 0, "shape", "Breast Cleavage", "Separate", "Join", 0f, -0.3f, 1.3f, false, null, null, null)); Params.put(685, new VisualParam(685, "Chest_Male_No_Pecs", 0, "shape", "Pectorals", "Big Pectorals", "Sunken Chest", 0f, -0.5f, 1.1f, false, null, null, null)); Params.put(686, new VisualParam(686, "Head_Eyes_Big", 1, "shape", "Eye Size", "Beady Eyes", "Anime Eyes", 0f, -2f, 2f, false, null, null, null)); Params.put(687, new VisualParam(687, "Eyeball_Size", 1, "shape", "Big Eyeball", "small eye", "big eye", -0.25f, -0.25f, 0.25f, false, null, null, null)); Params.put(689, new VisualParam(689, "EyeBone_Big_Eyes", 1, "shape", "", "Eyes Back", "Eyes Forward", -1f, -1f, 1f, false, null, null, null)); Params.put(690, new VisualParam(690, "Eye Size", 0, "shape", "Eye Size", "Beady Eyes", "Anime Eyes", 0.5f, 0f, 1f, false, new int[] { 686, 687, 695, 688, 691, 689 }, null, null)); Params.put(691, new VisualParam(691, "Eyeball_Size", 1, "shape", "Big Eyeball", "small eye", "big eye", -0.25f, -0.25f, 0.25f, false, null, null, null)); Params.put(692, new VisualParam(692, "Leg Length", 0, "shape", "", "Short Legs", "Long Legs", -1f, -1f, 1f, false, null, null, null)); Params.put(693, new VisualParam(693, "Arm Length", 0, "shape", "", "Short Arms", "Long arms", 0.6f, -1f, 1f, false, null, null, null)); Params.put(694, new VisualParam(694, "Eyeball_Size", 1, "shape", "Eyeball Size", "small eye", "big eye", -0.25f, -0.25f, 0.1f, false, null, null, null)); Params.put(695, new VisualParam(695, "Eyeball_Size", 1, "shape", "Big Eyeball", "small eye", "big eye", -0.25f, -0.25f, 0.25f, false, null, null, null)); Params.put(700, new VisualParam(700, "Lipstick Color", 0, "skin", "", "Pink", "Black", 0.25f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(245, 161, 177, 200), new Color4(216, 37, 67, 200), new Color4(178, 48, 76, 200), new Color4(68, 0, 11, 200), new Color4(252, 207, 184, 200), new Color4(241, 136, 106, 200), new Color4(208, 110, 85, 200), new Color4(106, 28, 18, 200), new Color4(58, 26, 49, 200), new Color4(14, 14, 14, 200) }))); Params.put(701, new VisualParam(701, "Lipstick", 0, "skin", "", "No Lipstick", "More Lipstick", 0f, 0f, 0.9f, false, null, new VisualAlphaParam(0.05f, "lipstick_alpha.tga", true, false), null)); Params.put(702, new VisualParam(702, "Lipgloss", 0, "skin", "", "No Lipgloss", "Glossy", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.2f, "lipgloss_alpha.tga", true, false), null)); Params.put(703, new VisualParam(703, "Eyeliner", 0, "skin", "", "No Eyeliner", "Full Eyeliner", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.1f, "eyeliner_alpha.tga", true, false), null)); Params.put(704, new VisualParam(704, "Blush", 0, "skin", "", "No Blush", "More Blush", 0f, 0f, 0.9f, false, null, new VisualAlphaParam(0.3f, "blush_alpha.tga", true, false), null)); Params.put(705, new VisualParam(705, "Blush Color", 0, "skin", "", "Pink", "Orange", 0.5f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(253, 162, 193, 200), new Color4(247, 131, 152, 200), new Color4(213, 122, 140, 200), new Color4(253, 152, 144, 200), new Color4(236, 138, 103, 200), new Color4(195, 128, 122, 200), new Color4(148, 103, 100, 200), new Color4(168, 95, 62, 200) }))); Params.put(706, new VisualParam(706, "Out Shdw Opacity", 0, "skin", "", "Clear", "Opaque", 0.6f, 0.2f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Blend, new Color4[] { new Color4(255, 255, 255, 0), new Color4(255, 255, 255, 255) }))); Params.put(707, new VisualParam(707, "Outer Shadow", 0, "skin", "", "No Eyeshadow", "More Eyeshadow", 0f, 0f, 0.7f, false, null, new VisualAlphaParam(0.05f, "eyeshadow_outer_alpha.tga", true, false), null)); Params.put(708, new VisualParam(708, "Out Shdw Color", 0, "skin", "", "Light", "Dark", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(252, 247, 246, 255), new Color4(255, 206, 206, 255), new Color4(233, 135, 149, 255), new Color4(220, 168, 192, 255), new Color4(228, 203, 232, 255), new Color4(255, 234, 195, 255), new Color4(230, 157, 101, 255), new Color4(255, 147, 86, 255), new Color4(228, 110, 89, 255), new Color4(228, 150, 120, 255), new Color4(223, 227, 213, 255), new Color4(96, 116, 87, 255), new Color4(88, 143, 107, 255), new Color4(194, 231, 223, 255), new Color4(207, 227, 234, 255), new Color4(41, 171, 212, 255), new Color4(180, 137, 130, 255), new Color4(173, 125, 105, 255), new Color4(144, 95, 98, 255), new Color4(115, 70, 77, 255), new Color4(155, 78, 47, 255), new Color4(239, 239, 239, 255), new Color4(194, 194, 194, 255), new Color4(120, 120, 120, 255), new Color4(10, 10, 10, 255) }))); Params.put(709, new VisualParam(709, "Inner Shadow", 0, "skin", "", "No Eyeshadow", "More Eyeshadow", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.2f, "eyeshadow_inner_alpha.tga", true, false), null)); Params.put(710, new VisualParam(710, "Nail Polish", 0, "skin", "", "No Polish", "Painted Nails", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.1f, "nailpolish_alpha.tga", true, false), null)); Params.put(711, new VisualParam(711, "Blush Opacity", 0, "skin", "", "Clear", "Opaque", 0.5f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Blend, new Color4[] { new Color4(255, 255, 255, 0), new Color4(255, 255, 255, 255) }))); Params.put(712, new VisualParam(712, "In Shdw Color", 0, "skin", "", "Light", "Dark", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(252, 247, 246, 255), new Color4(255, 206, 206, 255), new Color4(233, 135, 149, 255), new Color4(220, 168, 192, 255), new Color4(228, 203, 232, 255), new Color4(255, 234, 195, 255), new Color4(230, 157, 101, 255), new Color4(255, 147, 86, 255), new Color4(228, 110, 89, 255), new Color4(228, 150, 120, 255), new Color4(223, 227, 213, 255), new Color4(96, 116, 87, 255), new Color4(88, 143, 107, 255), new Color4(194, 231, 223, 255), new Color4(207, 227, 234, 255), new Color4(41, 171, 212, 255), new Color4(180, 137, 130, 255), new Color4(173, 125, 105, 255), new Color4(144, 95, 98, 255), new Color4(115, 70, 77, 255), new Color4(155, 78, 47, 255), new Color4(239, 239, 239, 255), new Color4(194, 194, 194, 255), new Color4(120, 120, 120, 255), new Color4(10, 10, 10, 255) }))); Params.put(713, new VisualParam(713, "In Shdw Opacity", 0, "skin", "", "Clear", "Opaque", 0.7f, 0.2f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Blend, new Color4[] { new Color4(255, 255, 255, 0), new Color4(255, 255, 255, 255) }))); Params.put(714, new VisualParam(714, "Eyeliner Color", 0, "skin", "", "Dark Green", "Black", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(24, 98, 40, 250), new Color4(9, 100, 127, 250), new Color4(61, 93, 134, 250), new Color4(70, 29, 27, 250), new Color4(115, 75, 65, 250), new Color4(100, 100, 100, 250), new Color4(91, 80, 74, 250), new Color4(112, 42, 76, 250), new Color4(14, 14, 14, 250) }))); Params.put(715, new VisualParam(715, "Nail Polish Color", 0, "skin", "", "Pink", "Black", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(255, 187, 200, 255), new Color4(194, 102, 127, 255), new Color4(227, 34, 99, 255), new Color4(168, 41, 60, 255), new Color4(97, 28, 59, 255), new Color4(234, 115, 93, 255), new Color4(142, 58, 47, 255), new Color4(114, 30, 46, 255), new Color4(14, 14, 14, 255) }))); Params.put(750, new VisualParam(750, "Eyebrow Density", 0, "hair", "", "Sparse", "Dense", 0.7f, 0f, 1f, false, new int[] { 1002, 1003 }, null, null)); Params.put(751, new VisualParam(751, "5 O'Clock Shadow", 1, "hair", "", "Dense hair", "Shadow hair", 0.7f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Blend, new Color4[] { new Color4(255, 255, 255, 255), new Color4(255, 255, 255, 30) }))); Params.put(752, new VisualParam(752, "Hair Thickness", 0, "hair", "", "5 O'Clock Shadow", "Bushy Hair", 0.5f, 0f, 1f, false, new int[] { 751, 1012, 400 }, null, null)); Params.put(753, new VisualParam(753, "Saddlebags", 0, "shape", "Saddle Bags", "Less Saddle", "More Saddle", 0f, -0.5f, 3f, false, new int[] { 850, 854 }, null, null)); Params.put(754, new VisualParam(754, "Hair_Taper_Back", 0, "hair", "Taper Back", "Wide Back", "Narrow Back", 0f, -1f, 2f, false, null, null, null)); Params.put(755, new VisualParam(755, "Hair_Taper_Front", 0, "hair", "Taper Front", "Wide Front", "Narrow Front", 0.05f, -1.5f, 1.5f, false, null, null, null)); Params.put(756, new VisualParam(756, "Neck Length", 0, "shape", "", "Short Neck", "Long Neck", 0f, -1f, 1f, false, null, null, null)); Params.put(757, new VisualParam(757, "Lower_Eyebrows", 0, "hair", "Eyebrow Height", "Higher", "Lower", -1f, -4f, 2f, false, new int[] { 871 }, null, null)); Params.put(758, new VisualParam(758, "Lower_Bridge_Nose", 0, "shape", "Lower Bridge", "Low", "High", -1.5f, -1.5f, 1.5f, false, null, null, null)); Params.put(759, new VisualParam(759, "Low_Septum_Nose", 0, "shape", "Nostril Division", "High", "Low", 0.5f, -1f, 1.5f, false, null, null, null)); Params.put(760, new VisualParam(760, "Jaw_Angle", 0, "shape", "Jaw Angle", "Low Jaw", "High Jaw", 0f, -1.2f, 2f, false, null, null, null)); Params.put(761, new VisualParam(761, "Hair_Volume_Small", 1, "hair", "Hair Volume", "Less", "More", 0f, 0f, 1.3f, false, null, null, null)); Params.put(762, new VisualParam(762, "Hair_Shear_Front", 0, "hair", "Shear Front", "Full Front", "Sheared Front", 0f, 0f, 3f, false, null, null, null)); Params.put(763, new VisualParam(763, "Hair Volume", 0, "hair", "", "Less Volume", "More Volume", 0.55f, 0f, 1f, false, new int[] { 761, 180 }, null, null)); Params.put(764, new VisualParam(764, "Lip_Cleft_Deep", 0, "shape", "Lip Cleft Depth", "Shallow", "Deep", -0.5f, -0.5f, 1.2f, false, null, null, null)); Params.put(765, new VisualParam(765, "Puffy_Lower_Lids", 0, "shape", "Puffy Eyelids", "Flat", "Puffy", -0.3f, -0.3f, 2.5f, false, null, null, null)); Params.put(767, new VisualParam(767, "Bug_Eyed_Head", 1, "shape", "Eye Depth", "Sunken Eyes", "Bug Eyes", 0f, -2f, 2f, false, null, null, null)); Params.put(768, new VisualParam(768, "EyeBone_Bug", 1, "shape", "", "Eyes Sunken", "Eyes Bugged", -2f, -2f, 2f, false, null, null, null)); Params.put(769, new VisualParam(769, "Eye Depth", 0, "shape", "", "Sunken Eyes", "Bugged Eyes", 0.5f, 0f, 1f, false, new int[] { 767, 768 }, null, null)); Params.put(770, new VisualParam(770, "Elongate_Head", 1, "shape", "Shear Face", "Flat Head", "Long Head", 0f, -1f, 1f, false, null, null, null)); Params.put(771, new VisualParam(771, "Elongate_Head_Hair", 1, "hair", "", "", "", -1f, -1f, 1f, false, null, null, null)); Params.put(772, new VisualParam(772, "EyeBone_Head_Elongate", 1, "shape", "", "Eyes Short Head", "Eyes Long Head", -1f, -1f, 1f, false, null, null, null)); Params.put(773, new VisualParam(773, "Head Length", 0, "shape", "", "Flat Head", "Long Head", 0.5f, 0f, 1f, false, new int[] { 770, 771, 772 }, null, null)); Params.put(774, new VisualParam(774, "Shear_Head_Hair", 1, "hair", "", "", "", -2f, -2f, 2f, false, null, null, null)); Params.put(775, new VisualParam(775, "Body Freckles", 0, "skin", "", "Less Freckles", "More Freckles", 0f, 0f, 1f, false, new int[] { 776, 777 }, null, null)); Params.put(778, new VisualParam(778, "Collar Back Height Cloth", 1, "shirt", "", "", "", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_collar_back_alpha.tga", false, true), null)); Params.put(779, new VisualParam(779, "Collar Back", 0, "undershirt", "", "Low", "High", 0.84f, 0f, 1f, false, new int[] { 1048, 1049 }, null, null)); Params.put(780, new VisualParam(780, "Collar Back", 0, "jacket", "", "Low", "High", 0.8f, 0f, 1f, false, new int[] { 1023, 1041, 1024 }, null, null)); Params.put(781, new VisualParam(781, "Collar Back", 0, "shirt", "", "Low", "High", 0.78f, 0f, 1f, false, new int[] { 778, 1016, 1032, 903 }, null, null)); Params.put(782, new VisualParam(782, "Hair_Pigtails_Short", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(783, new VisualParam(783, "Hair_Pigtails_Med", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(784, new VisualParam(784, "Hair_Pigtails_Long", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(785, new VisualParam(785, "Pigtails", 0, "hair", "", "Short Pigtails", "Long Pigtails", 0f, 0f, 1f, false, new int[] { 782, 783, 790, 784 }, null, null)); Params.put(786, new VisualParam(786, "Hair_Ponytail_Short", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(787, new VisualParam(787, "Hair_Ponytail_Med", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(788, new VisualParam(788, "Hair_Ponytail_Long", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(789, new VisualParam(789, "Ponytail", 0, "hair", "", "Short Ponytail", "Long Ponytail", 0f, 0f, 1f, false, new int[] { 786, 787, 788 }, null, null)); Params.put(790, new VisualParam(790, "Hair_Pigtails_Medlong", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(793, new VisualParam(793, "Leg_Longcuffs", 1, "pants", "Longcuffs", "", "", 0f, 0f, 3f, false, null, null, null)); Params.put(794, new VisualParam(794, "Small_Butt", 1, "shape", "Butt Size", "Regular", "Small", 0f, 0f, 1f, false, null, null, null)); Params.put(795, new VisualParam(795, "Butt Size", 0, "shape", "Butt Size", "Flat Butt", "Big Butt", 0.25f, 0f, 1f, false, new int[] { 867, 794, 151, 852 }, null, null)); Params.put(796, new VisualParam(796, "Pointy_Ears", 0, "shape", "Ear Tips", "Flat", "Pointy", -0.4f, -0.4f, 3f, false, null, null, null)); Params.put(797, new VisualParam(797, "Fat_Upper_Lip", 1, "shape", "Fat Upper Lip", "Normal Upper", "Fat Upper", 0f, 0f, 1.5f, false, null, null, null)); Params.put(798, new VisualParam(798, "Fat_Lower_Lip", 1, "shape", "Fat Lower Lip", "Normal Lower", "Fat Lower", 0f, 0f, 1.5f, false, null, null, null)); Params.put(799, new VisualParam(799, "Lip Ratio", 0, "shape", "Lip Ratio", "More Upper Lip", "More Lower Lip", 0.5f, 0f, 1f, false, new int[] { 797, 798 }, null, null)); Params.put(800, new VisualParam(800, "Sleeve Length", 0, "shirt", "", "Short", "Long", 0.89f, 0f, 1f, false, new int[] { 600, 1013, 1029, 900 }, null, null)); Params.put(801, new VisualParam(801, "Shirt Bottom", 0, "shirt", "", "Short", "Long", 1f, 0f, 1f, false, new int[] { 601, 1014, 1030, 901 }, null, null)); Params.put(802, new VisualParam(802, "Collar Front", 0, "shirt", "", "Low", "High", 0.78f, 0f, 1f, false, new int[] { 602, 1015, 1031, 902 }, null, null)); Params.put(803, new VisualParam(803, "shirt_red", 0, "shirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(804, new VisualParam(804, "shirt_green", 0, "shirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(805, new VisualParam(805, "shirt_blue", 0, "shirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(806, new VisualParam(806, "pants_red", 0, "pants", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(807, new VisualParam(807, "pants_green", 0, "pants", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(808, new VisualParam(808, "pants_blue", 0, "pants", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(809, new VisualParam(809, "lower_jacket_red", 1, "jacket", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(810, new VisualParam(810, "lower_jacket_green", 1, "jacket", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(811, new VisualParam(811, "lower_jacket_blue", 1, "jacket", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(812, new VisualParam(812, "shoes_red", 0, "shoes", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(813, new VisualParam(813, "shoes_green", 0, "shoes", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(814, new VisualParam(814, "Waist Height", 0, "pants", "", "Low", "High", 1f, 0f, 1f, false, new int[] { 614, 1017, 1035, 914 }, null, null)); Params.put(815, new VisualParam(815, "Pants Length", 0, "pants", "", "Short", "Long", 0.8f, 0f, 1f, false, new int[] { 615, 1018, 1036, 793, 915 }, null, null)); Params.put(816, new VisualParam(816, "Loose Lower Clothing", 0, "pants", "Pants Fit", "Tight Pants", "Loose Pants", 0f, 0f, 1f, false, new int[] { 516, 913 }, null, null)); Params.put(817, new VisualParam(817, "shoes_blue", 0, "shoes", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(818, new VisualParam(818, "socks_red", 0, "socks", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(819, new VisualParam(819, "socks_green", 0, "socks", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(820, new VisualParam(820, "socks_blue", 0, "socks", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(821, new VisualParam(821, "undershirt_red", 0, "undershirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(822, new VisualParam(822, "undershirt_green", 0, "undershirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(823, new VisualParam(823, "undershirt_blue", 0, "undershirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(824, new VisualParam(824, "underpants_red", 0, "underpants", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(825, new VisualParam(825, "underpants_green", 0, "underpants", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(826, new VisualParam(826, "underpants_blue", 0, "underpants", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(827, new VisualParam(827, "gloves_red", 0, "gloves", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(828, new VisualParam(828, "Loose Upper Clothing", 0, "shirt", "Shirt Fit", "Tight Shirt", "Loose Shirt", 0f, 0f, 1f, false, new int[] { 628, 899 }, null, null)); Params.put(829, new VisualParam(829, "gloves_green", 0, "gloves", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(830, new VisualParam(830, "gloves_blue", 0, "gloves", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(831, new VisualParam(831, "upper_jacket_red", 1, "jacket", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(832, new VisualParam(832, "upper_jacket_green", 1, "jacket", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(833, new VisualParam(833, "upper_jacket_blue", 1, "jacket", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(834, new VisualParam(834, "jacket_red", 0, "jacket", "", "", "", 1f, 0f, 1f, false, new int[] { 809, 831 }, null, null)); Params.put(835, new VisualParam(835, "jacket_green", 0, "jacket", "", "", "", 1f, 0f, 1f, false, new int[] { 810, 832 }, null, null)); Params.put(836, new VisualParam(836, "jacket_blue", 0, "jacket", "", "", "", 1f, 0f, 1f, false, new int[] { 811, 833 }, null, null)); Params.put(840, new VisualParam(840, "Shirtsleeve_flair", 0, "shirt", "Sleeve Looseness", "Tight Sleeves", "Loose Sleeves", 0f, 0f, 1.5f, false, null, null, null)); Params.put(841, new VisualParam(841, "Bowed_Legs", 0, "shape", "Knee Angle", "Knock Kneed", "Bow Legged", 0f, -1f, 1f, false, new int[] { 853, 847 }, null, null)); Params.put(842, new VisualParam(842, "Hip Length", 0, "shape", "", "Short hips", "Long Hips", -1f, -1f, 1f, false, null, null, null)); Params.put(843, new VisualParam(843, "No_Chest", 1, "shape", "Chest Size", "Some", "None", 0f, 0f, 1f, false, null, null, null)); Params.put(844, new VisualParam(844, "Glove Fingers", 0, "gloves", "", "Fingerless", "Fingers", 1f, 0.01f, 1f, false, new int[] { 1060, 1061 }, null, null)); Params.put(845, new VisualParam(845, "skirt_poofy", 1, "skirt", "poofy skirt", "less poofy", "more poofy", 0f, 0f, 1.5f, false, null, null, null)); Params.put(846, new VisualParam(846, "skirt_loose", 1, "skirt", "loose skirt", "form fitting", "loose", 0f, 0f, 1f, false, null, null, null)); Params.put(847, new VisualParam(847, "skirt_bowlegs", 1, "skirt", "legs skirt", "", "", 0f, -1f, 1f, false, null, null, null)); Params.put(848, new VisualParam(848, "skirt_bustle", 0, "skirt", "bustle skirt", "no bustle", "more bustle", 0.2f, 0f, 2f, false, null, null, null)); Params.put(849, new VisualParam(849, "skirt_belly", 1, "skirt", "big belly skirt", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(850, new VisualParam(850, "skirt_saddlebags", 1, "skirt", "", "", "", -0.5f, -0.5f, 3f, false, null, null, null)); Params.put(851, new VisualParam(851, "skirt_chubby", 1, "skirt", "", "less", "more", 0f, 0f, 1f, false, null, null, null)); Params.put(852, new VisualParam(852, "skirt_bigbutt", 1, "skirt", "bigbutt skirt", "less", "more", 0f, 0f, 1f, false, null, null, null)); Params.put(854, new VisualParam(854, "Saddlebags", 1, "shape", "", "", "", -0.5f, -0.5f, 3f, false, null, null, null)); Params.put(855, new VisualParam(855, "Love_Handles", 1, "shape", "", "", "", 0f, -1f, 2f, false, null, null, null)); Params.put(856, new VisualParam(856, "skirt_lovehandles", 1, "skirt", "", "less", "more", 0f, -1f, 2f, false, null, null, null)); Params.put(857, new VisualParam(857, "skirt_male", 1, "skirt", "", "", "", 0f, 0f, 1f, false, null, null, null)); Params.put(858, new VisualParam(858, "Skirt Length", 0, "skirt", "", "Short", "Long", 0.4f, 0.01f, 1f, false, null, new VisualAlphaParam(0f, "skirt_length_alpha.tga", false, true), null)); Params.put(859, new VisualParam(859, "Slit Front", 0, "skirt", "", "Open Front", "Closed Front", 1f, 0f, 1f, false, null, new VisualAlphaParam(0f, "skirt_slit_front_alpha.tga", false, true), null)); Params.put(860, new VisualParam(860, "Slit Back", 0, "skirt", "", "Open Back", "Closed Back", 1f, 0f, 1f, false, null, new VisualAlphaParam(0f, "skirt_slit_back_alpha.tga", false, true), null)); Params.put(861, new VisualParam(861, "Slit Left", 0, "skirt", "", "Open Left", "Closed Left", 1f, 0f, 1f, false, null, new VisualAlphaParam(0f, "skirt_slit_left_alpha.tga", false, true), null)); Params.put(862, new VisualParam(862, "Slit Right", 0, "skirt", "", "Open Right", "Closed Right", 1f, 0f, 1f, false, null, new VisualAlphaParam(0f, "skirt_slit_right_alpha.tga", false, true), null)); Params.put(863, new VisualParam(863, "skirt_looseness", 0, "skirt", "Skirt Fit", "Tight Skirt", "Poofy Skirt", 0.333f, 0f, 1f, false, new int[] { 866, 846, 845 }, null, null)); Params.put(866, new VisualParam(866, "skirt_tight", 1, "skirt", "tight skirt", "form fitting", "loose", 0f, 0f, 1f, false, null, null, null)); Params.put(867, new VisualParam(867, "skirt_smallbutt", 1, "skirt", "tight skirt", "form fitting", "loose", 0f, 0f, 1f, false, null, null, null)); Params.put(868, new VisualParam(868, "Shirt Wrinkles", 0, "shirt", "", "", "", 0f, 0f, 1f, true, null, null, null)); Params.put(869, new VisualParam(869, "Pants Wrinkles", 0, "pants", "", "", "", 0f, 0f, 1f, true, null, null, null)); Params.put(870, new VisualParam(870, "Pointy_Eyebrows", 1, "hair", "Eyebrow Points", "Smooth", "Pointy", -0.5f, -0.5f, 1f, false, null, null, null)); Params.put(871, new VisualParam(871, "Lower_Eyebrows", 1, "hair", "Eyebrow Height", "Higher", "Lower", -2f, -2f, 2f, false, null, null, null)); Params.put(872, new VisualParam(872, "Arced_Eyebrows", 1, "hair", "Eyebrow Arc", "Flat", "Arced", 0f, 0f, 1f, false, null, null, null)); Params.put(873, new VisualParam(873, "Bump base", 1, "skin", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0f, "", false, false), null)); Params.put(874, new VisualParam(874, "Bump upperdef", 1, "skin", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0f, "", false, false), null)); Params.put(877, new VisualParam(877, "Jacket Wrinkles", 0, "jacket", "Jacket Wrinkles", "No Wrinkles", "Wrinkles", 0f, 0f, 1f, false, new int[] { 875, 876 }, null, null)); Params.put(878, new VisualParam(878, "Bump upperdef", 1, "skin", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0f, "", false, false), null)); Params.put(879, new VisualParam(879, "Male_Package", 0, "shape", "Package", "Coin Purse", "Duffle Bag", 0f, -0.5f, 2f, false, null, null, null)); Params.put(880, new VisualParam(880, "Eyelid_Inner_Corner_Up", 0, "shape", "Inner Eye Corner", "Corner Down", "Corner Up", -1.3f, -1.3f, 1.2f, false, null, null, null)); Params.put(899, new VisualParam(899, "Upper Clothes Shading", 1, "shirt", "", "", "", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 80) }))); Params.put(900, new VisualParam(900, "Sleeve Length Shadow", 1, "shirt", "", "", "", 0.02f, 0.02f, 0.87f, false, null, new VisualAlphaParam(0.03f, "shirt_sleeve_alpha.tga", true, false), null)); Params.put(901, new VisualParam(901, "Shirt Shadow Bottom", 1, "shirt", "", "", "", 0.02f, 0.02f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_bottom_alpha.tga", true, true), null)); Params.put(902, new VisualParam(902, "Collar Front Shadow Height", 1, "shirt", "", "", "", 0.02f, 0.02f, 1f, false, null, new VisualAlphaParam(0.02f, "shirt_collar_alpha.tga", true, true), null)); Params.put(903, new VisualParam(903, "Collar Back Shadow Height", 1, "shirt", "", "", "", 0.02f, 0.02f, 1f, false, null, new VisualAlphaParam(0.02f, "shirt_collar_back_alpha.tga", true, true), null)); Params.put(913, new VisualParam(913, "Lower Clothes Shading", 1, "pants", "", "", "", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 0), new Color4(0, 0, 0, 80) }))); Params.put(914, new VisualParam(914, "Waist Height Shadow", 1, "pants", "", "", "", 0.02f, 0.02f, 1f, false, null, new VisualAlphaParam(0.04f, "pants_waist_alpha.tga", true, false), null)); Params.put(915, new VisualParam(915, "Pants Length Shadow", 1, "pants", "", "", "", 0.02f, 0.02f, 1f, false, null, new VisualAlphaParam(0.03f, "pants_length_alpha.tga", true, false), null)); Params.put(921, new VisualParam(921, "skirt_red", 0, "skirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(922, new VisualParam(922, "skirt_green", 0, "skirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(923, new VisualParam(923, "skirt_blue", 0, "skirt", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(1000, new VisualParam(1000, "Eyebrow Size Bump", 1, "hair", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.1f, "eyebrows_alpha.tga", false, false), null)); Params.put(1001, new VisualParam(1001, "Eyebrow Size", 1, "hair", "", "", "", 0.5f, 0f, 1f, false, null, new VisualAlphaParam(0.1f, "eyebrows_alpha.tga", false, false), null)); Params.put(1002, new VisualParam(1002, "Eyebrow Density Bump", 1, "hair", "", "", "", 0f, 0f, 1f, true, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(255, 255, 255, 0), new Color4(255, 255, 255, 255) }))); Params.put(1003, new VisualParam(1003, "Eyebrow Density", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Blend, new Color4[] { new Color4(255, 255, 255, 0), new Color4(255, 255, 255, 255) }))); Params.put(1004, new VisualParam(1004, "Sideburns bump", 1, "hair", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "facehair_sideburns_alpha.tga", true, false), null)); Params.put(1005, new VisualParam(1005, "Sideburns", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "facehair_sideburns_alpha.tga", true, false), null)); Params.put(1006, new VisualParam(1006, "Moustache bump", 1, "hair", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "facehair_moustache_alpha.tga", true, false), null)); Params.put(1007, new VisualParam(1007, "Moustache", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "facehair_moustache_alpha.tga", true, false), null)); Params.put(1008, new VisualParam(1008, "Soulpatch bump", 1, "hair", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.1f, "facehair_soulpatch_alpha.tga", true, false), null)); Params.put(1009, new VisualParam(1009, "Soulpatch", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.1f, "facehair_soulpatch_alpha.tga", true, false), null)); Params.put(1010, new VisualParam(1010, "Chin Curtains bump", 1, "hair", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.03f, "facehair_chincurtains_alpha.tga", true, false), null)); Params.put(1011, new VisualParam(1011, "Chin Curtains", 1, "hair", "", "", "", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.03f, "facehair_chincurtains_alpha.tga", true, false), null)); Params.put(1012, new VisualParam(1012, "5 O'Clock Shadow bump", 1, "hair", "", "", "", 0f, 0f, 1f, true, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(255, 255, 255, 255), new Color4(255, 255, 255, 0) }))); Params.put(1013, new VisualParam(1013, "Sleeve Length Cloth", 1, "shirt", "", "", "", 0f, 0f, 0.85f, true, null, new VisualAlphaParam(0.01f, "shirt_sleeve_alpha.tga", false, false), null)); Params.put(1014, new VisualParam(1014, "Shirt Bottom Cloth", 1, "shirt", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_bottom_alpha.tga", false, true), null)); Params.put(1015, new VisualParam(1015, "Collar Front Height Cloth", 1, "shirt", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_alpha.tga", false, true), null)); Params.put(1016, new VisualParam(1016, "Collar Back Height Cloth", 1, "shirt", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_back_alpha.tga", false, true), null)); Params.put(1017, new VisualParam(1017, "Waist Height Cloth", 1, "pants", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "pants_waist_alpha.tga", false, false), null)); Params.put(1018, new VisualParam(1018, "Pants Length Cloth", 1, "pants", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "pants_length_alpha.tga", false, false), null)); Params.put(1019, new VisualParam(1019, "Jacket Sleeve Length bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "shirt_sleeve_alpha.tga", false, false), null)); Params.put(1020, new VisualParam(1020, "jacket Sleeve Length", 1, "jacket", "", "", "", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "shirt_sleeve_alpha.tga", false, false), null)); Params.put(1021, new VisualParam(1021, "Jacket Collar Front bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_alpha.tga", false, true), null)); Params.put(1022, new VisualParam(1022, "jacket Collar Front", 1, "jacket", "", "", "", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_collar_alpha.tga", false, true), null)); Params.put(1023, new VisualParam(1023, "Jacket Collar Back bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_back_alpha.tga", false, true), null)); Params.put(1024, new VisualParam(1024, "jacket Collar Back", 1, "jacket", "", "", "", 0f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_collar_back_alpha.tga", false, true), null)); Params.put(1025, new VisualParam(1025, "jacket bottom length upper bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "jacket_length_upper_alpha.tga", false, true), null)); Params.put(1026, new VisualParam(1026, "jacket open upper bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "jacket_open_upper_alpha.tga", false, true), null)); Params.put(1027, new VisualParam(1027, "jacket bottom length lower bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "jacket_length_lower_alpha.tga", false, false), null)); Params.put(1028, new VisualParam(1028, "jacket open lower bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "jacket_open_lower_alpha.tga", false, true), null)); Params.put(1029, new VisualParam(1029, "Sleeve Length Cloth", 1, "shirt", "", "", "", 0f, 0f, 0.85f, true, null, new VisualAlphaParam(0.01f, "shirt_sleeve_alpha.tga", false, false), null)); Params.put(1030, new VisualParam(1030, "Shirt Bottom Cloth", 1, "shirt", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_bottom_alpha.tga", false, true), null)); Params.put(1031, new VisualParam(1031, "Collar Front Height Cloth", 1, "shirt", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_alpha.tga", false, true), null)); Params.put(1032, new VisualParam(1032, "Collar Back Height Cloth", 1, "shirt", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_back_alpha.tga", false, true), null)); Params.put(1033, new VisualParam(1033, "jacket bottom length lower bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "jacket_length_lower_alpha.tga", false, false), null)); Params.put(1034, new VisualParam(1034, "jacket open lower bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "jacket_open_lower_alpha.tga", false, true), null)); Params.put(1035, new VisualParam(1035, "Waist Height Cloth", 1, "pants", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "pants_waist_alpha.tga", false, false), null)); Params.put(1036, new VisualParam(1036, "Pants Length Cloth", 1, "pants", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "pants_length_alpha.tga", false, false), null)); Params.put(1037, new VisualParam(1037, "jacket bottom length upper bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "jacket_length_upper_alpha.tga", false, true), null)); Params.put(1038, new VisualParam(1038, "jacket open upper bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "jacket_open_upper_alpha.tga", false, true), null)); Params.put(1039, new VisualParam(1039, "Jacket Sleeve Length bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "shirt_sleeve_alpha.tga", false, false), null)); Params.put(1040, new VisualParam(1040, "Jacket Collar Front bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_alpha.tga", false, true), null)); Params.put(1041, new VisualParam(1041, "Jacket Collar Back bump", 1, "jacket", "", "", "", 0f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_back_alpha.tga", false, true), null)); Params.put(1042, new VisualParam(1042, "Sleeve Length", 1, "undershirt", "", "", "", 0.4f, 0.01f, 1f, false, null, new VisualAlphaParam(0.01f, "shirt_sleeve_alpha.tga", false, false), null)); Params.put(1043, new VisualParam(1043, "Sleeve Length bump", 1, "undershirt", "", "", "", 0.4f, 0.01f, 1f, true, null, new VisualAlphaParam(0.01f, "shirt_sleeve_alpha.tga", false, false), null)); Params.put(1044, new VisualParam(1044, "Bottom", 1, "undershirt", "", "", "", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_bottom_alpha.tga", false, true), null)); Params.put(1045, new VisualParam(1045, "Bottom bump", 1, "undershirt", "", "", "", 0.8f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_bottom_alpha.tga", false, true), null)); Params.put(1046, new VisualParam(1046, "Collar Front", 1, "undershirt", "", "", "", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_collar_alpha.tga", false, true), null)); Params.put(1047, new VisualParam(1047, "Collar Front bump", 1, "undershirt", "", "", "", 0.8f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_alpha.tga", false, true), null)); Params.put(1048, new VisualParam(1048, "Collar Back", 1, "undershirt", "", "Low", "High", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "shirt_collar_back_alpha.tga", false, true), null)); Params.put(1049, new VisualParam(1049, "Collar Back bump", 1, "undershirt", "", "", "", 0.8f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "shirt_collar_back_alpha.tga", false, true), null)); Params.put(1050, new VisualParam(1050, "Socks Length bump", 1, "socks", "", "", "", 0.35f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "shoe_height_alpha.tga", false, false), null)); Params.put(1051, new VisualParam(1051, "Socks Length bump", 1, "socks", "", "", "", 0.35f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "shoe_height_alpha.tga", false, false), null)); Params.put(1052, new VisualParam(1052, "Shoe Height", 1, "shoes", "", "", "", 0.1f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "shoe_height_alpha.tga", false, false), null)); Params.put(1053, new VisualParam(1053, "Shoe Height bump", 1, "shoes", "", "", "", 0.1f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "shoe_height_alpha.tga", false, false), null)); Params.put(1054, new VisualParam(1054, "Pants Length", 1, "underpants", "", "", "", 0.3f, 0f, 1f, false, null, new VisualAlphaParam(0.01f, "pants_length_alpha.tga", false, false), null)); Params.put(1055, new VisualParam(1055, "Pants Length", 1, "underpants", "", "", "", 0.3f, 0f, 1f, true, null, new VisualAlphaParam(0.01f, "pants_length_alpha.tga", false, false), null)); Params.put(1056, new VisualParam(1056, "Pants Waist", 1, "underpants", "", "", "", 0.8f, 0f, 1f, false, null, new VisualAlphaParam(0.05f, "pants_waist_alpha.tga", false, false), null)); Params.put(1057, new VisualParam(1057, "Pants Waist", 1, "underpants", "", "", "", 0.8f, 0f, 1f, true, null, new VisualAlphaParam(0.05f, "pants_waist_alpha.tga", false, false), null)); Params.put(1058, new VisualParam(1058, "Glove Length", 1, "gloves", "", "", "", 0.8f, 0.01f, 1f, false, null, new VisualAlphaParam(0.01f, "glove_length_alpha.tga", false, false), null)); Params.put(1059, new VisualParam(1059, "Glove Length bump", 1, "gloves", "", "", "", 0.8f, 0.01f, 1f, true, null, new VisualAlphaParam(0.01f, "glove_length_alpha.tga", false, false), null)); Params.put(1060, new VisualParam(1060, "Glove Fingers", 1, "gloves", "", "", "", 1f, 0.01f, 1f, false, null, new VisualAlphaParam(0.01f, "gloves_fingers_alpha.tga", false, true), null)); Params.put(1061, new VisualParam(1061, "Glove Fingers bump", 1, "gloves", "", "", "", 1f, 0.01f, 1f, true, null, new VisualAlphaParam(0.01f, "gloves_fingers_alpha.tga", false, true), null)); Params.put(1062, new VisualParam(1062, "tattoo_head_red", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(1063, new VisualParam(1063, "tattoo_head_green", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(1064, new VisualParam(1064, "tattoo_head_blue", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(1065, new VisualParam(1065, "tattoo_upper_red", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(1066, new VisualParam(1066, "tattoo_upper_green", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(1067, new VisualParam(1067, "tattoo_upper_blue", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(1068, new VisualParam(1068, "tattoo_lower_red", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(255, 0, 0, 255) }))); Params.put(1069, new VisualParam(1069, "tattoo_lower_green", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 255, 0, 255) }))); Params.put(1070, new VisualParam(1070, "tattoo_lower_blue", 1, "tattoo", "", "", "", 1f, 0f, 1f, false, null, null, new VisualColorParam(VisualColorOperation.Add, new Color4[] { new Color4(0, 0, 0, 255), new Color4(0, 0, 255, 255) }))); Params.put(1071, new VisualParam(1071, "tattoo_red", 2, "tattoo", "", "", "", 1f, 0f, 1f, false, new int[] { 1062, 1065, 1068 }, null, null)); Params.put(1072, new VisualParam(1072, "tattoo_green", 2, "tattoo", "", "", "", 1f, 0f, 1f, false, new int[] { 1063, 1066, 1069 }, null, null)); Params.put(1073, new VisualParam(1073, "tattoo_blue", 2, "tattoo", "", "", "", 1f, 0f, 1f, false, new int[] { 1064, 1067, 1070 }, null, null)); Params.put(1200, new VisualParam(1200, "Breast_Physics_UpDown_Driven", 1, "shape", "", "", "", 0f, -3f, 3f, false, null, null, null)); Params.put(1201, new VisualParam(1201, "Breast_Physics_InOut_Driven", 1, "shape", "", "", "", 0f, -1.25f, 1.25f, false, null, null, null)); Params.put(1202, new VisualParam(1202, "Belly_Physics_Legs_UpDown_Driven", 1, "physics", "", "", "", -1f, -1f, 1f, false, null, null, null)); Params.put(1203, new VisualParam(1203, "Belly_Physics_Skirt_UpDown_Driven", 1, "physics", "", "", "", 0f, -1f, 1f, false, null, null, null)); Params.put(1204, new VisualParam(1204, "Belly_Physics_Torso_UpDown_Driven", 1, "physics", "", "", "", 0f, -1f, 1f, false, null, null, null)); Params.put(1205, new VisualParam(1205, "Butt_Physics_UpDown_Driven", 1, "physics", "", "", "", 0f, -1f, 1f, false, null, null, null)); Params.put(1206, new VisualParam(1206, "Butt_Physics_LeftRight_Driven", 1, "physics", "", "", "", 0f, -1f, 1f, false, null, null, null)); Params.put(1207, new VisualParam(1207, "Breast_Physics_LeftRight_Driven", 1, "physics", "", "", "", 0f, -2f, 2f, false, null, null, null)); Params.put(10000, new VisualParam(10000, "Breast_Physics_Mass", 0, "physics", "Breast Physics Mass", "", "", 0.1f, 0.1f, 1f, false, null, null, null)); Params.put(10001, new VisualParam(10001, "Breast_Physics_Gravity", 0, "physics", "Breast Physics Gravity", "", "", 0f, 0f, 30f, false, null, null, null)); Params.put(10002, new VisualParam(10002, "Breast_Physics_Drag", 0, "physics", "Breast Physics Drag", "", "", 1f, 0f, 10f, false, null, null, null)); Params.put(10003, new VisualParam(10003, "Breast_Physics_UpDown_Max_Effect", 0, "physics", "Breast Physics UpDown Max Effect", "", "", 0f, 0f, 3f, false, null, null, null)); Params.put(10004, new VisualParam(10004, "Breast_Physics_UpDown_Spring", 0, "physics", "Breast Physics UpDown Spring", "", "", 10f, 0f, 100f, false, null, null, null)); Params.put(10005, new VisualParam(10005, "Breast_Physics_UpDown_Gain", 0, "physics", "Breast Physics UpDown Gain", "", "", 10f, 1f, 100f, false, null, null, null)); Params.put(10006, new VisualParam(10006, "Breast_Physics_UpDown_Damping", 0, "physics", "Breast Physics UpDown Damping", "", "", 0.2f, 0f, 1f, false, null, null, null)); Params.put(10007, new VisualParam(10007, "Breast_Physics_InOut_Max_Effect", 0, "physics", "Breast Physics InOut Max Effect", "", "", 0f, 0f, 3f, false, null, null, null)); Params.put(10008, new VisualParam(10008, "Breast_Physics_InOut_Spring", 0, "physics", "Breast Physics InOut Spring", "", "", 10f, 0f, 100f, false, null, null, null)); Params.put(10009, new VisualParam(10009, "Breast_Physics_InOut_Gain", 0, "physics", "Breast Physics InOut Gain", "", "", 10f, 1f, 100f, false, null, null, null)); Params.put(10010, new VisualParam(10010, "Breast_Physics_InOut_Damping", 0, "physics", "Breast Physics InOut Damping", "", "", 0.2f, 0f, 1f, false, null, null, null)); Params.put(10011, new VisualParam(10011, "Belly_Physics_Mass", 0, "physics", "Belly Physics Mass", "", "", 0.1f, 0.1f, 1f, false, null, null, null)); Params.put(10012, new VisualParam(10012, "Belly_Physics_Gravity", 0, "physics", "Belly Physics Gravity", "", "", 0f, 0f, 30f, false, null, null, null)); Params.put(10013, new VisualParam(10013, "Belly_Physics_Drag", 0, "physics", "Belly Physics Drag", "", "", 1f, 0f, 10f, false, null, null, null)); Params.put(10014, new VisualParam(10014, "Belly_Physics_UpDown_Max_Effect", 0, "physics", "Belly Physics UpDown Max Effect", "", "", 0f, 0f, 3f, false, null, null, null)); Params.put(10015, new VisualParam(10015, "Belly_Physics_UpDown_Spring", 0, "physics", "Belly Physics UpDown Spring", "", "", 10f, 0f, 100f, false, null, null, null)); Params.put(10016, new VisualParam(10016, "Belly_Physics_UpDown_Gain", 0, "physics", "Belly Physics UpDown Gain", "", "", 10f, 1f, 100f, false, null, null, null)); Params.put(10017, new VisualParam(10017, "Belly_Physics_UpDown_Damping", 0, "physics", "Belly Physics UpDown Damping", "", "", 0.2f, 0f, 1f, false, null, null, null)); Params.put(10018, new VisualParam(10018, "Butt_Physics_Mass", 0, "physics", "Butt Physics Mass", "", "", 0.1f, 0.1f, 1f, false, null, null, null)); Params.put(10019, new VisualParam(10019, "Butt_Physics_Gravity", 0, "physics", "Butt Physics Gravity", "", "", 0f, 0f, 30f, false, null, null, null)); Params.put(10020, new VisualParam(10020, "Butt_Physics_Drag", 0, "physics", "Butt Physics Drag", "", "", 1f, 0f, 10f, false, null, null, null)); Params.put(10021, new VisualParam(10021, "Butt_Physics_UpDown_Max_Effect", 0, "physics", "Butt Physics UpDown Max Effect", "", "", 0f, 0f, 3f, false, null, null, null)); Params.put(10022, new VisualParam(10022, "Butt_Physics_UpDown_Spring", 0, "physics", "Butt Physics UpDown Spring", "", "", 10f, 0f, 100f, false, null, null, null)); Params.put(10023, new VisualParam(10023, "Butt_Physics_UpDown_Gain", 0, "physics", "Butt Physics UpDown Gain", "", "", 10f, 1f, 100f, false, null, null, null)); Params.put(10024, new VisualParam(10024, "Butt_Physics_UpDown_Damping", 0, "physics", "Butt Physics UpDown Damping", "", "", 0.2f, 0f, 1f, false, null, null, null)); Params.put(10025, new VisualParam(10025, "Butt_Physics_LeftRight_Max_Effect", 0, "physics", "Butt Physics LeftRight Max Effect", "", "", 0f, 0f, 3f, false, null, null, null)); Params.put(10026, new VisualParam(10026, "Butt_Physics_LeftRight_Spring", 0, "physics", "Butt Physics LeftRight Spring", "", "", 10f, 0f, 100f, false, null, null, null)); Params.put(10027, new VisualParam(10027, "Butt_Physics_LeftRight_Gain", 0, "physics", "Butt Physics LeftRight Gain", "", "", 10f, 1f, 100f, false, null, null, null)); Params.put(10028, new VisualParam(10028, "Butt_Physics_LeftRight_Damping", 0, "physics", "Butt Physics LeftRight Damping", "", "", 0.2f, 0f, 1f, false, null, null, null)); Params.put(10029, new VisualParam(10029, "Breast_Physics_LeftRight_Max_Effect", 0, "physics", "Breast Physics LeftRight Max Effect", "", "", 0f, 0f, 3f, false, null, null, null)); Params.put(10030, new VisualParam(10030, "Breast_Physics_LeftRight_Spring", 0, "physics", "Breast Physics LeftRight Spring", "", "", 10f, 0f, 100f, false, null, null, null)); Params.put(10031, new VisualParam(10031, "Breast_Physics_LeftRight_Gain", 0, "physics", "Breast Physics LeftRight Gain", "", "", 10f, 1f, 100f, false, null, null, null)); Params.put(10032, new VisualParam(10032, "Breast_Physics_LeftRight_Damping", 0, "physics", "Breast Physics LeftRight Damping", "", "", 0.2f, 0f, 1f, false, null, null, null)); } }
lgpl-2.1
lucee/Lucee
core/src/main/java/lucee/runtime/functions/string/ReplaceNoCase.java
3453
/** * * 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); } }
lgpl-2.1
zhaozw/android-1
src/net/java/sip/communicator/service/protocol/event/WhiteboardParticipantEvent.java
3611
/* * 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(); } }
lgpl-2.1
raedle/univis
lib/hibernate-3.1.3/src/org/hibernate/engine/SessionFactoryImplementor.java
5315
//$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); }
lgpl-2.1
1fechner/FeatureExtractor
sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-spatial/src/main/java/org/hibernate/spatial/dialect/h2geodb/GeoDBGeometryTypeDescriptor.java
2853
/* * 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 ); } }; } }
lgpl-2.1
MobileConvergenceLab/icPhone-phoneapp
CCNVoice/src/CCNVoice.java
11864
/* * 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; } }
lgpl-2.1
EgorZhuk/pentaho-reporting
engine/core/src/main/java/org/pentaho/reporting/engine/classic/core/style/VerticalTextAlign.java
6057
/* * 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; } }
lgpl-2.1
timtiemens/secretshare
src/main/java/com/tiemens/secretshare/main/cli/MainBigIntCs.java
16433
/******************************************************************************* * 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 }
lgpl-2.1
bharathravi/tinysql
src/ORG/as220/tinySQL/util/ParameterPosition.java
1864
//============================================================================= /* $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; } }
lgpl-2.1
ironjacamar/ironjacamar
common/impl/src/main/java/org/jboss/jca/common/metadata/ds/DatasourcesImpl.java
6195
/* * 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())); } }
lgpl-2.1
Eladkay/Quaritum-as-is
src/main/java/com/outlookphone/quaritum/flora/EnumDye.java
252
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; } }
lgpl-2.1
geotools/geotools
modules/library/coverage/src/main/java/org/geotools/coverage/processing/operation/ExtendedRandomIter.java
3207
/* * 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(); } }
lgpl-2.1
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
23277
/* * 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 ); } }
lgpl-2.1
plast-lab/soot
src/main/java/soot/toolkits/graph/CompleteUnitGraph.java
3038
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); } }
lgpl-2.1
johnlee175/john4j
src/com/johnsoft/library/swing/component/gl/JohnGLRenderer.java
1405
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) { } }
lgpl-2.1
wolfc/jboss-common-beans
src/test/java/org/jboss/common/beans/property/AtomicIntegerEditorTestCase.java
2026
/* * 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(); } } }
lgpl-2.1
KurentoLegacy/kurento-media-framework
kmf-integration-tests/kmf-system-test/src/test/java/com/kurento/kmf/test/media/MediaApiWebRtc2HttpTest.java
4245
/* * (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(); } } }
lgpl-2.1
raffy1982/spine-project
Spine_apps/nodeEmulator/src/logic/SensorDataManager.java
9284
/***************************************************************** 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); } }
lgpl-2.1
jeremynorris/ddd-toolbox
dao/src/main/java/org/ddd/toolbox/dao/QueryFactoryCallback.java
468
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(); }
lgpl-2.1
EgorZhuk/pentaho-reporting
designer/report-designer/src/main/java/org/pentaho/reporting/designer/core/actions/report/export/ExportCsvAction.java
1180
/*! * 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.designer.core.actions.report.export; import org.pentaho.reporting.engine.classic.core.modules.gui.csv.CSVTableExportPlugin; /** * Todo: Document Me * * @author Ezequiel Cuellar */ public final class ExportCsvAction extends AbstractExportAction { public ExportCsvAction() { super( new CSVTableExportPlugin() ); } }
lgpl-2.1
Partysun/SE452-Tux-Guitar
TuxGuitar-viewer/src/org/herac/tuxguitar/app/Tests/SettingsActionTest.java
20032
package org.herac.tuxguitar.app.Tests; import java.awt.AWTEvent; import java.awt.event.ActionEvent; import java.awt.event.MouseEvent; import junit.framework.TestCase; import org.herac.tuxguitar.app.actions.settings.SettingsAction; import org.herac.tuxguitar.app.editors.TablatureEditor; import org.herac.tuxguitar.song.managers.TGSongManager; public class SettingsActionTest extends TestCase { /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.execute(AWTEvent)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testExecuteAWTEvent() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.SettingsAction()' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.settings.SettingsAction#SettingsAction())*/ public void testSettingsAction() { // Constructor under test SettingsAction constructorInstance = new SettingsAction(); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addViewMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddViewMenuJPopupMenu_Path1() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addViewMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddViewMenuJPopupMenu_Path2() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addViewMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddViewMenuJPopupMenu_Path3() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addViewMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddViewMenuJPopupMenu_Path4() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addViewMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddViewMenuJPopupMenu_Path5() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addViewMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddViewMenuJPopupMenu_Path6() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addViewMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddViewMenuJPopupMenu_Path7() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addViewMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddViewMenuJPopupMenu_Path8() { } /** Test method for 'org.herac.tuxguitar.app.actions.settings.SettingsAction.addSoundMenu(JPopupMenu)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testAddSoundMenuJPopupMenu() { } /** Test method for 'org.herac.tuxguitar.app.actions.Action.process(AWTEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#process(AWTEvent))*/ public void testProcessAWTEvent_Path1() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[47]!ActionLock.isLocked:TRUE *[47]!TuxGuitar.instance:.isLocked:TRUE *[48]!TuxGuitar.instance:.getTablatureEditor:.isStarted:FALSE *[54]flags&DISABLE_ON_PLAYING:!=0:TRUE *[54]TuxGuitar.instance:.getPlayer:.isRunning:TRUE *[55]flags&AUTO_UPDATE:!=0:TRUE ****************************************************************************/ // Method under test arguments AWTEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.process(e); fail("Path 1 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.process(AWTEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#process(AWTEvent))*/ public void testProcessAWTEvent_Path2() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[47]!ActionLock.isLocked:FALSE ****************************************************************************/ // Method under test arguments AWTEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.process(e); fail("Path 2 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.process(AWTEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#process(AWTEvent))*/ public void testProcessAWTEvent_Path3() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[47]!ActionLock.isLocked:TRUE *[47]!TuxGuitar.instance:.isLocked:FALSE ****************************************************************************/ // Method under test arguments AWTEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.process(e); fail("Path 3 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.process(AWTEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#process(AWTEvent))*/ public void testProcessAWTEvent_Path4() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[47]!ActionLock.isLocked:TRUE *[47]!TuxGuitar.instance:.isLocked:TRUE *[48]!TuxGuitar.instance:.getTablatureEditor:.isStarted:TRUE ****************************************************************************/ // Method under test arguments AWTEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.process(e); fail("Path 4 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.process(AWTEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#process(AWTEvent))*/ public void testProcessAWTEvent_Path5() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[47]!ActionLock.isLocked:TRUE *[47]!TuxGuitar.instance:.isLocked:TRUE *[48]!TuxGuitar.instance:.getTablatureEditor:.isStarted:FALSE *[54]flags&DISABLE_ON_PLAYING:!=0:FALSE *[59]flags&AUTO_LOCK:!=0:TRUE ****************************************************************************/ // Method under test arguments AWTEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.process(e); fail("Path 5 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.process(AWTEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#process(AWTEvent))*/ public void testProcessAWTEvent_Path6() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[47]!ActionLock.isLocked:TRUE *[47]!TuxGuitar.instance:.isLocked:TRUE *[48]!TuxGuitar.instance:.getTablatureEditor:.isStarted:FALSE *[54]flags&DISABLE_ON_PLAYING:!=0:TRUE *[54]TuxGuitar.instance:.getPlayer:.isRunning:FALSE *[59]flags&AUTO_LOCK:!=0:TRUE ****************************************************************************/ // Method under test arguments AWTEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.process(e); fail("Path 6 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.process(AWTEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#process(AWTEvent))*/ public void testProcessAWTEvent_Path7() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[47]!ActionLock.isLocked:TRUE *[47]!TuxGuitar.instance:.isLocked:TRUE *[48]!TuxGuitar.instance:.getTablatureEditor:.isStarted:FALSE *[54]flags&DISABLE_ON_PLAYING:!=0:TRUE *[54]TuxGuitar.instance:.getPlayer:.isRunning:TRUE *[55]flags&AUTO_UPDATE:!=0:FALSE ****************************************************************************/ // Method under test arguments AWTEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.process(e); fail("Path 7 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.process(AWTEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#process(AWTEvent))*/ public void testProcessAWTEvent_Path8() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[47]!ActionLock.isLocked:TRUE *[47]!TuxGuitar.instance:.isLocked:TRUE *[48]!TuxGuitar.instance:.getTablatureEditor:.isStarted:FALSE *[54]flags&DISABLE_ON_PLAYING:!=0:FALSE *[59]flags&AUTO_LOCK:!=0:FALSE ****************************************************************************/ // Method under test arguments AWTEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.process(e); fail("Path 8 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.getFlags()' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testGetFlags() { } /** Test method for 'org.herac.tuxguitar.app.actions.Action.getSongManager()' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#getSongManager())*/ public void testGetSongManager() { SettingsAction constructorInstance = new SettingsAction(); TGSongManager methodReturn = constructorInstance.getSongManager(); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.getEditor()' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#getEditor())*/ public void testGetEditor() { SettingsAction constructorInstance = new SettingsAction(); TablatureEditor methodReturn = constructorInstance.getEditor(); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.getName()' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#getName())*/ public void testGetName() { SettingsAction constructorInstance = new SettingsAction(); String methodReturn = constructorInstance.getName(); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.isKeyBindingAvailable()' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#isKeyBindingAvailable())*/ public void testIsKeyBindingAvailable_Path1() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[96]getFlags:&KEY_BINDING_AVAILABLE:!=0:TRUE ****************************************************************************/ // Method under test arguments SettingsAction constructorInstance = new SettingsAction(); boolean methodReturn = constructorInstance.isKeyBindingAvailable(); fail("Path 1 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.isKeyBindingAvailable()' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#isKeyBindingAvailable())*/ public void testIsKeyBindingAvailable_Path2() { /**************************************************************************** *This path executes an independent set of decisions listed below. *To fully unit test this path, * *(1) define the data that causes the decisions to evaluate as specified, *(2) and create the assertion. * *Format: [line number][decision]:[evaluates to] * *[96]getFlags:&KEY_BINDING_AVAILABLE:!=0:FALSE ****************************************************************************/ // Method under test arguments SettingsAction constructorInstance = new SettingsAction(); boolean methodReturn = constructorInstance.isKeyBindingAvailable(); fail("Path 2 assertion not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.updateTablature()' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#updateTablature())*/ public void testUpdateTablature() { SettingsAction constructorInstance = new SettingsAction(); constructorInstance.updateTablature(); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.Action.fireUpdate(int)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.Action#fireUpdate(int))*/ public void testFireUpdateInt() { // Method under test arguments int measureNumber = 0; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.fireUpdate(measureNumber); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.ActionAdapter.doProcess(AWTEvent)' * !!! Auto generated unit tests for non-public methods or in case of non-public class constructors are a premium feature. * Visit <a href="http://www.codign.com/purchase.html">Codign site</a> for details */ public void testDoProcessAWTEvent() { } /** Test method for 'org.herac.tuxguitar.app.actions.ActionAdapter.actionPerformed(ActionEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.ActionAdapter#actionPerformed(ActionEvent))*/ public void testActionPerformedActionEvent() { // Method under test arguments ActionEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.actionPerformed(e); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.ActionAdapter.mouseClicked(MouseEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.ActionAdapter#mouseClicked(MouseEvent))*/ public void testMouseClickedMouseEvent() { // Method under test arguments MouseEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.mouseClicked(e); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.ActionAdapter.mousePressed(MouseEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.ActionAdapter#mousePressed(MouseEvent))*/ public void testMousePressedMouseEvent() { // Method under test arguments MouseEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.mousePressed(e); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.ActionAdapter.mouseReleased(MouseEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.ActionAdapter#mouseReleased(MouseEvent))*/ public void testMouseReleasedMouseEvent() { // Method under test arguments MouseEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.mouseReleased(e); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.ActionAdapter.mouseEntered(MouseEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.ActionAdapter#mouseEntered(MouseEvent))*/ public void testMouseEnteredMouseEvent() { // Method under test arguments MouseEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.mouseEntered(e); fail("Test method not implemented."); } /** Test method for 'org.herac.tuxguitar.app.actions.ActionAdapter.mouseExited(MouseEvent)' @CoViewTest (coview_methodundertest=org.herac.tuxguitar.app.actions.ActionAdapter#mouseExited(MouseEvent))*/ public void testMouseExitedMouseEvent() { // Method under test arguments MouseEvent e = null; SettingsAction constructorInstance = new SettingsAction(); constructorInstance.mouseExited(e); fail("Test method not implemented."); } }
lgpl-2.1
cytoscape/cytoscape-impl
custom-graphics-internal/src/main/java/org/cytoscape/cg/model/CustomGraphicsUtil.java
945
package org.cytoscape.cg.model; import java.awt.Image; public class CustomGraphicsUtil { public static Image getResizedImage(Image original, Integer w, Integer h, boolean keepAspectRatio) { if (original == null) throw new IllegalArgumentException("Original image cannot be null."); if (w == null && h == null) return original; int currentW = original.getWidth(null); int currentH = original.getHeight(null); float ratio; int converted; if (keepAspectRatio == false) { return original.getScaledInstance(w, h, Image.SCALE_AREA_AVERAGING); } else if (h == null) { ratio = ((float) currentH) / ((float) currentW); converted = (int) (w * ratio); return original.getScaledInstance(w, converted, Image.SCALE_AREA_AVERAGING); } else { ratio = ((float) currentW) / ((float) currentH); converted = (int) (h * ratio); return original.getScaledInstance(converted, h, Image.SCALE_AREA_AVERAGING); } } }
lgpl-2.1
trainboy2019/1.7modrecove4r2
src/main/java/com/camp/block/NetherLapis.java
2215
package com.camp.block; import java.util.Random; import net.minecraft.block.Block; import net.minecraft.block.material.Material; import net.minecraft.creativetab.CreativeTabs; import net.minecraft.init.Items; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import com.camp.creativetabs.CreativeTabsManager; import com.camp.item.ItemManager; //import com.bedrockminer.tutorial.Main; import com.camp.lib.StringLibrary; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; public class NetherLapis extends Block { //"LapisItem" = new ItemStack(Items.dye, 1, 4); private ItemStack drop; private int meta; private int least_quantity; private int most_quantity; //("gemLapis", new ItemStack(Items.dye, 1, 4) protected NetherLapis(String unlocalizedName, Material mat, ItemStack gemLapisGem2, int meta, int least_quantity, int most_quantity) { super(mat); this.drop = gemLapisGem2; this.meta = meta; this.least_quantity = 1; this.most_quantity = 2; this.setLightLevel(0.0F); this.setBlockName(unlocalizedName); this.setBlockTextureName(StringLibrary.MODID + ":" + "nether_lapis"); this.setCreativeTab(CreativeTabsManager.tabBlock); } //ItemStack gemLapis = new ItemStack(Items.dye,1); ///ItemStack gemLapis = new ItemStack(Items.dye, 1, 4); setItemDamage(4); ItemStack gemLapisGem = new ItemStack(Items.dye, 1, 4); protected NetherLapis(String unlocalizedName, Material mat, ItemStack gemLapisGem2, int least_quantity, int most_quantity) { this(unlocalizedName, mat, gemLapisGem2, 0, least_quantity, most_quantity); } protected NetherLapis(String unlocalizedName, Material mat, net.minecraft.item.ItemStack drop) { this(unlocalizedName, mat, drop, 1, 1); } public ItemStack ItemStack (int meta, Random random, int fortune) { return gemLapisGem; } @Override public int damageDropped(int meta) { return meta; } @Override public int quantityDropped(int meta, int fortune, Random random) { if (this.least_quantity >= this.most_quantity) return this.least_quantity; return this.least_quantity + random.nextInt(this.most_quantity - this.least_quantity + fortune + 1); } }
lgpl-2.1
cristhiank/jasperreportsjsf
plugin/src/main/java/net/sf/jasperreports/jsf/context/JRFacesContextWrapper.java
3019
/* * JaspertReports JSF Plugin Copyright (C) 2011 A. Alonso Dominguez * * 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 A. * * Alonso Dominguez * alonsoft@users.sf.net */ package net.sf.jasperreports.jsf.context; import java.util.Collection; import javax.faces.component.UIComponent; import javax.faces.context.FacesContext; import net.sf.jasperreports.jsf.component.UIOutputReport; import net.sf.jasperreports.jsf.component.UIReport; import net.sf.jasperreports.jsf.convert.ReportConverter; import net.sf.jasperreports.jsf.convert.SourceConverter; import net.sf.jasperreports.jsf.engine.Exporter; import net.sf.jasperreports.jsf.engine.Filler; import net.sf.jasperreports.jsf.resource.Resource; /** * * @author A. Alonso Dominguez */ public abstract class JRFacesContextWrapper extends JRFacesContext { @Override public ReportConverter createReportConverter(FacesContext context, UIReport component) { return getWrapped().createReportConverter(context, component); } @Override public Resource createResource(FacesContext context, UIComponent component, String name) { return getWrapped().createResource(context, component, name); } @Override public SourceConverter createSourceConverter(FacesContext context, UIComponent component) { return getWrapped().createSourceConverter(context, component); } @Override public Collection<String> getAvailableExportFormats() { return getWrapped().getAvailableExportFormats(); } @Override public Collection<String> getAvailableSourceTypes() { return getWrapped().getAvailableSourceTypes(); } @Override public Exporter getExporter(FacesContext context, UIOutputReport component) { return getWrapped().getExporter(context, component); } @Override public ExternalContextHelper getExternalContextHelper(FacesContext context) { return getWrapped().getExternalContextHelper(context); } @Override public Filler getFiller(FacesContext context, UIOutputReport component) { return getWrapped().getFiller(context, component); } @Override public Collection<ContentType> getSupportedContentTypes() { return getWrapped().getSupportedContentTypes(); } protected abstract JRFacesContext getWrapped(); }
lgpl-2.1
ideaconsult/i5
iuclid_6_4-io/src/main/java/eu/europa/echa/iuclid6/namespaces/flexible_record_estimatedquantities/_6/ObjectFactory.java
11538
package eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6; import java.math.BigDecimal; import java.math.BigInteger; import javax.xml.bind.JAXBElement; import javax.xml.bind.annotation.XmlElementDecl; import javax.xml.bind.annotation.XmlRegistry; import javax.xml.namespace.QName; /** * This object contains factory methods for each * Java content interface and Java element interface * generated in the eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6 package. * <p>An ObjectFactory allows you to programatically * construct new instances of the Java representation * for XML content. The Java representation of XML * content can consist of schema derived interfaces * and classes representing the binding of schema * type definitions, element declarations and model * groups. Factory methods for each of these are * provided in this class. * */ @XmlRegistry public class ObjectFactory { private final static QName _FLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Imported"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Manufacturer"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageImportedArticles"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageProducedArticles"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageOwnUser"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageIntermediateTransporter"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageDirectlyExported"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "TonnageIntermediateOnsite"); private final static QName _FLEXIBLERECORDEstimatedQuantitiesYear_QNAME = new QName("http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", "Year"); /** * Create a new ObjectFactory that can be used to create new instances of schema derived classes for package: eu.europa.echa.iuclid6.namespaces.flexible_record_estimatedquantities._6 * */ public ObjectFactory() { } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities } * */ public FLEXIBLERECORDEstimatedQuantities createFLEXIBLERECORDEstimatedQuantities() { return new FLEXIBLERECORDEstimatedQuantities(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DataProtection } * */ public FLEXIBLERECORDEstimatedQuantities.DataProtection createFLEXIBLERECORDEstimatedQuantitiesDataProtection() { return new FLEXIBLERECORDEstimatedQuantities.DataProtection(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.TotalTonnage } * */ public FLEXIBLERECORDEstimatedQuantities.TotalTonnage createFLEXIBLERECORDEstimatedQuantitiesTotalTonnage() { return new FLEXIBLERECORDEstimatedQuantities.TotalTonnage(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DetailsTonnage } * */ public FLEXIBLERECORDEstimatedQuantities.DetailsTonnage createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnage() { return new FLEXIBLERECORDEstimatedQuantities.DetailsTonnage(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles } * */ public FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticles() { return new FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.AdditionalInformation } * */ public FLEXIBLERECORDEstimatedQuantities.AdditionalInformation createFLEXIBLERECORDEstimatedQuantitiesAdditionalInformation() { return new FLEXIBLERECORDEstimatedQuantities.AdditionalInformation(); } /** * Create an instance of {@link FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation } * */ public FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation createFLEXIBLERECORDEstimatedQuantitiesDataProtectionLegislation() { return new FLEXIBLERECORDEstimatedQuantities.DataProtection.Legislation(); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Imported", scope = FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTotalTonnageImported_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Manufacturer", scope = FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTotalTonnageManufacturer_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TotalTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageImportedArticles", scope = FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageImportedArticles_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageProducedArticles", scope = FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesTonnagesNotificationSubstancesInArticlesTonnageProducedArticles_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.TonnagesNotificationSubstancesInArticles.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageOwnUser", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageOwnUser_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageIntermediateTransporter", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateTransporter_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageDirectlyExported", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageDirectlyExported_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigDecimal }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "TonnageIntermediateOnsite", scope = FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class) public JAXBElement<BigDecimal> createFLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite(BigDecimal value) { return new JAXBElement<BigDecimal>(_FLEXIBLERECORDEstimatedQuantitiesDetailsTonnageTonnageIntermediateOnsite_QNAME, BigDecimal.class, FLEXIBLERECORDEstimatedQuantities.DetailsTonnage.class, value); } /** * Create an instance of {@link JAXBElement }{@code <}{@link BigInteger }{@code >}} * */ @XmlElementDecl(namespace = "http://iuclid6.echa.europa.eu/namespaces/FLEXIBLE_RECORD-EstimatedQuantities/6.0", name = "Year", scope = FLEXIBLERECORDEstimatedQuantities.class) public JAXBElement<BigInteger> createFLEXIBLERECORDEstimatedQuantitiesYear(BigInteger value) { return new JAXBElement<BigInteger>(_FLEXIBLERECORDEstimatedQuantitiesYear_QNAME, BigInteger.class, FLEXIBLERECORDEstimatedQuantities.class, value); } }
lgpl-3.0
nicosensei/batch-tools
batch-tools-elasticsearch/src/main/java/com/github/nicosensei/batch/elasticsearch/SkipLimitExceededException.java
525
/** * */ package com.github.nicosensei.batch.elasticsearch; import org.apache.log4j.Level; import com.github.nicosensei.batch.BatchException; /** * @author nicolas * */ public class SkipLimitExceededException extends BatchException { /** * */ private static final long serialVersionUID = 1095268691743122833L; public SkipLimitExceededException(final int skipLimit) { super( "OVER_SKIP_LIMIT", "Exceeded skip limit of {0}", new String[] { Integer.toString(skipLimit) }, Level.FATAL); } }
lgpl-3.0
Ash6390/JarCraft
src/main/java/com/ash6390/jarcraft/utility/LogHelper.java
920
package com.ash6390.jarcraft.utility; import com.ash6390.jarcraft.reference.References; import cpw.mods.fml.common.FMLLog; import org.apache.logging.log4j.Level; public class LogHelper { public static void log(Level logLevel, Object object) { FMLLog.log(References.NAME, logLevel, String.valueOf(object)); } public static void all(Object object) { log(Level.ALL, object); } public static void debug(Object object) { log(Level.DEBUG, object); } public static void error(Object object) { log(Level.ERROR, object); } public static void fatal(Object object) { log(Level.FATAL, object); } public static void info(Object object) { log(Level.INFO, object); } public static void off(Object object) { log(Level.OFF, object); } public static void trace(Object object) { log(Level.TRACE, object); } public static void warn(Object object) { log(Level.WARN, object); } }
lgpl-3.0
scodynelson/JCL
jcl-core/src/main/java/jcl/lang/SynonymStreamStruct.java
807
package jcl.lang; import jcl.lang.internal.stream.SynonymStreamStructImpl; /** * The {@link SynonymStreamStruct} is the object representation of a Lisp 'synonym-stream' type. */ public interface SynonymStreamStruct extends IOStreamStruct { /** * Returns the {@link SymbolStruct} stream symbol. * * @return the {@link SymbolStruct} stream symbol */ SymbolStruct synonymStreamSymbol(); /** * Returns a new Synonym-Stream instance that will delegate stream operations to the value of the provided {@link * SymbolStruct}. * * @param symbol * the {@link SymbolStruct} containing a {@link StreamStruct} value * * @return a new Synonym-Stream instance */ static SynonymStreamStruct toSynonymStream(final SymbolStruct symbol) { return new SynonymStreamStructImpl(symbol); } }
lgpl-3.0
leodmurillo/sonar
sonar-plugin-api/src/test/java/org/sonar/api/utils/ServerHttpClientTest.java
2855
/* * Sonar, open source software quality management tool. * Copyright (C) 2008-2011 SonarSource * mailto:contact AT sonarsource DOT com * * Sonar 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. * * Sonar 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 Sonar; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02 */ package org.sonar.api.utils; import static org.hamcrest.MatcherAssert.assertThat; import static org.hamcrest.Matchers.is; import org.junit.Before; import org.junit.Test; import java.io.IOException; public class ServerHttpClientTest { private String serverUrl = "http://test"; private ServerHttpClient serverHttpClient; @Before public void before() { serverHttpClient = new ServerHttpClient(serverUrl); } @Test public void shouldReturnAValidResult() throws IOException { final String validContent = "valid"; ServerHttpClient serverHttpClient = new ServerHttpClient(serverUrl) { @Override protected String getRemoteContent(String url) { return (validContent); } }; assertThat(serverHttpClient.executeAction("an action"), is(validContent)); } @Test public void shouldRemoveLastUrlSlash() { ServerHttpClient serverHttpClient = new ServerHttpClient(serverUrl + "/"); assertThat(serverHttpClient.getUrl(), is(serverUrl)); } @Test(expected = ServerHttpClient.ServerApiEmptyContentException.class) public void shouldThrowAnExceptionIfResultIsEmpty() throws IOException { final String invalidContent = " "; ServerHttpClient serverHttpClient = new ServerHttpClient(serverUrl) { @Override protected String getRemoteContent(String url) { return (invalidContent); } }; serverHttpClient.executeAction("an action"); } @Test public void shouldReturnMavenRepositoryUrl() { String sonarRepo = serverHttpClient.getMavenRepositoryUrl(); assertThat(sonarRepo, is(serverUrl + ServerHttpClient.MAVEN_PATH)); } @Test(expected = ServerHttpClient.ServerConnectionException.class) public void shouldFailIfCanNotConnectToServer() { ServerHttpClient serverHttpClient = new ServerHttpClient("fake") { @Override protected String getRemoteContent(String url) { throw new ServerConnectionException(""); } }; serverHttpClient.checkUp(); } }
lgpl-3.0
copyliu/Spoutcraft_CJKPatch
src/minecraft/org/getspout/spout/packet/ScreenAction.java
1122
/* * This file is part of Spoutcraft (http://wiki.getspout.org/). * * Spoutcraft 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. * * Spoutcraft is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program. If not, see <http://www.gnu.org/licenses/>. */ package org.getspout.spout.packet; public enum ScreenAction { Open(0), Close(1), ; private final byte id; ScreenAction(int id) { this.id = (byte)id; } public int getId() { return id; } public static ScreenAction getScreenActionFromId(int id) { for (ScreenAction action : values()) { if (action.getId() == id) { return action; } } return null; } }
lgpl-3.0
HATB0T/RuneCraftery
forge/mcp/temp/src/minecraft/net/minecraft/entity/ai/EntityAITradePlayer.java
1206
package net.minecraft.entity.ai; import net.minecraft.entity.ai.EntityAIBase; import net.minecraft.entity.passive.EntityVillager; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.inventory.Container; public class EntityAITradePlayer extends EntityAIBase { private EntityVillager field_75276_a; public EntityAITradePlayer(EntityVillager p_i1658_1_) { this.field_75276_a = p_i1658_1_; this.func_75248_a(5); } public boolean func_75250_a() { if(!this.field_75276_a.func_70089_S()) { return false; } else if(this.field_75276_a.func_70090_H()) { return false; } else if(!this.field_75276_a.field_70122_E) { return false; } else if(this.field_75276_a.field_70133_I) { return false; } else { EntityPlayer var1 = this.field_75276_a.func_70931_l_(); return var1 == null?false:(this.field_75276_a.func_70068_e(var1) > 16.0D?false:var1.field_71070_bA instanceof Container); } } public void func_75249_e() { this.field_75276_a.func_70661_as().func_75499_g(); } public void func_75251_c() { this.field_75276_a.func_70932_a_((EntityPlayer)null); } }
lgpl-3.0
jjettenn/molgenis
molgenis-data-annotators/src/main/java/org/molgenis/data/annotation/core/entity/impl/hpo/HPORepository.java
4146
package org.molgenis.data.annotation.core.entity.impl.hpo; import au.com.bytecode.opencsv.CSVParser; import au.com.bytecode.opencsv.CSVReader; import com.google.common.collect.Iterables; import org.molgenis.data.Entity; import org.molgenis.data.MolgenisDataException; import org.molgenis.data.Query; import org.molgenis.data.QueryRule.Operator; import org.molgenis.data.RepositoryCapability; import org.molgenis.data.meta.model.AttributeFactory; import org.molgenis.data.meta.model.EntityType; import org.molgenis.data.meta.model.EntityTypeFactory; import org.molgenis.data.support.AbstractRepository; import org.molgenis.data.support.DynamicEntity; import java.io.*; import java.nio.charset.Charset; import java.util.*; import java.util.stream.Stream; import static org.molgenis.data.meta.model.EntityType.AttributeRole.ROLE_ID; public class HPORepository extends AbstractRepository { public static final String HPO_DISEASE_ID_COL_NAME = "diseaseId"; public static final String HPO_GENE_SYMBOL_COL_NAME = "gene-symbol"; public static final String HPO_ID_COL_NAME = "HPO-ID"; public static final String HPO_TERM_COL_NAME = "HPO-term-name"; private final EntityTypeFactory entityTypeFactory; private final AttributeFactory attributeFactory; private Map<String, List<Entity>> entitiesByGeneSymbol; private final File file; public HPORepository(File file, EntityTypeFactory entityTypeFactory, AttributeFactory attributeFactory) { this.file = file; this.entityTypeFactory = entityTypeFactory; this.attributeFactory = attributeFactory; } @Override public Set<RepositoryCapability> getCapabilities() { return Collections.emptySet(); } @Override public EntityType getEntityType() { EntityType entityType = entityTypeFactory.create().setSimpleName("HPO"); entityType.addAttribute(attributeFactory.create().setName(HPO_DISEASE_ID_COL_NAME)); entityType.addAttribute(attributeFactory.create().setName(HPO_GENE_SYMBOL_COL_NAME)); entityType.addAttribute(attributeFactory.create().setName(HPO_ID_COL_NAME), ROLE_ID); entityType.addAttribute(attributeFactory.create().setName(HPO_TERM_COL_NAME)); return entityType; } @Override public Iterator<Entity> iterator() { return getEntities().iterator(); } @Override public Stream<Entity> findAll(Query<Entity> q) { if (q.getRules().isEmpty()) return getEntities().stream(); if ((q.getRules().size() != 1) || (q.getRules().get(0).getOperator() != Operator.EQUALS)) { throw new MolgenisDataException("The only query allowed on this Repository is gene EQUALS"); } String geneSymbol = (String) q.getRules().get(0).getValue(); List<Entity> entities = getEntitiesByGeneSymbol().get(geneSymbol); return entities != null ? entities.stream() : Stream.empty(); } @Override public long count() { return Iterables.size(this); } private List<Entity> getEntities() { List<Entity> entities = new ArrayList<>(); getEntitiesByGeneSymbol().forEach((geneSymbol, geneSymbolEntities) -> entities.addAll(geneSymbolEntities)); return entities; } private Map<String, List<Entity>> getEntitiesByGeneSymbol() { if (entitiesByGeneSymbol == null) { entitiesByGeneSymbol = new LinkedHashMap<>(); try (CSVReader csvReader = new CSVReader( new InputStreamReader(new FileInputStream(file), Charset.forName("UTF-8")), '\t', CSVParser.DEFAULT_QUOTE_CHARACTER, 1)) { String[] values = csvReader.readNext(); while (values != null) { String geneSymbol = values[1]; Entity entity = new DynamicEntity(getEntityType()); entity.set(HPO_DISEASE_ID_COL_NAME, values[0]); entity.set(HPO_GENE_SYMBOL_COL_NAME, geneSymbol); entity.set(HPO_ID_COL_NAME, values[3]); entity.set(HPO_TERM_COL_NAME, values[4]); List<Entity> entities = entitiesByGeneSymbol.get(geneSymbol); if (entities == null) { entities = new ArrayList<>(); entitiesByGeneSymbol.put(geneSymbol, entities); } entities.add(entity); values = csvReader.readNext(); } } catch (IOException e) { throw new UncheckedIOException(e); } } return entitiesByGeneSymbol; } }
lgpl-3.0
dana-i2cat/opennaas
extensions/bundles/genericnetwork/src/main/java/org/opennaas/extensions/genericnetwork/model/circuit/request/CircuitRequest.java
3943
package org.opennaas.extensions.genericnetwork.model.circuit.request; /* * #%L * OpenNaaS :: Generic Network * %% * Copyright (C) 2007 - 2014 Fundació Privada i2CAT, Internet i Innovació a Catalunya * %% * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * #L% */ import javax.xml.bind.annotation.XmlAccessType; import javax.xml.bind.annotation.XmlAccessorType; import javax.xml.bind.annotation.XmlAttribute; import javax.xml.bind.annotation.XmlElement; import javax.xml.bind.annotation.XmlRootElement; import javax.xml.bind.annotation.XmlType; import javax.xml.bind.annotation.adapters.NormalizedStringAdapter; import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter; import org.opennaas.extensions.genericnetwork.model.circuit.QoSPolicy; /** * * @author Adrian Rosello Rey (i2CAT) * */ @XmlAccessorType(XmlAccessType.FIELD) @XmlType(name = "", propOrder = { "source", "destination", "label", "qosPolicy" }) @XmlRootElement(name = "qos_policy_request", namespace = "opennaas.api") public class CircuitRequest { @XmlAttribute(name = "atomic") @XmlJavaTypeAdapter(NormalizedStringAdapter.class) private String atomic; @XmlElement(required = true) private Source source; @XmlElement(required = true) private Destination destination; @XmlElement(required = true) private String label; @XmlElement(name = "qos_policy") private QoSPolicy qosPolicy; public String getAtomic() { return atomic; } public void setAtomic(String atomic) { this.atomic = atomic; } public Source getSource() { return source; } public void setSource(Source source) { this.source = source; } public Destination getDestination() { return destination; } public void setDestination(Destination destination) { this.destination = destination; } public String getLabel() { return label; } public void setLabel(String label) { this.label = label; } public QoSPolicy getQosPolicy() { return qosPolicy; } public void setQosPolicy(QoSPolicy qosPolicy) { this.qosPolicy = qosPolicy; } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((atomic == null) ? 0 : atomic.hashCode()); result = prime * result + ((destination == null) ? 0 : destination.hashCode()); result = prime * result + ((label == null) ? 0 : label.hashCode()); result = prime * result + ((qosPolicy == null) ? 0 : qosPolicy.hashCode()); result = prime * result + ((source == null) ? 0 : source.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) return true; if (obj == null) return false; if (getClass() != obj.getClass()) return false; CircuitRequest other = (CircuitRequest) obj; if (atomic == null) { if (other.atomic != null) return false; } else if (!atomic.equals(other.atomic)) return false; if (destination == null) { if (other.destination != null) return false; } else if (!destination.equals(other.destination)) return false; if (label == null) { if (other.label != null) return false; } else if (!label.equals(other.label)) return false; if (qosPolicy == null) { if (other.qosPolicy != null) return false; } else if (!qosPolicy.equals(other.qosPolicy)) return false; if (source == null) { if (other.source != null) return false; } else if (!source.equals(other.source)) return false; return true; } }
lgpl-3.0
KlickReform/dropkit
src/main/java/de/klickreform/dropkit/dao/Dao.java
856
package de.klickreform.dropkit.dao; import de.klickreform.dropkit.exception.DuplicateEntryException; import de.klickreform.dropkit.exception.NotFoundException; import de.klickreform.dropkit.models.DomainModel; import java.io.Serializable; import java.util.Collection; /** * Interface for Data Access Object (DAO) implementations that provide basic CRUD operations for a * Data Access Layer. * * @author Benjamin Bestmann */ public interface Dao<E extends DomainModel,K extends Serializable> { public Collection<E> findAll(); public E findById(K id) throws NotFoundException; public String create(E entity) throws DuplicateEntryException; public String createOrUpdate(E entity); public String update(E entity) throws NotFoundException, DuplicateEntryException; public void delete(E entity) throws NotFoundException; }
lgpl-3.0
SvenssonWeb/OpenHierarchy
src/main/java/se/unlogic/hierarchy/core/beans/Bundle.java
6040
/******************************************************************************* * Copyright (c) 2010 Robert "Unlogic" Olofsson (unlogic@unlogic.se). * All rights reserved. This program and the accompanying materials * are made available under the terms of the GNU Lesser Public License v3 * which accompanies this distribution, and is available at * http://www.gnu.org/licenses/lgpl-3.0-standalone.html ******************************************************************************/ package se.unlogic.hierarchy.core.beans; import java.util.ArrayList; import java.util.List; import org.w3c.dom.Document; import org.w3c.dom.Element; import se.unlogic.hierarchy.core.interfaces.BundleDescriptor; import se.unlogic.hierarchy.core.interfaces.ForegroundModuleDescriptor; import se.unlogic.hierarchy.core.interfaces.MenuItemDescriptor; import se.unlogic.standardutils.xml.XMLUtils; public class Bundle extends MenuItem implements Cloneable { private final Integer moduleID; private String uniqueID; private ArrayList<ModuleMenuItem> moduleMenuItems; public Bundle(BundleDescriptor bundleDescriptor, ForegroundModuleDescriptor descriptor) { this.name = bundleDescriptor.getName(); this.description = bundleDescriptor.getDescription(); this.url = bundleDescriptor.getUrl(); this.urlType = bundleDescriptor.getUrlType(); this.itemType = bundleDescriptor.getItemType(); this.allowedGroupIDs = bundleDescriptor.getAllowedGroupIDs(); this.allowedUserIDs = bundleDescriptor.getAllowedUserIDs(); this.adminAccess = bundleDescriptor.allowsAdminAccess(); this.userAccess = bundleDescriptor.allowsUserAccess(); this.anonymousAccess = bundleDescriptor.allowsAnonymousAccess(); this.moduleMenuItems = new ArrayList<ModuleMenuItem>(); if(bundleDescriptor.getMenuItemDescriptors() != null){ List<? extends MenuItemDescriptor> tempMenuItemDescriptors = bundleDescriptor.getMenuItemDescriptors(); for (MenuItemDescriptor menuItemDescriptor : tempMenuItemDescriptors) { this.moduleMenuItems.add(new ModuleMenuItem(menuItemDescriptor, descriptor, true)); } } this.sectionID = descriptor.getSectionID(); this.moduleID = descriptor.getModuleID(); this.uniqueID = bundleDescriptor.getUniqueID(); } public ArrayList<ModuleMenuItem> getModuleMenuItems() { return this.moduleMenuItems; } public Integer getModuleID() { return moduleID; } @Override public void setMenuIndex(Integer menuIndex) { this.menuIndex = menuIndex; } public void setUniqueID(String uniqueID) { this.uniqueID = uniqueID; } public String getUniqueID() { return uniqueID; } @Override protected void getAdditionalXML(Document doc, Element menuItemElement) { Element bundleElement = doc.createElement("bundle"); bundleElement.appendChild(XMLUtils.createCDATAElement("moduleID", this.moduleID.toString(), doc)); bundleElement.appendChild(XMLUtils.createCDATAElement("uniqueID", this.uniqueID, doc)); menuItemElement.appendChild(bundleElement); } @Override public int hashCode() { final int prime = 31; int result = 1; result = prime * result + ((moduleID == null) ? 0 : moduleID.hashCode()); result = prime * result + ((uniqueID == null) ? 0 : uniqueID.hashCode()); return result; } @Override public boolean equals(Object obj) { if (this == obj) { return true; } if (obj == null) { return false; } if (getClass() != obj.getClass()) { return false; } Bundle other = (Bundle) obj; if (moduleID == null) { if (other.moduleID != null) { return false; } } else if (!moduleID.equals(other.moduleID)) { return false; } if (uniqueID == null) { if (other.uniqueID != null) { return false; } } else if (!uniqueID.equals(other.uniqueID)) { return false; } return true; } @Override public Bundle clone() { try { Bundle bundle = (Bundle) super.clone(); bundle.moduleMenuItems = new ArrayList<ModuleMenuItem>(this.moduleMenuItems); return bundle; } catch (CloneNotSupportedException e) { // This can never happen since we implement clonable... throw new RuntimeException(e); } } public Element toFullXML(Document doc) { Element bundleElement = doc.createElement("bundle"); bundleElement.appendChild(XMLUtils.createCDATAElement("moduleID", this.moduleID.toString(), doc)); if (this.name != null) { bundleElement.appendChild(XMLUtils.createCDATAElement("name", this.name, doc)); } if (this.description != null) { bundleElement.appendChild(XMLUtils.createCDATAElement("description", this.description, doc)); } if (this.menuIndex != null) { bundleElement.appendChild(XMLUtils.createCDATAElement("menuIndex", this.menuIndex.toString(), doc)); } if (this.url != null) { bundleElement.appendChild(XMLUtils.createCDATAElement("url", this.url, doc)); } if (this.urlType != null) { bundleElement.appendChild(XMLUtils.createCDATAElement("urlType", this.urlType.toString(), doc)); } if (this.itemType != null) { bundleElement.appendChild(XMLUtils.createCDATAElement("itemType", this.itemType.toString(), doc)); } if (this.sectionID != null) { bundleElement.appendChild(XMLUtils.createCDATAElement("sectionID", this.sectionID.toString(), doc)); } if(uniqueID != null){ bundleElement.appendChild(XMLUtils.createCDATAElement("uniqueID", this.uniqueID.toString(), doc)); } Element adminAccess = doc.createElement("adminAccess"); adminAccess.appendChild(doc.createTextNode(Boolean.toString(this.adminAccess))); bundleElement.appendChild(adminAccess); Element userAccess = doc.createElement("userAccess"); userAccess.appendChild(doc.createTextNode(Boolean.toString(this.userAccess))); bundleElement.appendChild(userAccess); Element anonymousAccess = doc.createElement("anonymousAccess"); anonymousAccess.appendChild(doc.createTextNode(Boolean.toString(this.anonymousAccess))); bundleElement.appendChild(anonymousAccess); XMLUtils.append(doc, bundleElement, "menuitems", this.moduleMenuItems); return bundleElement; } }
lgpl-3.0
ClearVolume/ClearVolume
src/java/clearvolume/utils/AppleMac.java
2849
package clearvolume.utils; import java.awt.Image; import java.awt.Window; import java.lang.reflect.Method; public class AppleMac { // final static com.apple.eawt.Application cApplication = // com.apple.eawt.Application.getApplication(); static Class<?> cClass; static Object cApplication; static { try { cClass = Class.forName("com.apple.eawt.Application"); Method lMethod = cClass.getDeclaredMethod("getApplication"); cApplication = lMethod.invoke(null); } catch (Throwable e) { System.err.println(e.getLocalizedMessage()); } } private static String OS = System.getProperty("os.name") .toLowerCase(); public static boolean isMac() { return (OS.indexOf("mac") >= 0); } public static final boolean setApplicationIcon(final Image pImage) { if (!isMac()) return false; try { final Thread lThread = new Thread("Apple Set Application Icon") { @Override public void run() { try { Method lMethod = cClass.getDeclaredMethod( "setDockIconImage", Image.class); lMethod.invoke(cApplication, pImage); // cApplication.setDockIconImage(pImage); } catch (final Throwable e) { System.out.println(AppleMac.class.getSimpleName() + ": Could not set Dock Icon (not on osx?)"); } super.run(); } }; lThread.start(); return true; } catch (final Throwable e) { System.err.println(e.getMessage()); return false; } } public static final boolean setApplicationName(final String pString) { if (!isMac()) return false; try { System.setProperty( "com.apple.mrj.application.apple.menu.about.name", pString); return true; } catch (final Throwable e) { System.err.println(e.getMessage()); return false; } } @SuppressWarnings( { "unchecked", "rawtypes" }) public static boolean enableOSXFullscreen(final Window window) { if (!isMac()) return false; if (window == null) return false; try { final Class util = Class.forName("com.apple.eawt.FullScreenUtilities"); final Class params[] = new Class[] { Window.class, Boolean.TYPE }; final Method method = util.getMethod( "setWindowCanFullScreen", params); method.invoke(util, window, true); return true; } catch (final Throwable e) { System.err.println(e.getLocalizedMessage()); return false; } } public final static boolean requestFullscreen(final Window pWindow) { if (!isMac()) return false; try { // cApplication.requestToggleFullScreen(pWindow); Method lMethod = cClass.getDeclaredMethod( "requestToggleFullScreen", Window.class); lMethod.invoke(cApplication, pWindow); return true; } catch (final Throwable e) { System.err.println(e.getLocalizedMessage()); return false; } } }
lgpl-3.0
Mindtoeye/Hoop
src/org/jdesktop/swingx/plaf/TableHeaderAddon.java
2161
/* * $Id$ * * Copyright 2009 Sun Microsystems, Inc., 4150 Network Circle, * Santa Clara, California 95054, U.S.A. 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, write to the Free Software * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA * */ package org.jdesktop.swingx.plaf; import javax.swing.BorderFactory; import javax.swing.UIManager; import javax.swing.border.Border; import javax.swing.plaf.BorderUIResource; import javax.swing.plaf.metal.MetalBorders; /** * Addon for JXTableHeader. * * Implemented to hack around core issue ??: Metal header renderer appears squeezed. * * @author Jeanette Winzenburg */ public class TableHeaderAddon extends AbstractComponentAddon { /** * @param name */ public TableHeaderAddon() { super("JXTableHeader"); } @Override protected void addMetalDefaults(LookAndFeelAddons addon, DefaultsList defaults) { super.addMetalDefaults(addon, defaults); String key = "TableHeader.cellBorder"; Border border = UIManager.getBorder(key); if (border instanceof MetalBorders.TableHeaderBorder) { border = new BorderUIResource.CompoundBorderUIResource(border, BorderFactory.createEmptyBorder()); // PENDING JW: this is fishy ... adding to lookAndFeelDefaults is taken UIManager.getLookAndFeelDefaults().put(key, border); // adding to defaults is not // defaults.add(key, border); } } }
lgpl-3.0
IblowUpTnT/tntMods
src/main/java/com/iblowuptnt/tntMods/item/ItemCompShovel.java
1656
package com.iblowuptnt.tntMods.item; import com.google.common.collect.Sets; import com.iblowuptnt.tntMods.creativetab.CreativeTab; import com.iblowuptnt.tntMods.reference.Material; import com.iblowuptnt.tntMods.reference.Name; import com.iblowuptnt.tntMods.reference.Textures; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.block.Block; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.item.ItemSpade; import net.minecraft.init.Blocks; import net.minecraft.item.ItemStack; import java.util.Set; public class ItemCompShovel extends ItemSpade { public ItemCompShovel() { super(Material.Tools.COMP_DIAMOND); this.setCreativeTab(CreativeTab.TNT_TAB); this.setUnlocalizedName(Name.Tools.COMP_SHOVEL); this.maxStackSize = 1; } protected String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } @Override public String getUnlocalizedName() { return String.format("item.%s%s", Textures.MOD_ID_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override public String getUnlocalizedName(ItemStack itemStack) { return String.format("item.%s%s", Textures.MOD_ID_PREFIX, getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1)); } }
lgpl-3.0
teryk/sonarqube
server/sonar-server/src/test/java/org/sonar/server/rule/RegisterRulesTest.java
12879
/* * SonarQube, open source software quality management tool. * Copyright (C) 2008-2014 SonarSource * mailto:contact AT sonarsource DOT com * * SonarQube 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. * * SonarQube is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU * Lesser General Public License for more details. * * You should have received a copy of the GNU Lesser General Public License * along with this program; if not, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.server.rule; import com.google.common.collect.Sets; import org.junit.After; import org.junit.Before; import org.junit.Test; import org.sonar.api.resources.Language; import org.sonar.api.resources.Languages; import org.sonar.api.rule.RuleKey; import org.sonar.api.rule.RuleStatus; import org.sonar.api.rule.Severity; import org.sonar.api.server.rule.RulesDefinition; import org.sonar.api.utils.DateUtils; import org.sonar.api.utils.System2; import org.sonar.core.persistence.AbstractDaoTestCase; import org.sonar.core.persistence.DbSession; import org.sonar.core.qualityprofile.db.QualityProfileDao; import org.sonar.core.rule.RuleDto; import org.sonar.core.rule.RuleParamDto; import org.sonar.core.technicaldebt.db.CharacteristicDao; import org.sonar.server.db.DbClient; import org.sonar.server.qualityprofile.RuleActivator; import org.sonar.server.qualityprofile.db.ActiveRuleDao; import org.sonar.server.rule.db.RuleDao; import java.util.Date; import java.util.List; import static org.fest.assertions.Assertions.assertThat; import static org.mockito.Mockito.mock; import static org.mockito.Mockito.when; public class RegisterRulesTest extends AbstractDaoTestCase { static final Date DATE1 = DateUtils.parseDateTime("2014-01-01T19:10:03+0100"); static final Date DATE2 = DateUtils.parseDateTime("2014-02-01T12:10:03+0100"); static final Date DATE3 = DateUtils.parseDateTime("2014-03-01T12:10:03+0100"); RuleActivator ruleActivator = mock(RuleActivator.class); System2 system; DbClient dbClient; DbSession dbSession; @Before public void before() { system = mock(System2.class); when(system.now()).thenReturn(DATE1.getTime()); RuleDao ruleDao = new RuleDao(system); ActiveRuleDao activeRuleDao = new ActiveRuleDao(new QualityProfileDao(getMyBatis(), system), ruleDao, system); dbClient = new DbClient(getDatabase(), getMyBatis(), ruleDao, activeRuleDao, new QualityProfileDao(getMyBatis(), system), new CharacteristicDao(getMyBatis())); dbSession = dbClient.openSession(false); } @After public void after() throws Exception { dbSession.close(); } @Test public void insert_new_rules() { execute(new FakeRepositoryV1()); // verify db assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2); RuleKey ruleKey1 = RuleKey.of("fake", "rule1"); RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1); assertThat(rule1.getName()).isEqualTo("One"); assertThat(rule1.getDescription()).isEqualTo("Description of One"); assertThat(rule1.getSeverityString()).isEqualTo(Severity.BLOCKER); assertThat(rule1.getTags()).isEmpty(); assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag2", "tag3"); assertThat(rule1.getConfigKey()).isEqualTo("config1"); assertThat(rule1.getStatus()).isEqualTo(RuleStatus.BETA); assertThat(rule1.getCreatedAt()).isEqualTo(DATE1); assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1); // TODO check characteristic and remediation function List<RuleParamDto> params = dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, ruleKey1); assertThat(params).hasSize(2); RuleParamDto param = getParam(params, "param1"); assertThat(param.getDescription()).isEqualTo("parameter one"); assertThat(param.getDefaultValue()).isEqualTo("default1"); } @Test public void do_not_update_rules_when_no_changes() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2); when(system.now()).thenReturn(DATE2.getTime()); execute(new FakeRepositoryV1()); RuleKey ruleKey1 = RuleKey.of("fake", "rule1"); RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1); assertThat(rule1.getCreatedAt()).isEqualTo(DATE1); assertThat(rule1.getUpdatedAt()).isEqualTo(DATE1); } @Test public void update_and_remove_rules_on_changes() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2); // user adds tags and sets markdown note RuleKey ruleKey1 = RuleKey.of("fake", "rule1"); RuleDto rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1); rule1.setTags(Sets.newHashSet("usertag1", "usertag2")); rule1.setNoteData("user *note*"); rule1.setNoteUserLogin("marius"); dbClient.ruleDao().update(dbSession, rule1); dbSession.commit(); when(system.now()).thenReturn(DATE2.getTime()); execute(new FakeRepositoryV2()); // rule1 has been updated rule1 = dbClient.ruleDao().getNullableByKey(dbSession, ruleKey1); assertThat(rule1.getName()).isEqualTo("One v2"); assertThat(rule1.getDescription()).isEqualTo("Description of One v2"); assertThat(rule1.getSeverityString()).isEqualTo(Severity.INFO); assertThat(rule1.getTags()).containsOnly("usertag1", "usertag2"); assertThat(rule1.getSystemTags()).containsOnly("tag1", "tag4"); assertThat(rule1.getConfigKey()).isEqualTo("config1 v2"); assertThat(rule1.getNoteData()).isEqualTo("user *note*"); assertThat(rule1.getNoteUserLogin()).isEqualTo("marius"); assertThat(rule1.getStatus()).isEqualTo(RuleStatus.READY); assertThat(rule1.getCreatedAt()).isEqualTo(DATE1); assertThat(rule1.getUpdatedAt()).isEqualTo(DATE2); // TODO check characteristic and remediation function List<RuleParamDto> params = dbClient.ruleDao().findRuleParamsByRuleKey(dbSession, ruleKey1); assertThat(params).hasSize(2); RuleParamDto param = getParam(params, "param1"); assertThat(param.getDescription()).isEqualTo("parameter one v2"); assertThat(param.getDefaultValue()).isEqualTo("default1 v2"); // rule2 has been removed -> status set to REMOVED but db row is not deleted RuleDto rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED); assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2); // rule3 has been created RuleDto rule3 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule3")); assertThat(rule3).isNotNull(); assertThat(rule3.getStatus()).isEqualTo(RuleStatus.READY); } @Test public void do_not_update_already_removed_rules() { execute(new FakeRepositoryV1()); assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(2); RuleDto rule2 = dbClient.ruleDao().getByKey(dbSession, RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.READY); when(system.now()).thenReturn(DATE2.getTime()); execute(new FakeRepositoryV2()); // On MySQL, need to update a rule otherwise rule2 will be seen as READY, but why ??? dbClient.ruleDao().update(dbSession, dbClient.ruleDao().getByKey(dbSession, RuleKey.of("fake", "rule1"))); dbSession.commit(); // rule2 is removed rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED); when(system.now()).thenReturn(DATE3.getTime()); execute(new FakeRepositoryV2()); dbSession.commit(); // -> rule2 is still removed, but not update at DATE3 rule2 = dbClient.ruleDao().getNullableByKey(dbSession, RuleKey.of("fake", "rule2")); assertThat(rule2.getStatus()).isEqualTo(RuleStatus.REMOVED); assertThat(rule2.getUpdatedAt()).isEqualTo(DATE2); } @Test public void mass_insert() { execute(new BigRepository()); assertThat(dbClient.ruleDao().findAll(dbSession)).hasSize(BigRepository.SIZE); assertThat(dbClient.ruleDao().findAllRuleParams(dbSession)).hasSize(BigRepository.SIZE * 20); } @Test public void manage_repository_extensions() { execute(new FindbugsRepository(), new FbContribRepository()); List<RuleDto> rules = dbClient.ruleDao().findAll(dbSession); assertThat(rules).hasSize(2); for (RuleDto rule : rules) { assertThat(rule.getRepositoryKey()).isEqualTo("findbugs"); } } private void execute(RulesDefinition... defs) { RuleDefinitionsLoader loader = new RuleDefinitionsLoader(mock(RuleRepositories.class), defs); Languages languages = mock(Languages.class); when(languages.get("java")).thenReturn(mock(Language.class)); RegisterRules task = new RegisterRules(loader, ruleActivator, dbClient, languages, system); task.start(); } private RuleParamDto getParam(List<RuleParamDto> params, String key) { for (RuleParamDto param : params) { if (param.getName().equals(key)) { return param; } } return null; } static class FakeRepositoryV1 implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("fake", "java"); NewRule rule1 = repo.createRule("rule1") .setName("One") .setHtmlDescription("Description of One") .setSeverity(Severity.BLOCKER) .setInternalKey("config1") .setTags("tag1", "tag2", "tag3") .setStatus(RuleStatus.BETA) .setDebtSubCharacteristic("MEMORY_EFFICIENCY") .setEffortToFixDescription("squid.S115.effortToFix"); rule1.setDebtRemediationFunction(rule1.debtRemediationFunctions().linearWithOffset("5d", "10h")); rule1.createParam("param1").setDescription("parameter one").setDefaultValue("default1"); rule1.createParam("param2").setDescription("parameter two").setDefaultValue("default2"); repo.createRule("rule2") .setName("Two") .setHtmlDescription("Minimal rule"); repo.done(); } } /** * FakeRepositoryV1 with some changes */ static class FakeRepositoryV2 implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("fake", "java"); // almost all the attributes of rule1 are changed NewRule rule1 = repo.createRule("rule1") .setName("One v2") .setHtmlDescription("Description of One v2") .setSeverity(Severity.INFO) .setInternalKey("config1 v2") // tag2 and tag3 removed, tag4 added .setTags("tag1", "tag4") .setStatus(RuleStatus.READY) .setDebtSubCharacteristic("MEMORY_EFFICIENCY") .setEffortToFixDescription("squid.S115.effortToFix.v2"); rule1.setDebtRemediationFunction(rule1.debtRemediationFunctions().linearWithOffset("6d", "2h")); rule1.createParam("param1").setDescription("parameter one v2").setDefaultValue("default1 v2"); rule1.createParam("param2").setDescription("parameter two v2").setDefaultValue("default2 v2"); // rule2 is dropped, rule3 is new repo.createRule("rule3") .setName("Three") .setHtmlDescription("Rule Three"); repo.done(); } } static class BigRepository implements RulesDefinition { static final int SIZE = 500; @Override public void define(Context context) { NewRepository repo = context.createRepository("big", "java"); for (int i = 0; i < SIZE; i++) { NewRule rule = repo.createRule("rule" + i) .setName("name of " + i) .setHtmlDescription("description of " + i); for (int j = 0; j < 20; j++) { rule.createParam("param" + j); } } repo.done(); } } static class FindbugsRepository implements RulesDefinition { @Override public void define(Context context) { NewRepository repo = context.createRepository("findbugs", "java"); repo.createRule("rule1") .setName("Rule One") .setHtmlDescription("Description of Rule One"); repo.done(); } } static class FbContribRepository implements RulesDefinition { @Override public void define(Context context) { NewExtendedRepository repo = context.extendRepository("findbugs", "java"); repo.createRule("rule2") .setName("Rule Two") .setHtmlDescription("Description of Rule Two"); repo.done(); } } }
lgpl-3.0
cismet/cismap-commons
src/main/java/de/cismet/cismap/commons/internaldb/DBTransferable.java
1839
/*************************************************** * * cismet GmbH, Saarbruecken, Germany * * ... and it just works. * ****************************************************/ /* * To change this template, choose Tools | Templates * and open the template in the editor. */ package de.cismet.cismap.commons.internaldb; import java.awt.datatransfer.DataFlavor; import java.awt.datatransfer.Transferable; import java.awt.datatransfer.UnsupportedFlavorException; import java.io.IOException; /** * DOCUMENT ME! * * @author therter * @version $Revision$, $Date$ */ public class DBTransferable implements Transferable { //~ Instance fields -------------------------------------------------------- private DataFlavor TREEPATH_FLAVOR = new DataFlavor( DataFlavor.javaJVMLocalObjectMimeType, "SelectionAndCapabilities"); // NOI18N private DBTableInformation[] transferObjects; //~ Constructors ----------------------------------------------------------- /** * Creates a new DBTransferable object. * * @param transferObjects DOCUMENT ME! */ public DBTransferable(final DBTableInformation[] transferObjects) { this.transferObjects = transferObjects; } //~ Methods ---------------------------------------------------------------- @Override public DataFlavor[] getTransferDataFlavors() { return new DataFlavor[] { TREEPATH_FLAVOR }; } @Override public boolean isDataFlavorSupported(final DataFlavor flavor) { return flavor.equals(TREEPATH_FLAVOR); } @Override public Object getTransferData(final DataFlavor flavor) throws UnsupportedFlavorException, IOException { if (isDataFlavorSupported(flavor)) { return transferObjects; } return null; } }
lgpl-3.0
EntityAPIDev/EntityAPI
modules/API/src/main/java/org/entityapi/api/entity/type/nms/ControllableSlimeHandle.java
938
/* * Copyright (C) EntityAPI Team * * This file is part of EntityAPI. * * EntityAPI 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. * * EntityAPI 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 EntityAPI. If not, see <http://www.gnu.org/licenses/>. */ package org.entityapi.api.entity.type.nms; import org.bukkit.entity.Slime; import org.entityapi.api.entity.ControllableEntityHandle; public interface ControllableSlimeHandle extends ControllableEntityHandle<Slime> { }
lgpl-3.0
anndy201/mars-framework
com.sqsoft.mars.qyweixin.client/src/main/java/com/sqsoft/mars/qyweixin/client/cgibin/message/QyweixinMessageClient.java
656
/** * */ package com.sqsoft.mars.qyweixin.client.cgibin.message; import com.sqsoft.mars.qyweixin.client.QyweixinDefaultClient; /** * @author lenovo * */ public class QyweixinMessageClient extends QyweixinDefaultClient { /** * */ private String access_token; /** * * @param access_token */ public QyweixinMessageClient(String access_token) { super(); this.access_token = access_token; } /* (non-Javadoc) * @see com.sqsoft.mars.qyweixin.client.DefaultQyweixinClient#getUrl() */ @Override protected String getUrl() { return "https://qyapi.weixin.qq.com/cgi-bin/message/{method}?access_token=" + access_token; } }
lgpl-3.0
scodynelson/JCL
jcl-compiler/src/main/java/jcl/compiler/sa/analyzer/lambdalistparser/LambdaListParser.java
37554
package jcl.compiler.sa.analyzer.lambdalistparser; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import java.util.function.Predicate; import jcl.compiler.environment.Environment; import jcl.compiler.environment.binding.Binding; import jcl.compiler.environment.binding.lambdalist.AuxParameter; import jcl.compiler.environment.binding.lambdalist.BodyParameter; import jcl.compiler.environment.binding.lambdalist.DestructuringLambdaList; import jcl.compiler.environment.binding.lambdalist.EnvironmentParameter; import jcl.compiler.environment.binding.lambdalist.KeyParameter; import jcl.compiler.environment.binding.lambdalist.OptionalParameter; import jcl.compiler.environment.binding.lambdalist.RequiredParameter; import jcl.compiler.environment.binding.lambdalist.RestParameter; import jcl.compiler.environment.binding.lambdalist.SuppliedPParameter; import jcl.compiler.environment.binding.lambdalist.WholeParameter; import jcl.compiler.sa.FormAnalyzer; import jcl.compiler.struct.specialoperator.declare.DeclareStruct; import jcl.compiler.struct.specialoperator.declare.SpecialDeclarationStruct; import jcl.lang.KeywordStruct; import jcl.lang.LispStruct; import jcl.lang.ListStruct; import jcl.lang.NILStruct; import jcl.lang.PackageStruct; import jcl.lang.PackageSymbolStruct; import jcl.lang.SymbolStruct; import jcl.lang.condition.exception.ProgramErrorException; import jcl.lang.statics.CommonLispSymbols; import jcl.lang.statics.CompilerConstants; import jcl.lang.statics.GlobalPackageStruct; import lombok.experimental.UtilityClass; @UtilityClass public final class LambdaListParser { public static WholeParseResult parseWholeBinding(final Environment environment, final Iterator<LispStruct> iterator, final DeclareStruct declareElement) { final LispStruct currentElement = iterator.next(); if (!(currentElement instanceof SymbolStruct)) { throw new ProgramErrorException("LambdaList &whole parameters must be a symbol: " + currentElement); } final SymbolStruct currentParam = (SymbolStruct) currentElement; final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(currentParam)); final Binding binding = new Binding(currentParam, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final WholeParameter wholeBinding = new WholeParameter(currentParam, isSpecial); return new WholeParseResult(wholeBinding); } public static EnvironmentParseResult parseEnvironmentBinding(final Environment environment, final Iterator<LispStruct> iterator, final boolean isAfterRequired) { LispStruct currentElement = iterator.next(); if (!(currentElement instanceof SymbolStruct)) { throw new ProgramErrorException("LambdaList &environment parameters must be a symbol: " + currentElement); } final SymbolStruct currentParam = (SymbolStruct) currentElement; if (iterator.hasNext() && isAfterRequired) { currentElement = iterator.next(); if (!isLambdaListKeyword(currentElement)) { throw new ProgramErrorException("LambdaList &environment parameter must only have 1 parameter: " + currentElement); } } final Binding binding = new Binding(currentParam, CommonLispSymbols.T); environment.addDynamicBinding(binding); final EnvironmentParameter environmentBinding = new EnvironmentParameter(currentParam); return new EnvironmentParseResult(currentElement, environmentBinding); } public static RequiredParseResult parseRequiredBindings(final Environment environment, final Iterator<LispStruct> iterator, final DeclareStruct declareElement, final boolean isDotted, final boolean isDestructuringAllowed) { final List<RequiredParameter> requiredBindings = new ArrayList<>(); LispStruct currentElement; do { currentElement = iterator.next(); if (!iterator.hasNext() && isDotted) { return new RequiredParseResult(currentElement, requiredBindings); } if (isLambdaListKeyword(currentElement)) { return new RequiredParseResult(currentElement, requiredBindings); } final SymbolStruct currentParam; DestructuringLambdaList destructuringForm = null; if (currentElement instanceof SymbolStruct) { currentParam = (SymbolStruct) currentElement; } else { if (isDestructuringAllowed) { if (currentElement instanceof ListStruct) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); currentParam = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final ListStruct destructuringFormList = (ListStruct) currentElement; destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); } else { throw new ProgramErrorException("LambdaList required parameter must be a symbol or a destructuring list: " + currentElement); } } else { throw new ProgramErrorException("LambdaList required parameters must be a symbol: " + currentElement); } } final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(currentParam)); final Binding binding = new Binding(currentParam, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final RequiredParameter requiredBinding = new RequiredParameter(currentParam, destructuringForm, isSpecial); requiredBindings.add(requiredBinding); } while (iterator.hasNext()); return new RequiredParseResult(currentElement, requiredBindings); } public static OptionalParseResult parseOptionalBindings(final Environment environment, final Iterator<LispStruct> iterator, final DeclareStruct declareElement, final boolean isDotted, final boolean isDestructuringAllowed) { final List<OptionalParameter> optionalBindings = new ArrayList<>(); if (!iterator.hasNext()) { return new OptionalParseResult(null, optionalBindings); } LispStruct currentElement; do { currentElement = iterator.next(); if (isLambdaListKeyword(currentElement)) { return new OptionalParseResult(currentElement, optionalBindings); } if (!iterator.hasNext() && isDotted) { return new OptionalParseResult(currentElement, optionalBindings); } if (currentElement instanceof SymbolStruct) { final SymbolStruct currentParam = (SymbolStruct) currentElement; final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(currentParam)); Binding binding = new Binding(currentParam, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final String paramName = currentParam.getName(); final String customSuppliedPName = paramName + "-P-" + System.nanoTime(); final PackageStruct currentParamPackage = currentParam.getSymbolPackage(); final SymbolStruct customSuppliedPCurrent = currentParamPackage.intern(customSuppliedPName).getSymbol(); final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(customSuppliedPCurrent)); binding = new Binding(customSuppliedPCurrent, CommonLispSymbols.T); if (isSuppliedPSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final SuppliedPParameter suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent, isSuppliedPSpecial); final OptionalParameter optionalBinding = new OptionalParameter(currentParam, null, NILStruct.INSTANCE, isSpecial, suppliedPBinding); optionalBindings.add(optionalBinding); } else if (currentElement instanceof ListStruct) { final ListStruct currentParam = (ListStruct) currentElement; final long currentParamLength = currentParam.length().toJavaPLong(); if ((currentParamLength < 1) || (currentParamLength > 3)) { if (isDestructuringAllowed) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); final SymbolStruct varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final ListStruct destructuringFormList = (ListStruct) currentElement; final DestructuringLambdaList destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); final String customSuppliedPName = destructuringName + "-P-" + System.nanoTime(); final SymbolStruct customSuppliedPCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(customSuppliedPName).getSymbol(); final SuppliedPParameter suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent); final OptionalParameter optionalBinding = new OptionalParameter(varNameCurrent, destructuringForm, NILStruct.INSTANCE, false, suppliedPBinding); optionalBindings.add(optionalBinding); } else { throw new ProgramErrorException("LambdaList &optional parameters must have between 1 and 3 parameters: " + currentParam); } } else { final Iterator<LispStruct> currentIterator = currentParam.iterator(); final LispStruct firstInCurrent = currentIterator.next(); final LispStruct secondInCurrent; if (currentIterator.hasNext()) { secondInCurrent = currentIterator.next(); } else { secondInCurrent = NILStruct.INSTANCE; } final LispStruct thirdInCurrent; if (currentIterator.hasNext()) { thirdInCurrent = currentIterator.next(); } else { thirdInCurrent = NILStruct.INSTANCE; } final SymbolStruct varNameCurrent; DestructuringLambdaList destructuringForm = null; if (firstInCurrent instanceof SymbolStruct) { varNameCurrent = (SymbolStruct) firstInCurrent; } else { if (isDestructuringAllowed) { if (firstInCurrent instanceof ListStruct) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final ListStruct destructuringFormList = (ListStruct) firstInCurrent; destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); } else { throw new ProgramErrorException("LambdaList &optional var name parameter must be a symbol or a destructuring list: " + firstInCurrent); } } else { throw new ProgramErrorException("LambdaList &optional var name parameters must be a symbol: " + firstInCurrent); } } LispStruct initForm = NILStruct.INSTANCE; if (!secondInCurrent.eq(NILStruct.INSTANCE)) { initForm = secondInCurrent; } final LispStruct parameterValueInitForm = FormAnalyzer.analyze(initForm, environment); final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(varNameCurrent)); Binding binding = new Binding(varNameCurrent, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final SuppliedPParameter suppliedPBinding; if (thirdInCurrent.eq(NILStruct.INSTANCE)) { final String paramName = varNameCurrent.getName(); final String customSuppliedPName = paramName + "-P-" + System.nanoTime(); final PackageStruct currentParamPackage = varNameCurrent.getSymbolPackage(); final SymbolStruct customSuppliedPCurrent = currentParamPackage.intern(customSuppliedPName).getSymbol(); final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(customSuppliedPCurrent)); binding = new Binding(customSuppliedPCurrent, CommonLispSymbols.T); if (isSuppliedPSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent, isSuppliedPSpecial); } else { if (!(thirdInCurrent instanceof SymbolStruct)) { throw new ProgramErrorException("LambdaList &optional supplied-p parameters must be a symbol: " + thirdInCurrent); } final SymbolStruct suppliedPCurrent = (SymbolStruct) thirdInCurrent; final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(suppliedPCurrent)); binding = new Binding(suppliedPCurrent, CommonLispSymbols.T); if (isSuppliedPSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } suppliedPBinding = new SuppliedPParameter(suppliedPCurrent, isSuppliedPSpecial); } final OptionalParameter optionalBinding = new OptionalParameter(varNameCurrent, destructuringForm, parameterValueInitForm, isSpecial, suppliedPBinding); optionalBindings.add(optionalBinding); } } else { throw new ProgramErrorException("LambdaList &optional parameters must be a symbol or a list: " + currentElement); } } while (iterator.hasNext()); return new OptionalParseResult(currentElement, optionalBindings); } public static RestParseResult parseRestBinding(final Environment environment, final Iterator<LispStruct> iterator, final DeclareStruct declareElement, final boolean isDestructuringAllowed) { if (!iterator.hasNext()) { throw new ProgramErrorException("LambdaList &rest parameter must be provided."); } LispStruct currentElement = iterator.next(); final SymbolStruct currentParam; DestructuringLambdaList destructuringForm = null; if (currentElement instanceof SymbolStruct) { currentParam = (SymbolStruct) currentElement; } else { if (isDestructuringAllowed) { if (currentElement instanceof ListStruct) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); currentParam = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final ListStruct destructuringFormList = (ListStruct) currentElement; destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); } else { throw new ProgramErrorException("LambdaList &rest parameters must be a symbol or a destructuring list: " + currentElement); } } else { throw new ProgramErrorException("LambdaList &rest parameters must be a symbol: " + currentElement); } } if (iterator.hasNext()) { currentElement = iterator.next(); if (!isLambdaListKeyword(currentElement)) { throw new ProgramErrorException("LambdaList &rest parameter must only have 1 parameter: " + currentElement); } } final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(currentParam)); final Binding binding = new Binding(currentParam, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final RestParameter restBinding = new RestParameter(currentParam, destructuringForm, isSpecial); return new RestParseResult(currentElement, restBinding); } public static RestParseResult parseDottedRestBinding(final Environment environment, final LispStruct dottedRest, final DeclareStruct declareElement, final boolean isDestructuringAllowed) { final SymbolStruct currentParam; DestructuringLambdaList destructuringForm = null; if (dottedRest instanceof SymbolStruct) { currentParam = (SymbolStruct) dottedRest; } else { if (isDestructuringAllowed) { if (dottedRest instanceof ListStruct) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); currentParam = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final ListStruct destructuringFormList = (ListStruct) dottedRest; destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); } else { throw new ProgramErrorException("LambdaList &rest parameters must be a symbol or a destructuring list: " + dottedRest); } } else { throw new ProgramErrorException("LambdaList &rest parameters must be a symbol: " + dottedRest); } } final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(currentParam)); final Binding binding = new Binding(currentParam, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final RestParameter restBinding = new RestParameter(currentParam, destructuringForm, isSpecial); return new RestParseResult(dottedRest, restBinding); } public static BodyParseResult parseBodyBinding(final Environment environment, final Iterator<LispStruct> iterator, final DeclareStruct declareElement, final boolean isDestructuringAllowed) { if (!iterator.hasNext()) { throw new ProgramErrorException("LambdaList &body parameter must be provided."); } LispStruct currentElement = iterator.next(); final SymbolStruct currentParam; DestructuringLambdaList destructuringForm = null; if (currentElement instanceof SymbolStruct) { currentParam = (SymbolStruct) currentElement; } else { if (isDestructuringAllowed) { if (currentElement instanceof ListStruct) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); currentParam = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final ListStruct destructuringFormList = (ListStruct) currentElement; destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); } else { throw new ProgramErrorException("LambdaList &rest parameters must be a symbol or a destructuring list: " + currentElement); } } else { throw new ProgramErrorException("LambdaList &rest parameters must be a symbol: " + currentElement); } } if (iterator.hasNext()) { currentElement = iterator.next(); if (!isLambdaListKeyword(currentElement)) { throw new ProgramErrorException("LambdaList &body parameter must only have 1 parameter: " + currentElement); } } final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(currentParam)); final Binding binding = new Binding(currentParam, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final BodyParameter bodyBinding = new BodyParameter(currentParam, destructuringForm, isSpecial); return new BodyParseResult(currentElement, bodyBinding); } public static KeyParseResult parseKeyBindings(final Environment environment, final Iterator<LispStruct> iterator, final DeclareStruct declareElement, final boolean isDestructuringAllowed) { final List<KeyParameter> keyBindings = new ArrayList<>(); if (!iterator.hasNext()) { return new KeyParseResult(null, keyBindings); } LispStruct currentElement; do { currentElement = iterator.next(); if (isLambdaListKeyword(currentElement)) { return new KeyParseResult(currentElement, keyBindings); } if (currentElement instanceof SymbolStruct) { final SymbolStruct currentParam = (SymbolStruct) currentElement; final KeywordStruct keyName = getKeywordStruct(currentParam.getName()); final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(currentParam)); Binding binding = new Binding(currentParam, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final String paramName = currentParam.getName(); final String customSuppliedPName = paramName + "-P-" + System.nanoTime(); final PackageStruct currentParamPackage = currentParam.getSymbolPackage(); final SymbolStruct customSuppliedPCurrent = currentParamPackage.intern(customSuppliedPName).getSymbol(); final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(customSuppliedPCurrent)); binding = new Binding(customSuppliedPCurrent, CommonLispSymbols.T); if (isSuppliedPSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final SuppliedPParameter suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent, isSuppliedPSpecial); final KeyParameter keyBinding = new KeyParameter(currentParam, null, NILStruct.INSTANCE, isSpecial, keyName, suppliedPBinding); keyBindings.add(keyBinding); } else if (currentElement instanceof ListStruct) { final ListStruct currentParam = (ListStruct) currentElement; final long currentParamLength = currentParam.length().toJavaPLong(); if ((currentParamLength < 1) || (currentParamLength > 3)) { if (isDestructuringAllowed) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); final SymbolStruct varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final SymbolStruct varKeyNameCurrent = getKeywordStruct(varNameCurrent.getName()); final ListStruct destructuringFormList = (ListStruct) currentElement; final DestructuringLambdaList destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); final String customSuppliedPName = destructuringName + "-P-" + System.nanoTime(); final SymbolStruct customSuppliedPCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(customSuppliedPName).getSymbol(); final SuppliedPParameter suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent); final KeyParameter keyBinding = new KeyParameter(varNameCurrent, destructuringForm, NILStruct.INSTANCE, false, varKeyNameCurrent, suppliedPBinding); keyBindings.add(keyBinding); } else { throw new ProgramErrorException("LambdaList &key parameters must have between 1 and 3 parameters: " + currentParam); } } else { final Iterator<LispStruct> currentIterator = currentParam.iterator(); final LispStruct firstInCurrent = currentIterator.next(); final LispStruct secondInCurrent; if (currentIterator.hasNext()) { secondInCurrent = currentIterator.next(); } else { secondInCurrent = NILStruct.INSTANCE; } final LispStruct thirdInCurrent; if (currentIterator.hasNext()) { thirdInCurrent = currentIterator.next(); } else { thirdInCurrent = NILStruct.INSTANCE; } final SymbolStruct varNameCurrent; final SymbolStruct varKeyNameCurrent; DestructuringLambdaList destructuringForm = null; if (firstInCurrent instanceof SymbolStruct) { varNameCurrent = (SymbolStruct) firstInCurrent; varKeyNameCurrent = getKeywordStruct(varNameCurrent.getName()); } else if (firstInCurrent instanceof ListStruct) { final ListStruct currentVar = (ListStruct) firstInCurrent; final long currentVarLength = currentVar.length().toJavaPLong(); if (currentVarLength == 2) { final LispStruct firstInCurrentVar = currentVar.car(); if (firstInCurrentVar instanceof SymbolStruct) { varKeyNameCurrent = (SymbolStruct) firstInCurrentVar; } else { throw new ProgramErrorException("LambdaList &key var name list key-name parameters must be a symbol: " + firstInCurrentVar); } final LispStruct secondInCurrentVar = ((ListStruct) currentVar.cdr()).car(); if (!(secondInCurrentVar instanceof SymbolStruct)) { throw new ProgramErrorException("LambdaList &key var name list name parameters must be a symbol: " + secondInCurrentVar); } varNameCurrent = (SymbolStruct) secondInCurrentVar; } else { if (isDestructuringAllowed) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); varKeyNameCurrent = getKeywordStruct(varNameCurrent.getName()); final ListStruct destructuringFormList = (ListStruct) currentElement; destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); } else { throw new ProgramErrorException("LambdaList &key var name list parameters must have 2 parameters: " + currentVar); } } } else { throw new ProgramErrorException("LambdaList &key var name parameters must be a symbol or a list: " + firstInCurrent); } LispStruct initForm = NILStruct.INSTANCE; if (!secondInCurrent.eq(NILStruct.INSTANCE)) { initForm = secondInCurrent; } final LispStruct parameterValueInitForm = FormAnalyzer.analyze(initForm, environment); final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(varNameCurrent)); Binding binding = new Binding(varNameCurrent, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final SuppliedPParameter suppliedPBinding; if (thirdInCurrent.eq(NILStruct.INSTANCE)) { final String paramName = varNameCurrent.getName(); final String customSuppliedPName = paramName + "-P-" + System.nanoTime(); final PackageStruct currentParamPackage = varNameCurrent.getSymbolPackage(); final SymbolStruct customSuppliedPCurrent = currentParamPackage.intern(customSuppliedPName).getSymbol(); final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(customSuppliedPCurrent)); binding = new Binding(customSuppliedPCurrent, CommonLispSymbols.T); if (isSuppliedPSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } suppliedPBinding = new SuppliedPParameter(customSuppliedPCurrent, isSuppliedPSpecial); } else { if (!(thirdInCurrent instanceof SymbolStruct)) { throw new ProgramErrorException("LambdaList &key supplied-p parameters must be a symbol: " + thirdInCurrent); } final SymbolStruct suppliedPCurrent = (SymbolStruct) thirdInCurrent; final boolean isSuppliedPSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(suppliedPCurrent)); binding = new Binding(suppliedPCurrent, CommonLispSymbols.T); if (isSuppliedPSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } suppliedPBinding = new SuppliedPParameter(suppliedPCurrent, isSuppliedPSpecial); } final KeyParameter keyBinding = new KeyParameter(varNameCurrent, destructuringForm, parameterValueInitForm, isSpecial, varKeyNameCurrent, suppliedPBinding); keyBindings.add(keyBinding); } } else { throw new ProgramErrorException("LambdaList &key parameters must be a symbol or a list: " + currentElement); } } while (iterator.hasNext()); return new KeyParseResult(currentElement, keyBindings); } public static AuxParseResult parseAuxBindings(final Environment environment, final Iterator<LispStruct> iterator, final DeclareStruct declareElement, final boolean isDestructuringAllowed) { final List<AuxParameter> auxBindings = new ArrayList<>(); if (!iterator.hasNext()) { return new AuxParseResult(null, auxBindings); } LispStruct currentElement; do { currentElement = iterator.next(); if (isLambdaListKeyword(currentElement)) { return new AuxParseResult(currentElement, auxBindings); } if (currentElement instanceof SymbolStruct) { final SymbolStruct currentParam = (SymbolStruct) currentElement; final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(currentParam)); final Binding binding = new Binding(currentParam, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final AuxParameter auxBinding = new AuxParameter(currentParam, null, NILStruct.INSTANCE, isSpecial); auxBindings.add(auxBinding); } else if (currentElement instanceof ListStruct) { final ListStruct currentParam = (ListStruct) currentElement; final long currentParamLength = currentParam.length().toJavaPLong(); if ((currentParamLength < 1) || (currentParamLength > 2)) { if (isDestructuringAllowed) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); final SymbolStruct varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final ListStruct destructuringFormList = (ListStruct) currentElement; final DestructuringLambdaList destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); final AuxParameter auxBinding = new AuxParameter(varNameCurrent, destructuringForm, NILStruct.INSTANCE); auxBindings.add(auxBinding); } else { throw new ProgramErrorException("LambdaList &aux parameters must have between 1 and 2 parameters: " + currentParam); } } else { final Iterator<LispStruct> currentIterator = currentParam.iterator(); final LispStruct firstInCurrent = currentIterator.next(); final LispStruct secondInCurrent; if (currentIterator.hasNext()) { secondInCurrent = currentIterator.next(); } else { secondInCurrent = NILStruct.INSTANCE; } final SymbolStruct varNameCurrent; DestructuringLambdaList destructuringForm = null; if (firstInCurrent instanceof SymbolStruct) { varNameCurrent = (SymbolStruct) firstInCurrent; } else { if (isDestructuringAllowed) { if (firstInCurrent instanceof ListStruct) { final String destructuringName = "DestructuringSymbolName-" + System.nanoTime(); varNameCurrent = GlobalPackageStruct.COMMON_LISP_USER.intern(destructuringName).getSymbol(); final ListStruct destructuringFormList = (ListStruct) firstInCurrent; destructuringForm = DestructuringLambdaListParser.parseDestructuringLambdaList(environment, destructuringFormList, declareElement); } else { throw new ProgramErrorException("LambdaList &aux var name parameter must be a symbol or a destructuring list: " + firstInCurrent); } } else { throw new ProgramErrorException("LambdaList &aux var name parameters must be a symbol: " + firstInCurrent); } } LispStruct initForm = NILStruct.INSTANCE; if (!secondInCurrent.eq(NILStruct.INSTANCE)) { initForm = secondInCurrent; } final LispStruct parameterValueInitForm = FormAnalyzer.analyze(initForm, environment); final boolean isSpecial = declareElement.getSpecialDeclarations() .stream() .map(SpecialDeclarationStruct::getVar) .anyMatch(Predicate.isEqual(varNameCurrent)); final Binding binding = new Binding(varNameCurrent, CommonLispSymbols.T); if (isSpecial) { environment.addDynamicBinding(binding); } else { environment.addLexicalBinding(binding); } final AuxParameter auxBinding = new AuxParameter(varNameCurrent, destructuringForm, parameterValueInitForm, isSpecial); auxBindings.add(auxBinding); } } else { throw new ProgramErrorException("LambdaList &aux parameters must be a symbol or a list: " + currentElement); } } while (iterator.hasNext()); return new AuxParseResult(currentElement, auxBindings); } private static boolean isLambdaListKeyword(final LispStruct lispStruct) { return lispStruct.eq(CompilerConstants.AUX) || lispStruct.eq(CompilerConstants.ALLOW_OTHER_KEYS) || lispStruct.eq(CompilerConstants.KEY) || lispStruct.eq(CompilerConstants.OPTIONAL) || lispStruct.eq(CompilerConstants.REST) || lispStruct.eq(CompilerConstants.WHOLE) || lispStruct.eq(CompilerConstants.ENVIRONMENT) || lispStruct.eq(CompilerConstants.BODY); } private static KeywordStruct getKeywordStruct(final String symbolName) { final PackageSymbolStruct symbol = GlobalPackageStruct.KEYWORD.findSymbol(symbolName); if (symbol.notFound()) { return KeywordStruct.toLispKeyword(symbolName); } // NOTE: This should be a safe cast because we're finding the symbol in the Keyword Package and they are only // this type of symbol. return (KeywordStruct) symbol.getSymbol(); } }
lgpl-3.0
Gals42/JSDOMBox
src/main/java/org/fit/cssbox/jsdombox/global/core/Attr.java
1112
/* * Attr.java * Copyright (c) Radim Kocman */ package org.fit.cssbox.jsdombox.global.core; import org.fit.cssbox.jsdombox.global.misc.JSAdapterFactory; import org.fit.cssbox.jsdombox.global.misc.JSAdapter; import org.fit.cssbox.jsdombox.global.misc.JSAdapterType; /** * DOM Interface Attr Adapter * * @author Radim Kocman */ public class Attr extends Node { protected org.w3c.dom.Attr source; public Attr(org.w3c.dom.Attr source, JSAdapterFactory jsaf) { super(source, jsaf); this.source = source; } // DOM Level 1 Implementation public String getName() { return source.getName().toLowerCase(); } public boolean getSpecified() { return source.getSpecified(); } public String getValue() { return source.getValue(); } public void setValue(String value) { source.setValue(value); jsaf.cssEvent.recomputeStyles(source); } // DOM Level 2 Implementation public JSAdapter getOwnerElement() { Object result = source.getOwnerElement(); return jsaf.create(result, JSAdapterType.ELEMENT); } }
lgpl-3.0
anndy201/mars-framework
com.sqsoft.mars.weixin.client/src/main/java/com/sqsoft/mars/weixin/client/cgibin/template/ApiSetIndustryRequest.java
1454
package com.sqsoft.mars.weixin.client.cgibin.template; import java.io.Serializable; import org.springframework.http.HttpMethod; import com.sqsoft.mars.core.common.utils.JsonUtils; import com.sqsoft.mars.weixin.client.WeixinRequest; /** * 设置所属行业 * @author whai888 * */ public class ApiSetIndustryRequest implements WeixinRequest<ApiSetIndustryResponse>, Serializable{ public ApiSetIndustryRequest(ApiSetIndustryPostVo apiSetIndustryPostVo) { super(); this.apiSetIndustryPostVo = apiSetIndustryPostVo; } /** * */ private static final long serialVersionUID = 1L; private ApiSetIndustryPostVo apiSetIndustryPostVo ; @Override public HttpMethod getHttpMethod() { // TODO Auto-generated method stub return HttpMethod.POST; } @Override public String getMethodScope() { // TODO Auto-generated method stub return null; } @Override public Class<ApiSetIndustryResponse> getResponseClass() { // TODO Auto-generated method stub return ApiSetIndustryResponse.class; } @Override public Object getRequestMessage() { // TODO Auto-generated method stub return JsonUtils.toJson(apiSetIndustryPostVo); } public ApiSetIndustryPostVo getApiSetIndustryPostVo() { return apiSetIndustryPostVo; } public void setApiSetIndustryPostVo(ApiSetIndustryPostVo apiSetIndustryPostVo) { this.apiSetIndustryPostVo = apiSetIndustryPostVo; } }
lgpl-3.0
xcourangon/lolongo
src/main/java/org/lolongo/FunctionContainer.java
1080
package org.lolongo; import java.util.ArrayList; import java.util.Iterator; import java.util.List; import org.slf4j.Logger; import org.slf4j.LoggerFactory; /** * A container of Functions. * * @author Xavier Courangon */ public class FunctionContainer implements Iterable<Function> { private static Logger logger = LoggerFactory.getLogger(FunctionContainer.class); final List<Function> functions = new ArrayList<>(); public FunctionContainer() { } // public FunctionContainer(Collection<Function> functions) { // for (final Function function : functions) { // this.functions.add(function); // } // } public void add(Function function) { if (function == null) { throw new IllegalArgumentException("function is null"); } else { logger.debug("adding Function {} into {}", function, this); functions.add(function); } } @Override public String toString() { final StringBuffer sb = new StringBuffer(getClass().getSimpleName()); return sb.toString(); } @Override public Iterator<Function> iterator() { return functions.iterator(); }; }
lgpl-3.0
Xyene/JBL
src/test/java/benchmark/bcel/classfile/ExceptionTable.java
6030
/* * Copyright 2000-2004 The Apache Software Foundation * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package benchmark.bcel.classfile; import java.io.DataInputStream; import java.io.DataOutputStream; import java.io.IOException; import benchmark.bcel.Constants; /** * This class represents the table of exceptions that are thrown by a * method. This attribute may be used once per method. The name of * this class is <em>ExceptionTable</em> for historical reasons; The * Java Virtual Machine Specification, Second Edition defines this * attribute using the name <em>Exceptions</em> (which is inconsistent * with the other classes). * * @version $Id: ExceptionTable.java 386056 2006-03-15 11:31:56Z tcurdt $ * @author <A HREF="mailto:m.dahm@gmx.de">M. Dahm</A> * @see Code */ public final class ExceptionTable extends Attribute { private int number_of_exceptions; // Table of indices into private int[] exception_index_table; // constant pool /** * Initialize from another object. Note that both objects use the same * references (shallow copy). Use copy() for a physical copy. */ public ExceptionTable(ExceptionTable c) { this(c.getNameIndex(), c.getLength(), c.getExceptionIndexTable(), c.getConstantPool()); } /** * @param name_index Index in constant pool * @param length Content length in bytes * @param exception_index_table Table of indices in constant pool * @param constant_pool Array of constants */ public ExceptionTable(int name_index, int length, int[] exception_index_table, ConstantPool constant_pool) { super(Constants.ATTR_EXCEPTIONS, name_index, length, constant_pool); setExceptionIndexTable(exception_index_table); } /** * Construct object from file stream. * @param name_index Index in constant pool * @param length Content length in bytes * @param file Input stream * @param constant_pool Array of constants * @throws IOException */ ExceptionTable(int name_index, int length, DataInputStream file, ConstantPool constant_pool) throws IOException { this(name_index, length, (int[]) null, constant_pool); number_of_exceptions = file.readUnsignedShort(); exception_index_table = new int[number_of_exceptions]; for (int i = 0; i < number_of_exceptions; i++) { exception_index_table[i] = file.readUnsignedShort(); } } /** * Called by objects that are traversing the nodes of the tree implicitely * defined by the contents of a Java class. I.e., the hierarchy of methods, * fields, attributes, etc. spawns a tree of objects. * * @param v Visitor object */ public void accept( Visitor v ) { v.visitExceptionTable(this); } /** * Dump exceptions attribute to file stream in binary format. * * @param file Output file stream * @throws IOException */ public final void dump( DataOutputStream file ) throws IOException { super.dump(file); file.writeShort(number_of_exceptions); for (int i = 0; i < number_of_exceptions; i++) { file.writeShort(exception_index_table[i]); } } /** * @return Array of indices into constant pool of thrown exceptions. */ public final int[] getExceptionIndexTable() { return exception_index_table; } /** * @return Length of exception table. */ public final int getNumberOfExceptions() { return number_of_exceptions; } /** * @return class names of thrown exceptions */ public final String[] getExceptionNames() { String[] names = new String[number_of_exceptions]; for (int i = 0; i < number_of_exceptions; i++) { names[i] = constant_pool.getConstantString(exception_index_table[i], Constants.CONSTANT_Class).replace('/', '.'); } return names; } /** * @param exception_index_table the list of exception indexes * Also redefines number_of_exceptions according to table length. */ public final void setExceptionIndexTable( int[] exception_index_table ) { this.exception_index_table = exception_index_table; number_of_exceptions = (exception_index_table == null) ? 0 : exception_index_table.length; } /** * @return String representation, i.e., a list of thrown exceptions. */ public final String toString() { StringBuffer buf = new StringBuffer(""); String str; for (int i = 0; i < number_of_exceptions; i++) { str = constant_pool.getConstantString(exception_index_table[i], Constants.CONSTANT_Class); buf.append(Utility.compactClassName(str, false)); if (i < number_of_exceptions - 1) { buf.append(", "); } } return buf.toString(); } /** * @return deep copy of this attribute */ public Attribute copy( ConstantPool _constant_pool ) { ExceptionTable c = (ExceptionTable) clone(); if (exception_index_table != null) { c.exception_index_table = new int[exception_index_table.length]; System.arraycopy(exception_index_table, 0, c.exception_index_table, 0, exception_index_table.length); } c.constant_pool = _constant_pool; return c; } }
lgpl-3.0
josejuansanchez/protocoder-mvd
protocoder_apprunner/src/main/java/org/protocoderrunner/apprunner/AppRunnerService.java
11875
package org.protocoderrunner.apprunner; import android.app.AlarmManager; import android.app.NotificationManager; import android.app.PendingIntent; import android.app.Service; import android.app.TaskStackBuilder; import android.content.BroadcastReceiver; import android.content.Context; import android.content.Intent; import android.content.IntentFilter; import android.graphics.PixelFormat; import android.os.IBinder; import android.os.Looper; import android.support.v4.app.NotificationCompat; import android.view.Gravity; import android.view.ViewGroup; import android.view.WindowManager; import android.widget.RelativeLayout; import android.widget.Toast; import org.protocoderrunner.R; import org.protocoderrunner.apprunner.api.PApp; import org.protocoderrunner.apprunner.api.PBoards; import org.protocoderrunner.apprunner.api.PConsole; import org.protocoderrunner.apprunner.api.PDashboard; import org.protocoderrunner.apprunner.api.PDevice; import org.protocoderrunner.apprunner.api.PFileIO; import org.protocoderrunner.apprunner.api.PMedia; import org.protocoderrunner.apprunner.api.PNetwork; import org.protocoderrunner.apprunner.api.PProtocoder; import org.protocoderrunner.apprunner.api.PSensors; import org.protocoderrunner.apprunner.api.PUI; import org.protocoderrunner.apprunner.api.PUtil; import org.protocoderrunner.apprunner.api.other.WhatIsRunning; import org.protocoderrunner.events.Events; import org.protocoderrunner.project.Project; import org.protocoderrunner.project.ProjectManager; import org.protocoderrunner.utils.MLog; import de.greenrobot.event.EventBus; //stopService //stopSelf public class AppRunnerService extends Service { private static final String SERVICE_CLOSE = "service_close"; private AppRunnerInterpreter interp; private final String TAG = "AppRunnerService"; private Project currentProject; public PApp pApp; public PBoards pBoards; public PConsole pConsole; public PDashboard pDashboard; public PDevice pDevice; public PFileIO pFileIO; public PMedia pMedia; public PNetwork pNetwork; public PProtocoder pProtocoder; public PSensors pSensors; public PUI pUi; public PUtil pUtil; private WindowManager windowManager; private RelativeLayout parentScriptedLayout; private RelativeLayout mainLayout; private BroadcastReceiver mReceiver; private NotificationManager mNotifManager; private PendingIntent mRestartPendingIntent; private Toast mToast; @Override public int onStartCommand(Intent intent, int flags, int startId) { // Can be called twice interp = new AppRunnerInterpreter(this); interp.createInterpreter(false); pApp = new PApp(this); //pApp.initForParentFragment(this); pBoards = new PBoards(this); pConsole = new PConsole(this); pDashboard = new PDashboard(this); pDevice = new PDevice(this); //pDevice.initForParentFragment(this); pFileIO = new PFileIO(this); pMedia = new PMedia(this); //pMedia.initForParentFragment(this); pNetwork = new PNetwork(this); //pNetwork.initForParentFragment(this); pProtocoder = new PProtocoder(this); pSensors = new PSensors(this); //pSensors.initForParentFragment(this); pUi = new PUI(this); pUi.initForParentService(this); //pUi.initForParentFragment(this); pUtil = new PUtil(this); interp.interpreter.addObjectToInterface("app", pApp); interp.interpreter.addObjectToInterface("boards", pBoards); interp.interpreter.addObjectToInterface("console", pConsole); interp.interpreter.addObjectToInterface("dashboard", pDashboard); interp.interpreter.addObjectToInterface("device", pDevice); interp.interpreter.addObjectToInterface("fileio", pFileIO); interp.interpreter.addObjectToInterface("media", pMedia); interp.interpreter.addObjectToInterface("network", pNetwork); interp.interpreter.addObjectToInterface("protocoder", pProtocoder); interp.interpreter.addObjectToInterface("sensors", pSensors); interp.interpreter.addObjectToInterface("ui", pUi); interp.interpreter.addObjectToInterface("util", pUtil); mainLayout = initLayout(); String projectName = intent.getStringExtra(Project.NAME); String projectFolder = intent.getStringExtra(Project.FOLDER); currentProject = ProjectManager.getInstance().get(projectFolder, projectName); ProjectManager.getInstance().setCurrentProject(currentProject); MLog.d(TAG, "launching " + projectName + " in " + projectFolder); AppRunnerSettings.get().project = currentProject; String script = ProjectManager.getInstance().getCode(currentProject); interp.evalFromService(script); //audio //AudioManager audio = (AudioManager) this.getSystemService(Context.AUDIO_SERVICE); //int currentVolume = audio.getStreamVolume(AudioManager.STREAM_MUSIC); //this.setVolumeControlStream(AudioManager.STREAM_MUSIC); windowManager = (WindowManager) getSystemService(WINDOW_SERVICE); boolean isTouchable = true; int touchParam; if (isTouchable) { touchParam = WindowManager.LayoutParams.TYPE_PHONE; } else { touchParam = WindowManager.LayoutParams.TYPE_SYSTEM_OVERLAY; } WindowManager.LayoutParams params = new WindowManager.LayoutParams( WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT, touchParam, WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE, PixelFormat.TRANSLUCENT); params.gravity = Gravity.TOP | Gravity.LEFT; params.x = 0; params.y = 0; windowManager.addView(mainLayout, params); // TEST //if (!EventBus.getDefault().isRegistered(this)) { // EventBus.getDefault().register(this); //} mNotifManager = (NotificationManager) AppRunnerService.this.getSystemService(Context.NOTIFICATION_SERVICE); int notificationId = (int) Math.ceil(100000 * Math.random()); createNotification(notificationId, projectFolder, projectName); //just in case it crash Intent restartIntent = new Intent("org.protocoder.LauncherActivity"); //getApplicationContext(), AppRunnerActivity.class); restartIntent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK); restartIntent.putExtra("wasCrash", true); // intent.setPackage("org.protocoder"); //intent.setClassName("org.protocoder", "MainActivity"); mRestartPendingIntent = PendingIntent.getActivity(AppRunnerService.this, 0, restartIntent, 0); mToast = Toast.makeText(AppRunnerService.this, "Crash :(", Toast.LENGTH_LONG); return Service.START_NOT_STICKY; } private void createNotification(final int notificationId, String scriptFolder, String scriptName) { IntentFilter filter = new IntentFilter(); filter.addAction(SERVICE_CLOSE); mReceiver = new BroadcastReceiver() { @Override public void onReceive(Context context, Intent intent) { if (intent.getAction().equals(SERVICE_CLOSE)) { AppRunnerService.this.stopSelf(); mNotifManager.cancel(notificationId); } } }; registerReceiver(mReceiver, filter); //RemoteViews remoteViews = new RemoteViews(getPackageName(), // R.layout.widget); Intent stopIntent = new Intent(SERVICE_CLOSE); PendingIntent pendingIntent = PendingIntent.getBroadcast(this, 0, stopIntent, 0); NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this) .setSmallIcon(R.drawable.app_icon) .setContentTitle(scriptName).setContentText("Running service: " + scriptFolder + " > " + scriptName) .setOngoing(false) .addAction(R.drawable.protocoder_icon, "stop", pendingIntent) .setDeleteIntent(pendingIntent); // Creates an explicit intent for an Activity in your app Intent resultIntent = new Intent(this, AppRunnerActivity.class); // The stack builder object will contain an artificial back stack for // navigating backward from the Activity leads out your application to the Home screen. TaskStackBuilder stackBuilder = TaskStackBuilder.create(this); stackBuilder.addParentStack(AppRunnerActivity.class); stackBuilder.addNextIntent(resultIntent); PendingIntent resultPendingIntent = stackBuilder.getPendingIntent(0, PendingIntent.FLAG_UPDATE_CURRENT); mBuilder.setContentIntent(resultPendingIntent); NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(this.NOTIFICATION_SERVICE); mNotificationManager.notify(notificationId, mBuilder.build()); Thread.setDefaultUncaughtExceptionHandler(handler); } Thread.UncaughtExceptionHandler handler = new Thread.UncaughtExceptionHandler() { @Override public void uncaughtException(Thread thread, Throwable ex) { new Thread() { @Override public void run() { Looper.prepare(); Toast.makeText(AppRunnerService.this, "lalll", Toast.LENGTH_LONG); Looper.loop(); } }.start(); // handlerToast.post(runnable); AlarmManager mgr = (AlarmManager) getSystemService(Context.ALARM_SERVICE); mgr.set(AlarmManager.RTC, System.currentTimeMillis() + 100, mRestartPendingIntent); mNotifManager.cancelAll(); android.os.Process.killProcess(android.os.Process.myPid()); System.exit(10); throw new RuntimeException(ex); } }; public void addScriptedLayout(RelativeLayout scriptedUILayout) { parentScriptedLayout.addView(scriptedUILayout); } public RelativeLayout initLayout() { ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT); // set the parent parentScriptedLayout = new RelativeLayout(this); parentScriptedLayout.setLayoutParams(layoutParams); parentScriptedLayout.setGravity(Gravity.BOTTOM); parentScriptedLayout.setBackgroundColor(getResources().getColor(R.color.transparent)); return parentScriptedLayout; } @Override public IBinder onBind(Intent intent) { // TODO for communication return IBinder implementation return null; } @Override public void onCreate() { super.onCreate(); MLog.d(TAG, "onCreate"); // interp.callJsFunction("onCreate"); // its called only once } @Override public void onDestroy() { super.onDestroy(); MLog.d(TAG, "onDestroy"); interp.callJsFunction("onDestroy"); windowManager.removeView(mainLayout); unregisterReceiver(mReceiver); WhatIsRunning.getInstance().stopAll(); interp = null; //EventBus.getDefault().unregister(this); } public void onEventMainThread(Events.ProjectEvent evt) { // Using transaction so the view blocks MLog.d(TAG, "event -> " + evt.getAction()); if (evt.getAction() == "stop") { stopSelf(); } } // execute lines public void onEventMainThread(Events.ExecuteCodeEvent evt) { String code = evt.getCode(); // .trim(); MLog.d(TAG, "event -> q " + code); interp.evalFromService(code); } }
lgpl-3.0
Farisllwaah/WorkflowSim-1.0
sources/org/workflowsim/scheduling/BaseSchedulingAlgorithm.java
2456
/** * Copyright 2012-2013 University Of Southern California * * Licensed under the Apache License, Version 2.0 (the "License"); you may not * use this file except in compliance with the License. You may obtain a copy of * the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, WITHOUT * WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the * License for the specific language governing permissions and limitations under * the License. */ package org.workflowsim.scheduling; import java.util.ArrayList; import java.util.List; import org.cloudbus.cloudsim.Cloudlet; import org.cloudbus.cloudsim.Vm; /** * The base scheduler has implemented the basic features. Every other scheduling method * should extend from BaseSchedulingAlgorithm but should not directly use it. * * @author Weiwei Chen * @since WorkflowSim Toolkit 1.0 * @date Apr 9, 2013 */ public abstract class BaseSchedulingAlgorithm implements SchedulingAlgorithmInterface { /** * the job list. */ private List<? extends Cloudlet> cloudletList; /** * the vm list. */ private List<? extends Vm> vmList; /** * the scheduled job list. */ private List< Cloudlet> scheduledList; /** * Initialize a BaseSchedulingAlgorithm */ public BaseSchedulingAlgorithm() { this.scheduledList = new ArrayList(); } /** * Sets the job list. * * @param list */ @Override public void setCloudletList(List list) { this.cloudletList = list; } /** * Sets the vm list * * @param list */ @Override public void setVmList(List list) { this.vmList = new ArrayList(list); } /** * Gets the job list. * * @return the job list */ @Override public List getCloudletList() { return this.cloudletList; } /** * Gets the vm list * * @return the vm list */ @Override public List getVmList() { return this.vmList; } /** * The main function */ public abstract void run() throws Exception; /** * Gets the scheduled job list * * @return job list */ @Override public List getScheduledList() { return this.scheduledList; } }
lgpl-3.0
rovemonteux/silvertunnel-monteux
src/main/java/cf/monteux/silvertunnel/netlib/layer/tor/circuit/cells/CellRelayEnd.java
1395
/** * OnionCoffee - Anonymous Communication through TOR Network * Copyright (C) 2005-2007 RWTH Aachen University, Informatik IV * * This program is free software; you can redistribute it and/or * modify it under the terms of the GNU General Public License * version 2 as published by the Free Software Foundation. * * This program is distributed in the hope that it will be useful, * but WITHOUT ANY WARRANTY; without even the implied warranty of * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the * GNU General Public License for more details. * * You should have received a copy of the GNU General Public License * along with this program; if not, write to the Free Software * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA */ package cf.monteux.silvertunnel.netlib.layer.tor.circuit.cells; import cf.monteux.silvertunnel.netlib.layer.tor.circuit.Stream; /** * sends an END cell, needed to close a tcp-stream. * * @author Lexi Pimenidis */ public class CellRelayEnd extends CellRelay { /** * constructor to build a ENDCELL. * * @param s * the stream that shall be closed * @param reason * a reason */ public CellRelayEnd(final Stream s, final byte reason) { // initialize a new Relay-cell super(s, CellRelay.RELAY_END); // set length setLength(1); data[0] = reason; } }
lgpl-3.0
iehudiel/nadia
src/com/ashokgelal/samaya/ToStringUtil.java
11583
package com.ashokgelal.samaya; import java.lang.reflect.InvocationTargetException; import java.lang.reflect.Method; import java.lang.reflect.Modifier; import java.util.ArrayList; import java.util.List; import java.util.StringTokenizer; import java.util.logging.Logger; import java.util.regex.Matcher; import java.util.regex.Pattern; /** Implements the <tt>toString</tt> method for some common cases. <P>This class is intended only for cases where <tt>toString</tt> is used in an informal manner (usually for logging and stack traces). It is especially suited for <tt>public</tt> classes which model domain objects. Here is an example of a return value of the {@link #getText} method : <PRE> hirondelle.web4j.model.MyUser { LoginName: Bob LoginPassword: **** EmailAddress: bob@blah.com StarRating: 1 FavoriteTheory: Quantum Chromodynamics SendCard: true Age: 42 DesiredSalary: 42000 BirthDate: Sat Feb 26 13:45:43 EST 2005 } </PRE> (Previous versions of this classes used indentation within the braces. That has been removed, since it displays poorly when nesting occurs.) <P>Here are two more examples, using classes taken from the JDK : <PRE> java.util.StringTokenizer { nextElement: This hasMoreElements: true countTokens: 3 nextToken: is hasMoreTokens: true } java.util.ArrayList { size: 3 toArray: [blah, blah, blah] isEmpty: false } </PRE> There are two use cases for this class. The typical use case is : <PRE> public String toString() { return ToStringUtil.getText(this); } </PRE> <span class="highlight">However, there is a case where this typical style can fail catastrophically</span> : when two objects reference each other, and each has <tt>toString</tt> implemented as above, then the program will loop indefinitely! <P>As a remedy for this problem, the following variation is provided : <PRE> public String toString() { return ToStringUtil.getTextAvoidCyclicRefs(this, Product.class, "getId"); } </PRE> Here, the usual behavior is overridden for any method which returns a <tt>Product</tt> : instead of calling <tt>Product.toString</tt>, the return value of <tt>Product.getId()</tt> is used to textually represent the object. */ final class ToStringUtil { /** Return an informal textual description of an object. <P>It is highly recommened that the caller <em>not</em> rely on details of the returned <tt>String</tt>. See class description for examples of return values. <P><span class="highlight">WARNING</span>: If two classes have cyclic references (that is, each has a reference to the other), then infinite looping will result if <em>both</em> call this method! To avoid this problem, use <tt>getText</tt> for one of the classes, and {@link #getTextAvoidCyclicRefs} for the other class. <P>The only items which contribute to the result are the class name, and all no-argument <tt>public</tt> methods which return a value. As well, methods defined by the <tt>Object</tt> class, and factory methods which return an <tt>Object</tt> of the native class ("<tt>getInstance</tt>" methods) do not contribute. <P>Items are converted to a <tt>String</tt> simply by calling their <tt>toString method</tt>, with these exceptions : <ul> <li>{@link Util#getArrayAsString(Object)} is used for arrays <li>a method whose name contain the text <tt>"password"</tt> (not case-sensitive) have their return values hard-coded to <tt>"****"</tt>. </ul> <P>If the method name follows the pattern <tt>getXXX</tt>, then the word 'get' is removed from the presented result. @param aObject the object for which a <tt>toString</tt> result is required. */ static String getText(Object aObject) { return getTextAvoidCyclicRefs(aObject, null, null); } /** As in {@link #getText}, but, for return values which are instances of <tt>aSpecialClass</tt>, then call <tt>aMethodName</tt> instead of <tt>toString</tt>. <P> If <tt>aSpecialClass</tt> and <tt>aMethodName</tt> are <tt>null</tt>, then the behavior is exactly the same as calling {@link #getText}. */ static String getTextAvoidCyclicRefs(Object aObject, Class aSpecialClass, String aMethodName) { StringBuilder result = new StringBuilder(); addStartLine(aObject, result); Method[] methods = aObject.getClass().getDeclaredMethods(); for(Method method: methods){ if ( isContributingMethod(method, aObject.getClass()) ){ addLineForGetXXXMethod(aObject, method, result, aSpecialClass, aMethodName); } } addEndLine(result); return result.toString(); } // PRIVATE // /* Names of methods in the <tt>Object</tt> class which are ignored. */ private static final String fGET_CLASS = "getClass"; private static final String fCLONE = "clone"; private static final String fHASH_CODE = "hashCode"; private static final String fTO_STRING = "toString"; private static final String fGET = "get"; private static final Object[] fNO_ARGS = new Object[0]; private static final Class[] fNO_PARAMS = new Class[0]; /* Previous versions of this class indented the data within a block. That style breaks when one object references another. The indentation has been removed, but this variable has been retained, since others might prefer the indentation anyway. */ private static final String fINDENT = ""; private static final String fAVOID_CIRCULAR_REFERENCES = "[circular reference]"; private static final Logger fLogger = Util.getLogger(ToStringUtil.class); private static final String NEW_LINE = System.getProperty("line.separator"); private static Pattern PASSWORD_PATTERN = Pattern.compile("password", Pattern.CASE_INSENSITIVE); private static String HIDDEN_PASSWORD_VALUE = "****"; //prevent construction by the caller private ToStringUtil() { //empty } private static void addStartLine(Object aObject, StringBuilder aResult){ aResult.append( aObject.getClass().getName() ); aResult.append(" {"); aResult.append(NEW_LINE); } private static void addEndLine(StringBuilder aResult){ aResult.append("}"); aResult.append(NEW_LINE); } /** Return <tt>true</tt> only if <tt>aMethod</tt> is public, takes no args, returns a value whose class is not the native class, is not a method of <tt>Object</tt>. */ private static boolean isContributingMethod(Method aMethod, Class aNativeClass){ boolean isPublic = Modifier.isPublic( aMethod.getModifiers() ); boolean hasNoArguments = aMethod.getParameterTypes().length == 0; boolean hasReturnValue = aMethod.getReturnType() != Void.TYPE; boolean returnsNativeObject = aMethod.getReturnType() == aNativeClass; boolean isMethodOfObjectClass = aMethod.getName().equals(fCLONE) || aMethod.getName().equals(fGET_CLASS) || aMethod.getName().equals(fHASH_CODE) || aMethod.getName().equals(fTO_STRING) ; return isPublic && hasNoArguments && hasReturnValue && ! isMethodOfObjectClass && ! returnsNativeObject; } private static void addLineForGetXXXMethod( Object aObject, Method aMethod, StringBuilder aResult, Class aCircularRefClass, String aCircularRefMethodName ){ aResult.append(fINDENT); aResult.append( getMethodNameMinusGet(aMethod) ); aResult.append(": "); Object returnValue = getMethodReturnValue(aObject, aMethod); if ( returnValue != null && returnValue.getClass().isArray() ) { aResult.append( Util.getArrayAsString(returnValue) ); } else { if (aCircularRefClass == null) { aResult.append( returnValue ); } else { if (aCircularRefClass == returnValue.getClass()) { Method method = getMethodFromName(aCircularRefClass, aCircularRefMethodName); if ( isContributingMethod(method, aCircularRefClass)){ returnValue = getMethodReturnValue(returnValue, method); aResult.append( returnValue ); } else { aResult.append(fAVOID_CIRCULAR_REFERENCES); } } } } aResult.append( NEW_LINE ); } private static String getMethodNameMinusGet(Method aMethod){ String result = aMethod.getName(); if (result.startsWith(fGET) ) { result = result.substring(fGET.length()); } return result; } /** Return value is possibly-null. */ private static Object getMethodReturnValue(Object aObject, Method aMethod){ Object result = null; try { result = aMethod.invoke(aObject, fNO_ARGS); } catch (IllegalAccessException ex){ vomit(aObject, aMethod); } catch (InvocationTargetException ex){ vomit(aObject, aMethod); } result = dontShowPasswords(result, aMethod); return result; } private static Method getMethodFromName(Class aSpecialClass, String aMethodName){ Method result = null; try { result = aSpecialClass.getMethod(aMethodName, fNO_PARAMS); } catch ( NoSuchMethodException ex){ vomit(aSpecialClass, aMethodName); } return result; } private static void vomit(Object aObject, Method aMethod){ fLogger.severe( "Cannot get return value using reflection. Class: " + aObject.getClass().getName() + " Method: " + aMethod.getName() ); } private static void vomit(Class aSpecialClass, String aMethodName){ fLogger.severe( "Reflection fails to get no-arg method named: " + Util.quote(aMethodName) + " for class: " + aSpecialClass.getName() ); } private static Object dontShowPasswords(Object aReturnValue, Method aMethod){ Object result = aReturnValue; Matcher matcher = PASSWORD_PATTERN.matcher(aMethod.getName()); if ( matcher.find()) { result = HIDDEN_PASSWORD_VALUE; } return result; } /* Two informal classes with cyclic references, used for testing. */ private static final class Ping { public void setPong(Pong aPong){fPong = aPong; } public Pong getPong(){ return fPong; } public Integer getId() { return new Integer(123); } public String getUserPassword(){ return "blah"; } public String toString() { return getText(this); } private Pong fPong; } private static final class Pong { public void setPing(Ping aPing){ fPing = aPing; } public Ping getPing() { return fPing; } public String toString() { return getTextAvoidCyclicRefs(this, Ping.class, "getId"); //to see the infinite looping, use this instead : //return getText(this); } private Ping fPing; } /** Informal test harness. */ public static void main (String... args) { List<String> list = new ArrayList<String>(); list.add("blah"); list.add("blah"); list.add("blah"); System.out.println( ToStringUtil.getText(list) ); StringTokenizer parser = new StringTokenizer("This is the end."); System.out.println( ToStringUtil.getText(parser) ); Ping ping = new Ping(); Pong pong = new Pong(); ping.setPong(pong); pong.setPing(ping); System.out.println( ping ); System.out.println( pong ); } }
lgpl-3.0
btrplace/scheduler
split/src/test/java/org/btrplace/scheduler/runner/disjoint/splitter/SleepingSplitterTest.java
2916
/* * Copyright 2020 The BtrPlace Authors. All rights reserved. * Use of this source code is governed by a LGPL-style * license that can be found in the LICENSE.txt file. */ package org.btrplace.scheduler.runner.disjoint.splitter; import gnu.trove.map.hash.TIntIntHashMap; import org.btrplace.model.DefaultModel; import org.btrplace.model.Instance; import org.btrplace.model.Model; import org.btrplace.model.Node; import org.btrplace.model.VM; import org.btrplace.model.constraint.MinMTTR; import org.btrplace.model.constraint.Sleeping; import org.btrplace.scheduler.runner.disjoint.Instances; import org.testng.Assert; import org.testng.annotations.Test; import java.util.ArrayList; import java.util.HashSet; import java.util.List; import java.util.Set; /** * Unit tests for {@link org.btrplace.scheduler.choco.runner.disjoint.splitter.SleepingSplitter}. * * @author Fabien Hermenier */ public class SleepingSplitterTest { @Test public void simpleTest() { SleepingSplitter splitter = new SleepingSplitter(); List<Instance> instances = new ArrayList<>(); Model origin = new DefaultModel(); Node n1 = origin.newNode(); Node n2 = origin.newNode(); VM vm1 = origin.newVM(); VM vm2 = origin.newVM(); VM vm3 = origin.newVM(); VM vm4 = origin.newVM(); /** * READY: vm1 * n1 vm2 * n2 (vm3) vm4 */ origin.getMapping().addOnlineNode(n1); origin.getMapping().addReadyVM(vm1); origin.getMapping().addRunningVM(vm2, n1); origin.getMapping().addOnlineNode(n2); origin.getMapping().addSleepingVM(vm3, n2); origin.getMapping().addRunningVM(vm4, n2); Model m0 = new DefaultModel(); m0.newNode(n1.id()); m0.newVM(vm1.id()); m0.newVM(vm2.id()); m0.getMapping().addOnlineNode(n1); m0.getMapping().addReadyVM(vm1); m0.getMapping().addRunningVM(vm2, n1); Model m1 = new DefaultModel(); m1.newNode(n2.id()); m1.newVM(vm3.id()); m1.newVM(vm4.id()); m1.getMapping().addOnlineNode(n2); m1.getMapping().addSleepingVM(vm3, n2); m1.getMapping().addRunningVM(vm4, n2); instances.add(new Instance(m0, new ArrayList<>(), new MinMTTR())); instances.add(new Instance(m1, new ArrayList<>(), new MinMTTR())); Set<VM> all = new HashSet<>(m0.getMapping().getAllVMs()); all.addAll(m1.getMapping().getAllVMs()); TIntIntHashMap index = Instances.makeVMIndex(instances); //Only VMs in m0 Sleeping single = new Sleeping(vm2); Assert.assertTrue(splitter.split(single, null, instances, index, new TIntIntHashMap())); Assert.assertTrue(instances.get(0).getSatConstraints().contains(single)); Assert.assertFalse(instances.get(1).getSatConstraints().contains(single)); } }
lgpl-3.0
Godin/sonar
server/sonar-ce-task-projectanalysis/src/main/java/org/sonar/ce/task/projectanalysis/issue/ComponentIssuesRepositoryImpl.java
2261
/* * SonarQube * Copyright (C) 2009-2019 SonarSource SA * mailto:info AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.ce.task.projectanalysis.issue; import java.util.Collections; import java.util.List; import javax.annotation.CheckForNull; import org.sonar.ce.task.projectanalysis.component.Component; import org.sonar.core.issue.DefaultIssue; import static com.google.common.base.Preconditions.checkArgument; import static com.google.common.base.Preconditions.checkState; import static java.util.Objects.requireNonNull; public class ComponentIssuesRepositoryImpl implements MutableComponentIssuesRepository { @CheckForNull private List<DefaultIssue> issues; @CheckForNull private Component component; @Override public void setIssues(Component component, List<DefaultIssue> issues) { this.issues = requireNonNull(issues, "issues cannot be null"); this.component = requireNonNull(component, "component cannot be null"); } @Override public List<DefaultIssue> getIssues(Component component) { if (component.getType() == Component.Type.DIRECTORY) { // No issues on directories return Collections.emptyList(); } checkState(this.component != null && this.issues != null, "Issues have not been initialized"); checkArgument(component.equals(this.component), "Only issues from component '%s' are available, but wanted component is '%s'.", this.component.getReportAttributes().getRef(), component.getReportAttributes().getRef()); return issues; } }
lgpl-3.0
MatofSteel1/SoulGlassModv1.0
src/main/java/com/MatofSteel1/soulglassmod/item/ItemSoulGlassMod.java
3035
package com.MatofSteel1.soulglassmod.item; import com.MatofSteel1.soulglassmod.creativetab.CreativeTabSGM; import com.MatofSteel1.soulglassmod.inventory.ItemInventory; import com.MatofSteel1.soulglassmod.reference.Reference; import com.MatofSteel1.soulglassmod.utility.InventoryUtils; import cpw.mods.fml.common.eventhandler.SubscribeEvent; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import net.minecraft.client.renderer.texture.IIconRegister; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.item.Item; import net.minecraft.item.ItemStack; import net.minecraft.world.World; import net.minecraftforge.event.entity.player.EntityItemPickupEvent; public class ItemSoulGlassMod extends Item { public ItemSoulGlassMod() { super(); this.setCreativeTab(CreativeTabSGM.SoulGlassMod_TAB); } @Override public String getUnlocalizedName() { return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override public String getUnlocalizedName(ItemStack itemStack) { return String.format("item.%s%s", Reference.MOD_ID.toLowerCase() + ":", getUnwrappedUnlocalizedName(super.getUnlocalizedName())); } @Override @SideOnly(Side.CLIENT) public void registerIcons(IIconRegister iconRegister) { itemIcon = iconRegister.registerIcon(this.getUnlocalizedName().substring(this.getUnlocalizedName().indexOf(".") + 1)); } protected String getUnwrappedUnlocalizedName(String unlocalizedName) { return unlocalizedName.substring(unlocalizedName.indexOf(".") + 1); } @SubscribeEvent public void onItemPickUp(EntityItemPickupEvent evt) { final EntityPlayer player = evt.entityPlayer; final ItemStack pickedStack = evt.item.getEntityItem(); if (pickedStack == null || player == null) return; boolean foundMatchingContainer = false; for (int i = 0; i < player.inventory.getSizeInventory(); i++) { ItemStack stack = player.inventory.getStackInSlot(i); if (stack != null && stack.getItem() == (this)) { ItemInventory inventory = new ItemInventory(stack, 1); ItemStack containedStack = inventory.getStackInSlot(0); if (containedStack != null) { boolean isMatching = InventoryUtils.areItemAndTagEqual(pickedStack, containedStack); if (isMatching) { foundMatchingContainer = true; InventoryUtils.tryInsertStack(inventory, 0, pickedStack, true); } } } } if (foundMatchingContainer) pickedStack.stackSize = 0; } public boolean placeBlockAt(ItemStack stack, EntityPlayer player, World world, int x, int y, int z, int side, float hitX, float hitY, float hitZ, int metadata) { stack.stackSize++; return true; } }
lgpl-3.0
rpau/javalang
src/main/java/org/walkmod/javalang/ast/LineComment.java
1807
/* * Copyright (C) 2013 Raquel Pau and Albert Coroleu. * * Walkmod 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. * * Walkmod 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 Walkmod. If * not, see <http://www.gnu.org/licenses/>. */ package org.walkmod.javalang.ast; import org.walkmod.javalang.visitors.GenericVisitor; import org.walkmod.javalang.visitors.VoidVisitor; /** * <p> * AST node that represent line comments. * </p> * Line comments are started with "//" and finish at the end of the line ("\n"). * * @author Julio Vilmar Gesser */ public final class LineComment extends Comment { public LineComment() {} public LineComment(String content) { super(content); } public LineComment(int beginLine, int beginColumn, int endLine, int endColumn, String content) { super(beginLine, beginColumn, endLine, endColumn, content); } @Override public <R, A> R accept(GenericVisitor<R, A> v, A arg) { if (!check()) { return null; } return v.visit(this, arg); } @Override public <A> void accept(VoidVisitor<A> v, A arg) { if (check()) { v.visit(this, arg); } } @Override public LineComment clone() throws CloneNotSupportedException { return new LineComment(getContent()); } }
lgpl-3.0
smallAreaHealthStatisticsUnit/rapidInquiryFacility
rifGenericLibrary/src/main/java/org/sahsu/rif/generic/presentation/WorkflowNavigationButtonPanel.java
7055
package org.sahsu.rif.generic.presentation; import java.awt.BorderLayout; import java.awt.GridBagConstraints; import java.awt.event.ActionListener; import javax.swing.JButton; import javax.swing.JPanel; import org.sahsu.rif.generic.system.Messages; /** * * A generic button control panel that supports navigation through a work flow. Only buttons that * can be pressed appear in any state. For example, if the work flow is set on the first state, * the previous and first button will not show. It also suggests the distinction between "First" and * "Start Again" buttons. The "First" button is meant to move the work flow to the first step in the * work flow. In a workflow, it is meant to suggest that if you go back to the first step, you will * preserve the work you've done in that step. "Start Again" suggests that when the work flow moves * to the first step, but all changed all the work done before will be discarded. * * <hr> * Copyright 2017 Imperial College London, developed by the Small Area * Health Statistics Unit. * * <pre> * This file is part of the Rapid Inquiry Facility (RIF) project. * RIF 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. * RIF 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 RIF. If not, see <http://www.gnu.org/licenses/>. * </pre> * * <hr> * Kevin Garwood * @author kgarwood */ /* * Code Road Map: * -------------- * Code is organised into the following sections. Wherever possible, * methods are classified based on an order of precedence described in * parentheses (..). For example, if you're trying to find a method * 'getName(...)' that is both an interface method and an accessor * method, the order tells you it should appear under interface. * * Order of * Precedence Section * ========== ====== * (1) Section Constants * (2) Section Properties * (3) Section Construction * (7) Section Accessors and Mutators * (6) Section Errors and Validation * (5) Section Interfaces * (4) Section Override * */ public final class WorkflowNavigationButtonPanel extends AbstractNavigationPanel { // ========================================== // Section Constants // ========================================== private static final Messages GENERIC_MESSAGES = Messages.genericMessages(); // ========================================== // Section Properties // ========================================== private JPanel panel; private JButton startAgainButton; private JButton submitButton; private JButton quitButton; // ========================================== // Section Construction // ========================================== public WorkflowNavigationButtonPanel( final UserInterfaceFactory userInterfaceFactory) { super(userInterfaceFactory); String submitButtonText = GENERIC_MESSAGES.getMessage("buttons.submit.label"); submitButton = userInterfaceFactory.createButton(submitButtonText); String quitButtonText = GENERIC_MESSAGES.getMessage("buttons.quit.label"); quitButton = userInterfaceFactory.createButton(quitButtonText); panel = userInterfaceFactory.createBorderLayoutPanel(); } public void startAgainButton(JButton startAgainButton) { this.startAgainButton = startAgainButton; } public boolean isStartAgainButton(Object item) { if (startAgainButton == null) { return false; } return startAgainButton.equals(item); } // ========================================== // Section Accessors and Mutators // ========================================== public boolean isQuitButton( final Object item) { if (item == null) { return false; } return quitButton.equals(item); } public boolean isSubmitButton( final Object item) { if (item == null) { return false; } return submitButton.equals(item); } public void showStartState() { panel.removeAll(); JPanel rightPanel = userInterfaceFactory.createPanel(); GridBagConstraints rightPanelGC = userInterfaceFactory.createGridBagConstraints(); rightPanel.add(nextButton, rightPanelGC); rightPanelGC.gridx++; rightPanel.add(quitButton, rightPanelGC); rightPanelGC.anchor = GridBagConstraints.SOUTHEAST; panel.add(rightPanel, BorderLayout.EAST); panel.updateUI(); } public void showMiddleState() { panel.removeAll(); panel.add(createLeftPanel(), BorderLayout.WEST); JPanel rightPanel = userInterfaceFactory.createPanel(); GridBagConstraints rightPanelGC = userInterfaceFactory.createGridBagConstraints(); rightPanel.add(firstButton, rightPanelGC); rightPanelGC.gridx++; rightPanel.add(previousButton, rightPanelGC); rightPanelGC.gridx++; rightPanel.add(nextButton, rightPanelGC); rightPanelGC.gridx++; rightPanel.add(quitButton, rightPanelGC); rightPanelGC.anchor = GridBagConstraints.SOUTHEAST; panel.add(rightPanel, BorderLayout.EAST); panel.updateUI(); } public void showEndState() { panel.removeAll(); panel.add(createLeftPanel(), BorderLayout.WEST); JPanel rightPanel = userInterfaceFactory.createPanel(); GridBagConstraints rightPanelGC = userInterfaceFactory.createGridBagConstraints(); rightPanelGC.anchor = GridBagConstraints.SOUTHEAST; rightPanel.add(firstButton, rightPanelGC); rightPanelGC.gridx++; rightPanel.add(previousButton, rightPanelGC); rightPanelGC.gridx++; rightPanel.add(submitButton, rightPanelGC); panel.add(rightPanel, BorderLayout.EAST); panel.updateUI(); } private JPanel createLeftPanel() { JPanel panel = userInterfaceFactory.createPanel(); if (startAgainButton != null) { GridBagConstraints panelGC = userInterfaceFactory.createGridBagConstraints(); panelGC.anchor = GridBagConstraints.SOUTHWEST; panel.add(startAgainButton, panelGC); } return panel; } public JPanel getPanel() { return panel; } public void addActionListener( final ActionListener actionListener) { super.addActionListener(actionListener); startAgainButton.addActionListener(actionListener); submitButton.addActionListener(actionListener); quitButton.addActionListener(actionListener); } // ========================================== // Section Errors and Validation // ========================================== // ========================================== // Section Interfaces // ========================================== // ========================================== // Section Override // ========================================== }
lgpl-3.0
test2v/DanDelXAdES
proj/xml-security-src-1_3_0/xml-security-1_3_0/src_unitTests/org/apache/xml/security/test/EncryptionTest.java
2150
/* * Copyright 2003-2004 The Apache Software Foundation. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. * */ package org.apache.xml.security.test; import junit.framework.Test; import junit.framework.TestCase; import junit.framework.TestSuite; import junit.textui.TestRunner; import org.apache.xml.security.test.encryption.BaltimoreEncTest; import org.apache.xml.security.test.encryption.XMLCipherTester; public class EncryptionTest extends TestCase { public EncryptionTest(String test) { super(test); } public static void main(String[] args) { org.apache.xml.security.Init.init(); processCmdLineArgs(args); TestRunner.run(suite()); } public static Test suite() { TestSuite suite = new TestSuite("DOM XML Encryption Tests"); suite.addTest(new TestSuite(XMLCipherTester.class)); suite.addTest(new TestSuite(BaltimoreEncTest.class)); return (suite); } private static void processCmdLineArgs(String[] args) { for (int i = 0; i < args.length; i++) { if (args[i].startsWith("-d")) { String doc = args[i].substring(2).trim(); System.setProperty("org.apache.xml.enc.test.doc", doc); } else if (args[i].startsWith("-e")) { String elem = args[i].substring(2).trim(); System.setProperty("org.apache.xml.enc.test.elem", elem); } else if (args[i].startsWith("-i")) { String idx = args[i].substring(2).trim(); System.setProperty("org.apache.xml.enc.test.idx", idx); } } } }
lgpl-3.0
onebeartoe/photorama
photorama-model/src/main/java/org/onebeartoe/electronics/photorama/Camera.java
1941
package org.onebeartoe.electronics.photorama; import java.io.File; /** * A call to the setCameraOutputPath() method is needed after the object is * instantiated. * * @author Roberto Marquez */ public abstract class Camera { protected PhotoramaModes mode; protected String outputPath; protected TimeLapseConfiguration configuration; protected boolean timeLapseOn; public PhotoramaModes getMode() { return mode; } public String getOutputPath() { return outputPath; } public abstract long getTimelapse(); public FrequencyUnits getTimelapseUnit() { return configuration.unit; } public void setMode(PhotoramaModes mode) { this.mode = mode; stopTimelapse(); } /** * Make sure the path has a path separator character at the end. * @param path */ public void setOutputPath(String path) throws Exception { File outdir = new File(path); if( ! outdir.exists() ) { // the output directory does not exist, // try creating it boolean dirCreated = outdir.mkdirs(); if( !dirCreated ) { String message = "could not set output directory: " + path; throw new Exception(message); } } outputPath = path; } public void setTimelapse(long delay, FrequencyUnits unit) { configuration.delay = delay; configuration.unit = unit; if(timeLapseOn) { startTimelapse(); } } public abstract void startTimelapse(); public abstract void stopTimelapse(); public abstract void takeSnapshot(); }
lgpl-3.0
chuidiang/chuidiang-ejemplos
JAVA/hazelcast-example/src/main/java/com/chuidiang/ejemplos/subscription/MyDataSerializer.java
1236
package com.chuidiang.ejemplos.subscription; import com.esotericsoftware.kryo.Kryo; import com.esotericsoftware.kryo.io.Input; import com.esotericsoftware.kryo.io.Output; import com.hazelcast.nio.ObjectDataInput; import com.hazelcast.nio.ObjectDataOutput; import com.hazelcast.nio.serialization.StreamSerializer; import java.io.ByteArrayOutputStream; import java.io.IOException; public class MyDataSerializer implements StreamSerializer<Object>{ @Override public void write(ObjectDataOutput objectDataOutput, Object data) throws IOException { Kryo kryo = new Kryo(); ByteArrayOutputStream bos = new ByteArrayOutputStream(); Output output = new Output(bos); kryo.writeClassAndObject(output, data); objectDataOutput.writeByteArray(output.getBuffer()); } @Override public Object read(ObjectDataInput objectDataInput) throws IOException { Kryo kryo = new Kryo(); byte [] buffer = objectDataInput.readByteArray(); Input input = new Input(buffer); Object data = kryo.readClassAndObject(input); return data; } @Override public int getTypeId() { return 1; } @Override public void destroy() { } }
lgpl-3.0
aaron-santos/lanterna
src/test/java/com/googlecode/lanterna/test/TestAllCodes.java
1398
/* * This file is part of lanterna (http://code.google.com/p/lanterna/). * * lanterna 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/>. * * Copyright (C) 2010-2014 Martin */ package com.googlecode.lanterna.test; /** * Prints the whole symbol table, this is debug stuff for UTF-8 to non-UTF-8 * symbol character conversions... * @author Martin */ public class TestAllCodes { public static void main(String[] args) throws Exception { System.out.write(new byte[] { (byte)0x1B, 0x28, 0x30 }); for(int i = 0; i < 200; i++) { System.out.write((i + " = " + ((char)i) + "\n").getBytes()); } System.out.write(new byte[] { (byte)0x1B, 0x28, 0x42 }); //System.out.write(new byte[] { (byte)0x1B, (byte)0x21, (byte)0x40, 15 }); } }
lgpl-3.0
rui-castro/roda
roda-ui/roda-wui/src/main/java/org/roda/wui/client/planning/EditFormat.java
6316
/** * The contents of this file are subject to the license and copyright * detailed in the LICENSE file at the root of the source * tree and available online at * * https://github.com/keeps/roda */ package org.roda.wui.client.planning; import java.util.Arrays; import java.util.List; import org.roda.core.data.common.RodaConstants; import org.roda.core.data.exceptions.NotFoundException; import org.roda.core.data.v2.formats.Format; import org.roda.core.data.v2.index.select.SelectedItemsList; import org.roda.wui.client.browse.BrowserService; import org.roda.wui.client.common.UserLogin; import org.roda.wui.client.common.utils.AsyncCallbackUtils; import org.roda.wui.client.common.utils.JavascriptUtils; import org.roda.wui.client.management.MemberManagement; import org.roda.wui.common.client.HistoryResolver; import org.roda.wui.common.client.tools.HistoryUtils; import org.roda.wui.common.client.tools.ListUtils; import org.roda.wui.common.client.widgets.Toast; import com.google.gwt.core.client.GWT; import com.google.gwt.event.dom.client.ClickEvent; import com.google.gwt.uibinder.client.UiBinder; import com.google.gwt.uibinder.client.UiField; import com.google.gwt.uibinder.client.UiHandler; import com.google.gwt.user.client.Timer; import com.google.gwt.user.client.rpc.AsyncCallback; import com.google.gwt.user.client.ui.Button; import com.google.gwt.user.client.ui.Composite; import com.google.gwt.user.client.ui.Widget; import config.i18n.client.ClientMessages; public class EditFormat extends Composite { public static final HistoryResolver RESOLVER = new HistoryResolver() { @Override public void resolve(List<String> historyTokens, final AsyncCallback<Widget> callback) { if (historyTokens.size() == 1) { String formatId = historyTokens.get(0); BrowserService.Util.getInstance().retrieve(Format.class.getName(), formatId, fieldsToReturn, new AsyncCallback<Format>() { @Override public void onFailure(Throwable caught) { callback.onFailure(caught); } @Override public void onSuccess(Format format) { EditFormat editFormat = new EditFormat(format); callback.onSuccess(editFormat); } }); } else { HistoryUtils.newHistory(FormatRegister.RESOLVER); callback.onSuccess(null); } } @Override public void isCurrentUserPermitted(AsyncCallback<Boolean> callback) { UserLogin.getInstance().checkRoles(new HistoryResolver[] {MemberManagement.RESOLVER}, false, callback); } @Override public List<String> getHistoryPath() { return ListUtils.concat(FormatRegister.RESOLVER.getHistoryPath(), getHistoryToken()); } @Override public String getHistoryToken() { return "edit_format"; } }; interface MyUiBinder extends UiBinder<Widget, EditFormat> { } private static MyUiBinder uiBinder = GWT.create(MyUiBinder.class); private static ClientMessages messages = GWT.create(ClientMessages.class); private Format format; private static final List<String> fieldsToReturn = Arrays.asList(RodaConstants.INDEX_UUID, RodaConstants.FORMAT_ID, RodaConstants.FORMAT_NAME, RodaConstants.FORMAT_DEFINITION, RodaConstants.FORMAT_CATEGORY, RodaConstants.FORMAT_LATEST_VERSION, RodaConstants.FORMAT_DEVELOPER, RodaConstants.FORMAT_POPULARITY, RodaConstants.FORMAT_INITIAL_RELEASE, RodaConstants.FORMAT_IS_OPEN_FORMAT, RodaConstants.FORMAT_STANDARD, RodaConstants.FORMAT_WEBSITE, RodaConstants.FORMAT_PROVENANCE_INFORMATION, RodaConstants.FORMAT_EXTENSIONS, RodaConstants.FORMAT_MIMETYPES, RodaConstants.FORMAT_PRONOMS, RodaConstants.FORMAT_UTIS, RodaConstants.FORMAT_ALTERNATIVE_DESIGNATIONS, RodaConstants.FORMAT_VERSIONS); @UiField Button buttonApply; @UiField Button buttonRemove; @UiField Button buttonCancel; @UiField(provided = true) FormatDataPanel formatDataPanel; /** * Create a new panel to create a user * * @param user * the user to create */ public EditFormat(Format format) { this.format = format; this.formatDataPanel = new FormatDataPanel(true, true, format); initWidget(uiBinder.createAndBindUi(this)); } @Override protected void onLoad() { super.onLoad(); JavascriptUtils.stickSidebar(); } @UiHandler("buttonApply") void buttonApplyHandler(ClickEvent e) { if (formatDataPanel.isChanged() && formatDataPanel.isValid()) { String formatId = format.getId(); format = formatDataPanel.getFormat(); format.setId(formatId); BrowserService.Util.getInstance().updateFormat(format, new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { errorMessage(caught); } @Override public void onSuccess(Void result) { HistoryUtils.newHistory(ShowFormat.RESOLVER, format.getId()); } }); } else { HistoryUtils.newHistory(ShowFormat.RESOLVER, format.getId()); } } @UiHandler("buttonRemove") void buttonRemoveHandler(ClickEvent e) { BrowserService.Util.getInstance().deleteFormat( new SelectedItemsList<Format>(Arrays.asList(format.getUUID()), Format.class.getName()), new AsyncCallback<Void>() { @Override public void onFailure(Throwable caught) { errorMessage(caught); } @Override public void onSuccess(Void result) { Timer timer = new Timer() { @Override public void run() { HistoryUtils.newHistory(FormatRegister.RESOLVER); } }; timer.schedule(RodaConstants.ACTION_TIMEOUT); } }); } @UiHandler("buttonCancel") void buttonCancelHandler(ClickEvent e) { cancel(); } private void cancel() { HistoryUtils.newHistory(ShowFormat.RESOLVER, format.getId()); } private void errorMessage(Throwable caught) { if (caught instanceof NotFoundException) { Toast.showError(messages.editFormatNotFound(format.getName())); cancel(); } else { AsyncCallbackUtils.defaultFailureTreatment(caught); } } protected void enableApplyButton(boolean enabled) { buttonApply.setVisible(enabled); } }
lgpl-3.0
korvus81/ari4java
classes/ch/loway/oss/ari4java/generated/ari_1_7_0/models/SystemInfo_impl_ari_1_7_0.java
1302
package ch.loway.oss.ari4java.generated.ari_1_7_0.models; // ---------------------------------------------------- // THIS CLASS WAS GENERATED AUTOMATICALLY // PLEASE DO NOT EDIT // Generated on: Sat Sep 19 08:50:54 CEST 2015 // ---------------------------------------------------- import ch.loway.oss.ari4java.generated.*; import com.fasterxml.jackson.databind.annotation.JsonDeserialize; import java.util.Date; import java.util.List; import java.util.Map; /********************************************************** * Info about Asterisk * * Defined in file: asterisk.json * Generated by: Model *********************************************************/ public class SystemInfo_impl_ari_1_7_0 implements SystemInfo, java.io.Serializable { private static final long serialVersionUID = 1L; /** */ private String entity_id; public String getEntity_id() { return entity_id; } @JsonDeserialize( as=String.class ) public void setEntity_id(String val ) { entity_id = val; } /** Asterisk version. */ private String version; public String getVersion() { return version; } @JsonDeserialize( as=String.class ) public void setVersion(String val ) { version = val; } /** No missing signatures from interface */ }
lgpl-3.0
EmiteGWT/emite
examples/src/main/java/com/calclab/emite/example/echo/client/ExampleEchoGinjector.java
1434
/* * ((e)) emite: A pure Google Web Toolkit XMPP library * Copyright (c) 2008-2011 The Emite development team * * This file is part of Emite. * * Emite 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. * * Emite 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 Emite. If not, see <http://www.gnu.org/licenses/>. */ package com.calclab.emite.example.echo.client; import com.calclab.emite.browser.EmiteBrowserModule; import com.calclab.emite.core.EmiteCoreModule; import com.calclab.emite.core.session.XmppSession; import com.calclab.emite.im.EmiteIMModule; import com.calclab.emite.im.chat.PairChatManager; import com.google.gwt.inject.client.GinModules; import com.google.gwt.inject.client.Ginjector; @GinModules({ EmiteCoreModule.class, EmiteIMModule.class, EmiteBrowserModule.class }) interface ExampleEchoGinjector extends Ginjector { XmppSession getXmppSession(); PairChatManager getPairChatManager(); }
lgpl-3.0
svn2github/dynamicreports-jasper
dynamicreports-distribution/src/main/java/net/sf/dynamicreports/site/Page.java
4192
/** * DynamicReports - Free Java reporting library for creating reports dynamically * * Copyright (C) 2010 - 2015 Ricardo Mariaca * http://www.dynamicreports.org * * This file is part of DynamicReports. * * DynamicReports 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. * * DynamicReports 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 DynamicReports. If not, see <http://www.gnu.org/licenses/>. */ package net.sf.dynamicreports.site; import java.util.LinkedHashSet; import java.util.Set; /** * @author Ricardo Mariaca (r.mariaca@dynamicreports.org) */ public class Page { private String page; private String path; private String documentation; private String examples; private boolean sideBar; private String content; private boolean hasCode; private Set<String> codeClasses; private boolean hasImage; private boolean hasImageGroup; private String description; private String keywords; private String title; public Page(String page, String name, String pageContent) throws Exception { this.page = page; init(); setPage(name, pageContent); } private void init() throws Exception { path = ""; documentation = "documentation/"; examples = "examples/"; sideBar = true; hasCode = false; codeClasses = new LinkedHashSet<String>(); hasImage = false; hasImageGroup = false; description = ""; keywords = ""; title = ""; } private void setPage(String name, String pageContent) throws Exception { if (pageContent.indexOf("<@java_code>") != -1) { codeClasses.add("Java"); } if (pageContent.indexOf("<@xml_code>") != -1) { codeClasses.add("Xml"); } hasCode = !codeClasses.isEmpty(); hasImage = pageContent.indexOf("<@example") != -1; hasImageGroup = pageContent.indexOf("<@image_group") != -1; content = "/" + name; } public String getPage() { return page; } public void setPage(String page) { this.page = page; } public String getPath() { return path; } public void setPath(String path) { this.path = path; } public String getDocumentation() { return documentation; } public void setDocumentation(String documentation) { this.documentation = documentation; } public String getExamples() { return examples; } public void setExamples(String examples) { this.examples = examples; } public boolean isSideBar() { return sideBar; } public void setSideBar(boolean sideBar) { this.sideBar = sideBar; } public String getContent() { return content; } public void setContent(String content) { this.content = content; } public boolean isHasCode() { return hasCode; } public void setHasCode(boolean hasCode) { this.hasCode = hasCode; } public Set<String> getCodeClasses() { return codeClasses; } public void setCodeClasses(Set<String> codeClasses) { this.codeClasses = codeClasses; } public boolean isHasImage() { return hasImage; } public void setHasImage(boolean hasImage) { this.hasImage = hasImage; } public boolean isHasImageGroup() { return hasImageGroup; } public void setHasImageGroup(boolean hasImageGroup) { this.hasImageGroup = hasImageGroup; } public String getDescription() { return description; } public void setDescription(String description) { this.description = description; } public String getKeywords() { return keywords; } public void setKeywords(String keywords) { this.keywords = keywords; } public String getTitle() { return title; } public void setTitle(String title) { this.title = title; } }
lgpl-3.0
jlpoolen/libreveris
src/test/omr/ui/symbol/AlignmentTest.java
5699
//----------------------------------------------------------------------------// // // // A l i g n m e n t T e s t // // // //----------------------------------------------------------------------------// // <editor-fold defaultstate="collapsed" desc="hdr"> // // Copyright (C) Hervé Bitteur 2000-2011. All rights reserved. // // This software is released under the GNU General Public License. // // Goto http://kenai.com/projects/audiveris to report bugs or suggestions. // //----------------------------------------------------------------------------// // </editor-fold> package omr.ui.symbol; import omr.ui.symbol.Alignment.Horizontal; import static omr.ui.symbol.Alignment.Horizontal.*; import omr.ui.symbol.Alignment.Vertical; import static omr.ui.symbol.Alignment.Vertical.*; import static org.junit.Assert.*; import org.junit.Test; import java.awt.Point; import java.awt.Rectangle; import java.util.HashMap; import java.util.Map; import java.util.Map.Entry; /** * Class {@code AlignmentTest} * * @author Hervé Bitteur */ public class AlignmentTest { //~ Instance fields -------------------------------------------------------- /** Map Alignment -> Point */ Map<Alignment, Point> points = new HashMap<>(); //~ Constructors ----------------------------------------------------------- /** * Creates a new AlignmentTest object. */ public AlignmentTest () { } //~ Methods ---------------------------------------------------------------- /** * Test of toPoint method, of class Alignment. */ @Test public void testToPoint () { System.out.println("toPoint"); Rectangle rect = new Rectangle(-6, -26, 50, 38); assignPoints(); for (Vertical vert : Vertical.values()) { for (Horizontal hori : Horizontal.values()) { Alignment instance = new Alignment(vert, hori); Point start = points.get(instance); for (Vertical v : Vertical.values()) { for (Horizontal h : Horizontal.values()) { Alignment expAlign = new Alignment(v, h); Point to = instance.toPoint(expAlign, rect); Point target = new Point(start); target.translate(to.x, to.y); System.out.print( instance + " + " + to + " = " + target); Alignment align = getAlign(target); Point expTarget = points.get(expAlign); System.out.println(" " + expAlign + " =? " + align); assertEquals("Different points", expTarget, target); assertEquals("Different aligns", expAlign, align); } } System.out.println(); } } } // /** // * Test of toPoint method, of class Alignment. // */ // @Test // public void testToPoint2D () // { // System.out.println("toPoint2D"); // // Rectangle2D rect = new Rectangle2D.Float(-5.8f, -26.0f, 50.0f, 37.4f); // Point2D expTo = null; // // for (Vertical vert : Vertical.values()) { // for (Horizontal hori : Horizontal.values()) { // Alignment instance = new Alignment(vert, hori); // // for (Vertical v : Vertical.values()) { // for (Horizontal h : Horizontal.values()) { // Alignment that = new Alignment(v, h); // Point2D to = instance.toPoint(that, rect); // // System.out.println( // instance + " + " + to + " = " + that); // } // } // // System.out.println(); // } // } // } private Alignment getAlign (Point target) { for (Entry<Alignment, Point> entry : points.entrySet()) { if (entry.getValue() .equals(target)) { return entry.getKey(); } } return null; } private void assignPoints () { points.put(new Alignment(TOP, LEFT), new Point(-6, -26)); points.put(new Alignment(TOP, CENTER), new Point(19, -26)); points.put(new Alignment(TOP, RIGHT), new Point(44, -26)); points.put(new Alignment(TOP, XORIGIN), new Point(0, -26)); points.put(new Alignment(MIDDLE, LEFT), new Point(-6, -7)); points.put(new Alignment(MIDDLE, CENTER), new Point(19, -7)); points.put(new Alignment(MIDDLE, RIGHT), new Point(44, -7)); points.put(new Alignment(MIDDLE, XORIGIN), new Point(0, -7)); points.put(new Alignment(BOTTOM, LEFT), new Point(-6, 12)); points.put(new Alignment(BOTTOM, CENTER), new Point(19, 12)); points.put(new Alignment(BOTTOM, RIGHT), new Point(44, 12)); points.put(new Alignment(BOTTOM, XORIGIN), new Point(0, 12)); points.put(new Alignment(BASELINE, LEFT), new Point(-6, 0)); points.put(new Alignment(BASELINE, CENTER), new Point(19, 0)); points.put(new Alignment(BASELINE, RIGHT), new Point(44, 0)); points.put(new Alignment(BASELINE, XORIGIN), new Point(0, 0)); } }
lgpl-3.0
cristal-ise/kernel
src/main/java/org/cristalise/kernel/lookup/AgentPath.java
4238
/** * This file is part of the CRISTAL-iSE kernel. * Copyright (c) 2001-2015 The CRISTAL Consortium. 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 3 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; with out 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. * * http://www.fsf.org/licensing/licenses/lgpl.html */ package org.cristalise.kernel.lookup; import java.util.List; import java.util.UUID; import org.cristalise.kernel.common.ObjectNotFoundException; import org.cristalise.kernel.common.SystemKey; import org.cristalise.kernel.persistency.ClusterType; import org.cristalise.kernel.process.Gateway; /** * Extends ItemPath with Agent specific codes **/ public class AgentPath extends ItemPath { private String mAgentName = null; private boolean mPasswordTemporary = false; public AgentPath() { super(); } public AgentPath(UUID uuid, String ior, String agentName) { super(uuid, ior); mAgentName = agentName; } public AgentPath(UUID uuid, String ior, String agentName, boolean isPwdTemporary) { super(uuid, ior); mAgentName = agentName; mPasswordTemporary = isPwdTemporary; } public AgentPath(UUID uuid) throws InvalidAgentPathException { super(uuid); //This is commented so a AgentPath can be constructed without setting up Lookup //if (getAgentName() == null) throw new InvalidAgentPathException(); } public AgentPath(SystemKey syskey) throws InvalidAgentPathException { this(new UUID(syskey.msb, syskey.lsb)); } public AgentPath(ItemPath itemPath) throws InvalidAgentPathException { this(itemPath.getUUID()); } public AgentPath(String path) throws InvalidItemPathException { //remove the '/entity/' string from the beginning if exists this(UUID.fromString(path.substring( (path.lastIndexOf("/") == -1 ? 0 : path.lastIndexOf("/")+1) ))); } public AgentPath(ItemPath itemPath, String agentName) { super(itemPath.getUUID()); mAgentName = agentName; } public AgentPath(UUID uuid, String agentName) { super(uuid); mAgentName = agentName; } public void setAgentName(String agentID) { mAgentName = agentID; } public String getAgentName() { if (mAgentName == null) { try { mAgentName = Gateway.getLookup().getAgentName(this); } catch (ObjectNotFoundException e) { return null; } } return mAgentName; } public RolePath[] getRoles() { return Gateway.getLookup().getRoles(this); } public RolePath getFirstMatchingRole(List<RolePath> roles) { for (RolePath role : roles) { if (Gateway.getLookup().hasRole(this, role)) return role; } return null; } public boolean hasRole(RolePath role) { return Gateway.getLookup().hasRole(this, role); } public boolean hasRole(String role) { try { return hasRole(Gateway.getLookup().getRolePath(role)); } catch (ObjectNotFoundException ex) { return false; } } @Override public String getClusterPath() { return ClusterType.PATH + "/Agent"; } @Override public String dump() { return super.dump() + "\n agentID=" + mAgentName; } public boolean isPasswordTemporary() { return mPasswordTemporary; } }
lgpl-3.0
molszewski/dante
module/AlgorithmsFramework/src/net/java/dante/algorithms/common/Dbg.java
7814
/* * Created on 2005-09-27 * @author M.Olszewski */ package net.java.dante.algorithms.common; import java.io.File; import java.io.FileNotFoundException; import java.io.IOException; import java.io.PrintStream; import java.text.DateFormat; import java.util.Calendar; import java.util.Date; /** * Class provides easy-to-control debug output. * * @author M.Olszewski */ public class Dbg { /* Store standard and error outputs */ private static PrintStream standardOut = System.out; private static PrintStream standardErr = System.err; private static PrintStream lastLogFile = null; // Debug prefixes private static final String debugPrefix = "[DEBUG]"; private static final String errorPrefix = debugPrefix + "[ ERROR ] "; private static final String warningPrefix = debugPrefix + "[ WARNING ] "; private static final String infoPrefix = debugPrefix + "[ INFO ] "; // Debug flags private static final int DBGS_NONE = 0x0000; private static final int DBGW_ENABLED = 0x0001; private static final int DBGE_ENABLED = 0x0002; // Debug level private static final int DBG_LEVEL = 2; private static final DateFormat timeFormat = DateFormat.getTimeInstance(DateFormat.LONG); /** Enables/disables time stamps in debug messages. */ private static final boolean TIME_STAMP = true; /** Enables/disables thread names in debug messages. */ private static final boolean THREAD_NAME = true; // Debug options - should contain all required flags private static final int DEBUG_OPTIONS = DBGS_NONE | DBGW_ENABLED | DBGE_ENABLED; /** * Indicates whether debug output is enabled. */ public static final boolean DEBUG = false; /** * Indicates whether warning debug output is enabled. */ public static final boolean DBGW = (DEBUG && ((DEBUG_OPTIONS & DBGW_ENABLED) == DBGW_ENABLED)); /** * Indicates whether error debug output is enabled. */ public static final boolean DBGE = (DEBUG && ((DEBUG_OPTIONS & DBGE_ENABLED) == DBGE_ENABLED)); /** * Indicates whether level 1 debug output is enabled. */ public static final boolean DBG1 = (DEBUG && (DBG_LEVEL >= 1)); /** * Indicates whether level 2 debug output is enabled. */ public static final boolean DBG2 = (DEBUG && (DBG_LEVEL >= 2)); /** * Indicates whether level 3 debug output is enabled. */ public static final boolean DBG3 = (DEBUG && (DBG_LEVEL >= 3)); /** * Private constructor - no external class creation, no inheritance. */ private Dbg() { // Intentionally left empty. } /** * Prints <code>string</code> to console with debug prefix. * * @param string string to be printed. */ public static void write(String string) { String commonPrefix = createCommonPrefix(); if (commonPrefix != null) { System.err.println(commonPrefix + " " + debugPrefix + " " + string); } else { System.err.println(debugPrefix + " " + string); } } /** * Prints <code>string</code> to console with warning prefix. * * @param string warning string to be printed. */ public static void warning(String string) { String commonPrefix = createCommonPrefix(); if (commonPrefix != null) { System.err.println(commonPrefix + " " + warningPrefix + " " + string); } else { System.err.println(warningPrefix + string); } } /** * Prints <code>string</code> to console with error prefix. * * @param string error string to be printed. */ public static void error(String string) { String commonPrefix = createCommonPrefix(); if (commonPrefix != null) { System.err.println(commonPrefix + " " + errorPrefix + " " + string); } else { System.err.println(errorPrefix + string); } } /** * Prints <code>string</code> on console with information prefix * * @param string information string to be printed */ public static void info(String string) { String commonPrefix = createCommonPrefix(); if (commonPrefix != null) { System.err.println(commonPrefix + " " + infoPrefix + " " + string); } else { System.err.println(infoPrefix + string); } } /** * Throws {@link AssertionError} if specified <code>statement</code> is * <code>false</code>. * * @param statement statement to check. * @param string error with this message is thrown if * <code>statement</code> is <code>false</code> */ public static void assertion(boolean statement, String string) { if (!statement) { throw new AssertionError(string); } } /** * Enables logging and stores all standard and error output in log file * with name based on the specified file prefix and suffix and current * date and time. * Log files will be stored in 'logs' directory in working directory. * * @param logFilePrefix the specified file prefix. * @param logFileSuffix the specified file suffix. */ public static void enableDateTimeLog(String logFilePrefix, String logFileSuffix) { StringBuilder fullFileName = new StringBuilder("./logs/"); fullFileName.append(logFilePrefix). append(String.format("%1$tY-%1$tm-%1$td_%1$tH.%1$tM.%1$tS.%1$tL", Calendar.getInstance())). append(logFileSuffix); enableLogging(fullFileName.toString()); } /** * Enables logging and stores all standard and error output in log file * with random name, generated by using the specified file prefix and suffix. * Log files will be stored in 'logs' directory in working directory. * * @param logFilePrefix the specified file prefix. * @param logFileSuffix the specified file suffix. */ public static void enableLogging(String logFilePrefix, String logFileSuffix) { try { enableLogging(File.createTempFile(logFilePrefix, logFileSuffix, new File("./logs"))); } catch (IOException e) { // Intentionally left empty. } } /** * Enables logging and stores all standard and error output in specified file. * * @param filePath path to a file where results sent to standard out and * error output will be stored. */ public static void enableLogging(String filePath) { enableLogging(new File(filePath)); } /** * Enables logging and stores all standard and error output in specified file. * * @param filePath path to a file where results sent to standard out and * error output will be stored. */ public static void enableLogging(File filePath) { ensureLogDirExists(); try { PrintStream logFile = new PrintStream(filePath); lastLogFile = logFile; System.setOut(logFile); System.setErr(logFile); } catch (FileNotFoundException e) { if (DBGE) { error("Exception in enableLogging() - printing stack trace."); } e.printStackTrace(); } } /** * Ensures that logs directory exists. */ private static void ensureLogDirExists() { File d = new File("./logs"); if (!d.exists()) { d.mkdir(); } } /** * Disables logging. */ public static void disableLogging() { System.setOut(standardOut); System.setErr(standardErr); if (lastLogFile != null) { lastLogFile.close(); lastLogFile = null; } } private static String createCommonPrefix() { return (THREAD_NAME)? ((TIME_STAMP)? (createThreadName() + " " + createTimeStamp()) : createThreadName()) : ((TIME_STAMP)? createTimeStamp() : null); } private static synchronized String createTimeStamp() { return timeFormat.format(new Date()); } private static String createThreadName() { return Thread.currentThread().getName(); } }
lgpl-3.0
deelam/agilion
dataengine/tasker/src/main/java/dataengine/tasker/RpcClients4TaskerModule.java
1155
package dataengine.tasker; import javax.jms.Connection; import com.google.inject.Provides; import dataengine.apis.DepJobService_I; import dataengine.apis.RpcClientProvider; import dataengine.apis.SessionsDB_I; import dataengine.apis.CommunicationConsts; import lombok.extern.slf4j.Slf4j; import net.deelam.activemq.rpc.RpcClientsModule; /// provides verticle clients used by Tasker service @Slf4j class RpcClients4TaskerModule extends RpcClientsModule { // private final String depJobMgrBroadcastAddr; public RpcClients4TaskerModule(Connection connection/*, String depJobMgrBroadcastAddr*/) { super(connection); // this.depJobMgrBroadcastAddr=depJobMgrBroadcastAddr; //debug = true; log.debug("VertxRpcClients4TaskerModule configured"); } // @Provides // RpcClientProvider<DepJobService_I> jobDispatcherRpcClient(){ // return new RpcClientProvider<>(getAmqClientSupplierFor(DepJobService_I.class, depJobMgrBroadcastAddr)); // } @Provides RpcClientProvider<SessionsDB_I> sessionsDbRpcClient(){ return new RpcClientProvider<>(getAmqClientSupplierFor(SessionsDB_I.class, CommunicationConsts.SESSIONDB_RPCADDR)); } }
lgpl-3.0
Builders-SonarSource/sonarqube-bis
sonar-plugin-api/src/main/java/org/sonar/api/server/authentication/IdentityProvider.java
1968
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.server.authentication; import org.sonar.api.server.ServerSide; /** * Entry-point to define a new Identity provider. * Only one of this two interfaces can be used : * <ul> * <li>{@link OAuth2IdentityProvider} for OAuth2 authentication</li> * <li>{@link BaseIdentityProvider} for other kind of authentication</li> * </ul> * * @since 5.4 */ @ServerSide public interface IdentityProvider { /** * Unique key of provider, for example "github". * Must not be blank. */ String getKey(); /** * Name displayed in login form. * Must not be blank. */ String getName(); /** * Display information for the login form */ Display getDisplay(); /** * Is the provider fully configured and enabled ? If {@code true}, then * the provider is available in login form. */ boolean isEnabled(); /** * Can users sign-up (connecting with their account for the first time) ? If {@code true}, * then users can register and create their account into SonarQube, else only already * registered users can login. */ boolean allowsUsersToSignUp(); }
lgpl-3.0
meteoinfo/meteoinfolib
src/org/meteoinfo/jts/precision/GeometryPrecisionReducer.java
7754
/* * The JTS Topology Suite is a collection of Java classes that * implement the fundamental operations required to validate a given * geo-spatial data set to a known topological specification. * * Copyright (C) 2001 Vivid Solutions * * 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 * * For more information, contact: * * Vivid Solutions * Suite #1A * 2328 Government Street * Victoria BC V8T 5G5 * Canada * * (250)385-6040 * www.vividsolutions.com */ package org.meteoinfo.jts.precision; import org.meteoinfo.jts.geom.*; import org.meteoinfo.jts.geom.util.*; /** * Reduces the precision of a {@link Geometry} * according to the supplied {@link PrecisionModel}, * ensuring that the result is topologically valid. * * @version 1.12 */ public class GeometryPrecisionReducer { /** * Convenience method for doing precision reduction * on a single geometry, * with collapses removed * and keeping the geometry precision model the same, * and preserving polygonal topology. * * @param g the geometry to reduce * @param precModel the precision model to use * @return the reduced geometry */ public static Geometry reduce(Geometry g, PrecisionModel precModel) { GeometryPrecisionReducer reducer = new GeometryPrecisionReducer(precModel); return reducer.reduce(g); } /** * Convenience method for doing pointwise precision reduction * on a single geometry, * with collapses removed * and keeping the geometry precision model the same, * but NOT preserving valid polygonal topology. * * @param g the geometry to reduce * @param precModel the precision model to use * @return the reduced geometry */ public static Geometry reducePointwise(Geometry g, PrecisionModel precModel) { GeometryPrecisionReducer reducer = new GeometryPrecisionReducer(precModel); reducer.setPointwise(true); return reducer.reduce(g); } private PrecisionModel targetPM; private boolean removeCollapsed = true; private boolean changePrecisionModel = false; private boolean isPointwise = false; public GeometryPrecisionReducer(PrecisionModel pm) { targetPM = pm; } /** * Sets whether the reduction will result in collapsed components * being removed completely, or simply being collapsed to an (invalid) * Geometry of the same type. * The default is to remove collapsed components. * * @param removeCollapsed if <code>true</code> collapsed components will be removed */ public void setRemoveCollapsedComponents(boolean removeCollapsed) { this.removeCollapsed = removeCollapsed; } /** * Sets whether the {@link PrecisionModel} of the new reduced Geometry * will be changed to be the {@link PrecisionModel} supplied to * specify the precision reduction. * <p> * The default is to <b>not</b> change the precision model * * @param changePrecisionModel if <code>true</code> the precision model of the created Geometry will be the * the precisionModel supplied in the constructor. */ public void setChangePrecisionModel(boolean changePrecisionModel) { this.changePrecisionModel = changePrecisionModel; } /** * Sets whether the precision reduction will be done * in pointwise fashion only. * Pointwise precision reduction reduces the precision * of the individual coordinates only, but does * not attempt to recreate valid topology. * This is only relevant for geometries containing polygonal components. * * @param isPointwise if reduction should be done pointwise only */ public void setPointwise(boolean isPointwise) { this.isPointwise = isPointwise; } public Geometry reduce(Geometry geom) { Geometry reducePW = reducePointwise(geom); if (isPointwise) return reducePW; //TODO: handle GeometryCollections containing polys if (! (reducePW instanceof Polygonal)) return reducePW; // Geometry is polygonal - test if topology needs to be fixed if (reducePW.isValid()) return reducePW; // hack to fix topology. // TODO: implement snap-rounding and use that. return fixPolygonalTopology(reducePW); } private Geometry reducePointwise(Geometry geom) { GeometryEditor geomEdit; if (changePrecisionModel) { GeometryFactory newFactory = createFactory(geom.getFactory(), targetPM); geomEdit = new GeometryEditor(newFactory); } else // don't change geometry factory geomEdit = new GeometryEditor(); /** * For polygonal geometries, collapses are always removed, in order * to produce correct topology */ boolean finalRemoveCollapsed = removeCollapsed; if (geom.getDimension() >= 2) finalRemoveCollapsed = true; Geometry reduceGeom = geomEdit.edit(geom, new PrecisionReducerCoordinateOperation(targetPM, finalRemoveCollapsed)); return reduceGeom; } private Geometry fixPolygonalTopology(Geometry geom) { /** * If precision model was *not* changed, need to flip * geometry to targetPM, buffer in that model, then flip back */ Geometry geomToBuffer = geom; if (! changePrecisionModel) { geomToBuffer = changePM(geom, targetPM); } Geometry bufGeom = geomToBuffer.buffer(0); Geometry finalGeom = bufGeom; if (! changePrecisionModel) { // a slick way to copy the geometry with the original precision factory finalGeom = geom.getFactory().createGeometry(bufGeom); } return finalGeom; } /** * Duplicates a geometry to one that uses a different PrecisionModel, * without changing any coordinate values. * * @param geom the geometry to duplicate * @param newPM the precision model to use * @return the geometry value with a new precision model */ private Geometry changePM(Geometry geom, PrecisionModel newPM) { GeometryEditor geomEditor = createEditor(geom.getFactory(), newPM); // this operation changes the PM for the entire geometry tree return geomEditor.edit(geom, new GeometryEditor.NoOpGeometryOperation()); } private GeometryEditor createEditor(GeometryFactory geomFactory, PrecisionModel newPM) { // no need to change if precision model is the same if (geomFactory.getPrecisionModel() == newPM) return new GeometryEditor(); // otherwise create a geometry editor which changes PrecisionModel GeometryFactory newFactory = createFactory(geomFactory, newPM); GeometryEditor geomEdit = new GeometryEditor(newFactory); return geomEdit; } private GeometryFactory createFactory(GeometryFactory inputFactory, PrecisionModel pm) { GeometryFactory newFactory = new GeometryFactory(pm, inputFactory.getSRID(), inputFactory.getCoordinateSequenceFactory()); return newFactory; } }
lgpl-3.0
socialwareinc/html-parser
parser/src/main/java/org/htmlparser/tags/HeadTag.java
2672
// HTMLParser Library - A java-based parser for HTML // http://htmlparser.org // Copyright (C) 2006 Dhaval Udani // // Revision Control Information // // $URL: file:///svn/p/htmlparser/code/tags/HTMLParserProject-2.1/parser/src/main/java/org/htmlparser/tags/HeadTag.java $ // $Author: derrickoswald $ // $Date: 2006-09-16 14:44:17 +0000 (Sat, 16 Sep 2006) $ // $Revision: 4 $ // // This library is free software; you can redistribute it and/or // modify it under the terms of the Common Public License; either // version 1.0 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 // Common Public License for more details. // // You should have received a copy of the Common Public License // along with this library; if not, the license is available from // the Open Source Initiative (OSI) website: // http://opensource.org/licenses/cpl1.0.php package org.htmlparser.tags; /** * A head tag. */ public class HeadTag extends CompositeTag { /** * The set of names handled by this tag. */ private static final String[] mIds = new String[] {"HEAD"}; /** * The set of tag names that indicate the end of this tag. */ private static final String[] mEnders = new String[] {"HEAD", "BODY"}; /** * The set of end tag names that indicate the end of this tag. */ private static final String[] mEndTagEnders = new String[] {"HTML"}; /** * Create a new head tag. */ public HeadTag () { } /** * Return the set of names handled by this tag. * @return The names to be matched that create tags of this type. */ public String[] getIds () { return (mIds); } /** * Return the set of tag names that cause this tag to finish. * @return The names of following tags that stop further scanning. */ public String[] getEnders () { return (mEnders); } /** * Return the set of end tag names that cause this tag to finish. * @return The names of following end tags that stop further scanning. */ public String[] getEndTagEnders () { return (mEndTagEnders); } /** * Returns a string representation of this <code>HEAD</code> tag suitable for debugging. * @return A string representing this tag. */ public String toString() { return "HEAD: " + super.toString(); } }
lgpl-3.0
caihongwang/ChatMe
src/com/csipsimple/wizards/impl/Betamax.java
16922
/** * Copyright (C) 2010-2012 Regis Montoya (aka r3gis - www.r3gis.fr) * This file is part of CSipSimple. * * CSipSimple 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. * If you own a pjsip commercial license you can also redistribute it * and/or modify it under the terms of the GNU Lesser General Public License * as an android library. * * CSipSimple 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 CSipSimple. If not, see <http://www.gnu.org/licenses/>. */ package com.csipsimple.wizards.impl; import android.preference.ListPreference; import android.text.TextUtils; import android.view.View; import android.widget.LinearLayout; import android.widget.TextView; import com.chatme.R; import com.csipsimple.api.SipConfigManager; import com.csipsimple.api.SipProfile; import com.csipsimple.utils.Log; import com.csipsimple.utils.PreferencesWrapper; import org.apache.http.client.methods.HttpGet; import org.apache.http.client.methods.HttpRequestBase; import java.io.IOException; import java.lang.ref.WeakReference; import java.util.HashMap; import java.util.Map.Entry; import java.util.SortedMap; import java.util.TreeMap; public class Betamax extends AuthorizationImplementation { static String PROVIDER = "provider"; protected static final String THIS_FILE = "BetamaxW"; private LinearLayout customWizard; private TextView customWizardText; ListPreference providerListPref; static SortedMap<String, String[]> providers = new TreeMap<String, String[]>() { private static final long serialVersionUID = 4984940975243241784L; { put("FreeCall", new String[] { "sip.voiparound.com", "stun.voiparound.com" }); put("InternetCalls", new String[] { "sip.internetcalls.com", "stun.internetcalls.com" }); put("Low Rate VoIP", new String[] { "sip.lowratevoip.com", "stun.lowratevoip.com" }); put("NetAppel", new String[] { "sip.netappel.fr", "stun.netappel.fr" }); put("Poivy", new String[] { "sip.poivy.com", "stun.poivy.com" }); put("SIP Discount", new String[] { "sip.sipdiscount.com", "stun.sipdiscount.com" }); put("SMS Discount", new String[] { "sip.smsdiscount.com", "stun.smsdiscount.com" }); put("SparVoIP", new String[] { "sip.sparvoip.com", "stun.sparvoip.com" }); put("VoIP Buster", new String[] { "sip.voipbuster.com", "stun.voipbuster.com" }); put("VoIP Buster Pro", new String[] { "sip.voipbusterpro.com", "stun.voipbusterpro.com" }); put("VoIP Cheap", new String[] { "sip.voipcheap.com", "stun.voipcheap.com" }); put("VoIP Discount", new String[] { "sip.voipdiscount.com", "stun.voipdiscount.com" }); put("12VoIP", new String[] { "sip.12voip.com", "stun.12voip.com" }); put("VoIP Stunt", new String[] { "sip.voipstunt.com", "stun.voipstunt.com" }); put("WebCall Direct", new String[] { "sip.webcalldirect.com", "stun.webcalldirect.com" }); put("Just VoIP", new String[] { "sip.justvoip.com", "stun.justvoip.com" }); put("Nonoh", new String[] { "sip.nonoh.net", "stun.nonoh.net" }); put("VoIPWise", new String[] { "sip.voipwise.com", "stun.voipwise.com" }); put("VoIPRaider", new String[] { "sip.voipraider.com", "stun.voipraider.com" }); put("BudgetSIP", new String[] { "sip.budgetsip.com", "stun.budgetsip.com" }); put("InterVoIP", new String[] { "sip.intervoip.com", "stun.intervoip.com" }); put("VoIPHit", new String[] { "sip.voiphit.com", "stun.voiphit.com" }); put("SmartVoIP", new String[] { "sip.smartvoip.com", "stun.smartvoip.com" }); put("ActionVoIP", new String[] { "sip.actionvoip.com", "stun.actionvoip.com" }); put("Jumblo", new String[] { "sip.jumblo.com", "stun.jumblo.com" }); put("Rynga", new String[] { "sip.rynga.com", "stun.rynga.com" }); put("PowerVoIP", new String[] { "sip.powervoip.com", "stun.powervoip.com" }); put("Voice Trading", new String[] { "sip.voicetrading.com", "stun.voicetrading.com" }); put("EasyVoip", new String[] { "sip.easyvoip.com", "stun.easyvoip.com" }); put("VoipBlast", new String[] { "sip.voipblast.com", "stun.voipblast.com" }); put("FreeVoipDeal", new String[] { "sip.freevoipdeal.com", "stun.freevoipdeal.com" }); put("VoipAlot", new String[] { "sip.voipalot.com", "" }); put("CosmoVoip", new String[] { "sip.cosmovoip.com", "stun.cosmovoip.com" }); put("BudgetVoipCall", new String[] { "sip.budgetvoipcall.com", "stun.budgetvoipcall.com" }); put("CheapBuzzer", new String[] { "sip.cheapbuzzer.com", "stun.cheapbuzzer.com" }); put("CallPirates", new String[] { "sip.callpirates.com", "stun.callpirates.com" }); put("CheapVoipCall", new String[] { "sip.cheapvoipcall.com", "stun.cheapvoipcall.com" }); put("DialCheap", new String[] { "sip.dialcheap.com", "stun.dialcheap.com" }); put("DiscountCalling", new String[] { "sip.discountcalling.com", "stun.discountcalling.com" }); put("Frynga", new String[] { "sip.frynga.com", "stun.frynga.com" }); put("GlobalFreeCall", new String[] { "sip.globalfreecall.com", "stun.globalfreecall.com" }); put("HotVoip", new String[] { "sip.hotvoip.com", "stun.hotvoip.com" }); put("MEGAvoip", new String[] { "sip.megavoip.com", "stun.megavoip.com" }); put("PennyConnect", new String[] { "sip.pennyconnect.com", "stun.pennyconnect.com" }); put("Rebvoice", new String[] { "sip.rebvoice.com", "stun.rebvoice.com" }); put("StuntCalls", new String[] { "sip.stuntcalls.com", "stun.stuntcalls.com" }); put("VoipBlazer", new String[] { "sip.voipblazer.com", "stun.voipblazer.com" }); put("VoipCaptain", new String[] { "sip.voipcaptain.com", "stun.voipcaptain.com" }); put("VoipChief", new String[] { "sip.voipchief.com", "stun.voipchief.com" }); put("VoipJumper", new String[] { "sip.voipjumper.com", "stun.voipjumper.com" }); put("VoipMove", new String[] { "sip.voipmove.com", "stun.voipmove.com" }); put("VoipSmash", new String[] { "sip.voipsmash.com", "stun.voipsmash.com" }); put("VoipGain", new String[] { "sip.voipgain.com", "stun.voipgain.com" }); put("VoipZoom", new String[] { "sip.voipzoom.com", "stun.voipzoom.com" }); put("Telbo", new String[] { "sip.telbo.com", "stun.telbo.com" }); put("Llevoip", new String[] { "77.72.174.129", "77.72.174.160" }); put("Llevoip (server 2)", new String[] { "77.72.174.130:6000", "77.72.174.162" }); /* * put("InternetCalls", new String[] {"", ""}); */ } }; /** * {@inheritDoc} */ @Override protected String getDefaultName() { return "Betamax"; } private static final String PROVIDER_LIST_KEY = "provider_list"; /** * {@inheritDoc} */ @Override public void fillLayout(final SipProfile account) { super.fillLayout(account); accountUsername.setTitle(R.string.w_advanced_caller_id); accountUsername.setDialogTitle(R.string.w_advanced_caller_id_desc); boolean recycle = true; providerListPref = (ListPreference) findPreference(PROVIDER_LIST_KEY); if (providerListPref == null) { Log.d(THIS_FILE, "Create new list pref"); providerListPref = new ListPreference(parent); providerListPref.setKey(PROVIDER_LIST_KEY); recycle = false; } else { Log.d(THIS_FILE, "Recycle existing list pref"); } CharSequence[] v = new CharSequence[providers.size()]; int i = 0; for (String pv : providers.keySet()) { v[i] = pv; i++; } providerListPref.setEntries(v); providerListPref.setEntryValues(v); providerListPref.setKey(PROVIDER); providerListPref.setDialogTitle("Provider"); providerListPref.setTitle("Provider"); providerListPref.setSummary("Betamax clone provider"); providerListPref.setDefaultValue("12VoIP"); if (!recycle) { addPreference(providerListPref); } hidePreference(null, SERVER); String domain = account.getDefaultDomain(); if (domain != null) { for (Entry<String, String[]> entry : providers.entrySet()) { String[] val = entry.getValue(); if (val[0].equalsIgnoreCase(domain)) { Log.d(THIS_FILE, "Set provider list pref value to " + entry.getKey()); providerListPref.setValue(entry.getKey()); break; } } } Log.d(THIS_FILE, providerListPref.getValue()); // Get wizard specific row customWizardText = (TextView) parent.findViewById(R.id.custom_wizard_text); customWizard = (LinearLayout) parent.findViewById(R.id.custom_wizard_row); updateAccountInfos(account); } /** * {@inheritDoc} */ @Override public SipProfile buildAccount(SipProfile account) { account = super.buildAccount(account); account.mwi_enabled = false; return account; } private static HashMap<String, Integer> SUMMARIES = new HashMap<String, Integer>() { /** * */ private static final long serialVersionUID = -5743705263738203615L; { put(DISPLAY_NAME, R.string.w_common_display_name_desc); put(USER_NAME, R.string.w_advanced_caller_id_desc); put(AUTH_NAME, R.string.w_authorization_auth_name_desc); put(PASSWORD, R.string.w_common_password_desc); put(SERVER, R.string.w_common_server_desc); } }; /** * {@inheritDoc} */ @Override public void updateDescriptions() { super.updateDescriptions(); setStringFieldSummary(PROVIDER); } /** * {@inheritDoc} */ @Override public String getDefaultFieldSummary(String fieldName) { Integer res = SUMMARIES.get(fieldName); if (fieldName == PROVIDER) { if (providerListPref != null) { return providerListPref.getValue(); } } if (res != null) { return parent.getString(res); } return ""; } /** * {@inheritDoc} */ @Override public boolean canSave() { boolean isValid = true; isValid &= checkField(accountDisplayName, isEmpty(accountDisplayName)); isValid &= checkField(accountUsername, isEmpty(accountUsername)); isValid &= checkField(accountAuthorization, isEmpty(accountAuthorization)); isValid &= checkField(accountPassword, isEmpty(accountPassword)); return isValid; } /** * {@inheritDoc} */ @Override protected String getDomain() { String provider = providerListPref.getValue(); if (provider != null) { String[] set = providers.get(provider); return set[0]; } return ""; } /** * {@inheritDoc} */ @Override public boolean needRestart() { return true; } /** * {@inheritDoc} */ @Override public void setDefaultParams(PreferencesWrapper prefs) { super.setDefaultParams(prefs); // Disable ICE and turn on STUN!!! prefs.setPreferenceBooleanValue(SipConfigManager.ENABLE_STUN, true); String provider = providerListPref.getValue(); if (provider != null) { String[] set = providers.get(provider); if (!TextUtils.isEmpty(set[1])) { prefs.addStunServer(set[1]); } } prefs.setPreferenceBooleanValue(SipConfigManager.ENABLE_ICE, false); } private void updateAccountInfos(final SipProfile acc) { if (acc != null && acc.id != SipProfile.INVALID_ID) { customWizard.setVisibility(View.GONE); accountBalanceHelper.launchRequest(acc); } else { // add a row to link customWizard.setVisibility(View.GONE); } } private AccountBalanceHelper accountBalanceHelper = new AccountBalance(this); private static class AccountBalance extends AccountBalanceHelper { WeakReference<Betamax> w; AccountBalance(Betamax wizard){ w = new WeakReference<Betamax>(wizard); } /** * {@inheritDoc} */ @Override public HttpRequestBase getRequest(SipProfile acc) throws IOException { Betamax wizard = w.get(); if(wizard == null) { return null; } String requestURL = "https://"; String provider = wizard.providerListPref.getValue(); if (provider != null) { String[] set = providers.get(provider); requestURL += set[0].replace("sip.", "www."); requestURL += "/myaccount/getbalance.php"; requestURL += "?username=" + acc.username; requestURL += "&password=" + acc.data; return new HttpGet(requestURL); } return null; } /** * {@inheritDoc} */ @Override public String parseResponseLine(String line) { try { float value = Float.parseFloat(line.trim()); if (value >= 0) { return "Balance : " + Math.round(value * 100.0) / 100.0 + " euros"; } } catch (NumberFormatException e) { Log.e(THIS_FILE, "Can't get value for line"); } return null; } /** * {@inheritDoc} */ @Override public void applyResultError() { Betamax wizard = w.get(); if(wizard != null) { wizard.customWizard.setVisibility(View.GONE); } } /** * {@inheritDoc} */ @Override public void applyResultSuccess(String balanceText) { Betamax wizard = w.get(); if(wizard != null) { wizard.customWizardText.setText(balanceText); wizard.customWizard.setVisibility(View.VISIBLE); } } }; }
lgpl-3.0
joansmith/sonarqube
sonar-plugin-api/src/main/java/org/sonar/api/measures/MeasureUtils.java
5520
/* * SonarQube * Copyright (C) 2009-2016 SonarSource SA * mailto:contact AT sonarsource DOT com * * 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, write to the Free Software Foundation, * Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA. */ package org.sonar.api.measures; import org.apache.commons.lang.StringUtils; import javax.annotation.Nullable; import java.util.Collection; /** * An utility class to manipulate measures * * @since 1.10 */ public final class MeasureUtils { /** * Class cannot be instantiated, it should only be access through static methods */ private MeasureUtils() { } /** * Return true if all measures have numeric value * * @param measures the measures * @return true if all measures numeric values */ public static boolean haveValues(Measure... measures) { if (measures == null || measures.length == 0) { return false; } for (Measure measure : measures) { if (!hasValue(measure)) { return false; } } return true; } /** * Get the value of a measure, or alternatively a default value * * @param measure the measure * @param defaultValue the default value * @return <code>defaultValue</code> if measure is null or has no values. */ public static Double getValue(Measure measure, @Nullable Double defaultValue) { if (MeasureUtils.hasValue(measure)) { return measure.getValue(); } return defaultValue; } public static Long getValueAsLong(Measure measure, Long defaultValue) { if (MeasureUtils.hasValue(measure)) { return measure.getValue().longValue(); } return defaultValue; } public static Double getVariation(Measure measure, int periodIndex) { return getVariation(measure, periodIndex, null); } public static Double getVariation(Measure measure, int periodIndex, @Nullable Double defaultValue) { Double result = null; if (measure != null) { result = measure.getVariation(periodIndex); } return result != null ? result : defaultValue; } public static Long getVariationAsLong(Measure measure, int periodIndex) { return getVariationAsLong(measure, periodIndex, null); } public static Long getVariationAsLong(Measure measure, int periodIndex, @Nullable Long defaultValue) { Double result = null; if (measure != null) { result = measure.getVariation(periodIndex); } return result == null ? defaultValue : Long.valueOf(result.longValue()); } /** * Tests if a measure has a value * * @param measure the measure * @return whether the measure has a value */ public static boolean hasValue(Measure measure) { return measure != null && measure.getValue() != null; } /** * Tests if a measure has a data field * * @param measure the measure * @return whether the measure has a data field */ public static boolean hasData(Measure measure) { return measure != null && StringUtils.isNotBlank(measure.getData()); } /** * Sums a series of measures * * @param zeroIfNone whether to return 0 or null in case measures is null * @param measures the series of measures * @return the sum of the measure series */ public static Double sum(boolean zeroIfNone, Collection<Measure> measures) { if (measures != null) { return sum(zeroIfNone, measures.toArray(new Measure[measures.size()])); } return zeroIfNone(zeroIfNone); } /** * Sums a series of measures * * @param zeroIfNone whether to return 0 or null in case measures is null * @param measures the series of measures * @return the sum of the measure series */ public static Double sum(boolean zeroIfNone, Measure... measures) { if (measures == null) { return zeroIfNone(zeroIfNone); } Double sum = 0d; boolean hasValue = false; for (Measure measure : measures) { if (measure != null && measure.getValue() != null) { hasValue = true; sum += measure.getValue(); } } if (hasValue) { return sum; } return zeroIfNone(zeroIfNone); } /** * Sums a series of measures for the given variation index * * @param zeroIfNone whether to return 0 or null in case measures is null * @param variationIndex the index of the variation to use * @param measures the series of measures * @return the sum of the variations for the measure series */ public static Double sumOnVariation(boolean zeroIfNone, int variationIndex, Collection<Measure> measures) { if (measures == null) { return zeroIfNone(zeroIfNone); } Double sum = 0d; for (Measure measure : measures) { Double var = measure.getVariation(variationIndex); if (var != null) { sum += var; } } return sum; } private static Double zeroIfNone(boolean zeroIfNone) { return zeroIfNone ? 0d : null; } }
lgpl-3.0
almondtools/testrecorder
testrecorder-agent/src/main/java/net/amygdalum/testrecorder/deserializers/builder/DefaultGenericCollectionAdaptor.java
4783
package net.amygdalum.testrecorder.deserializers.builder; import static java.util.stream.Collectors.toList; import static net.amygdalum.testrecorder.deserializers.Templates.assignLocalVariableStatement; import static net.amygdalum.testrecorder.deserializers.Templates.callMethodStatement; import static net.amygdalum.testrecorder.deserializers.Templates.newObject; import static net.amygdalum.testrecorder.types.Computation.variable; import static net.amygdalum.testrecorder.util.Types.baseType; import static net.amygdalum.testrecorder.util.Types.equalGenericTypes; import static net.amygdalum.testrecorder.util.Types.typeArgument; import static net.amygdalum.testrecorder.util.Types.typeArguments; import java.lang.reflect.Type; import java.util.Collection; import java.util.List; import java.util.Optional; import java.util.stream.Stream; import net.amygdalum.testrecorder.deserializers.Deserializer; import net.amygdalum.testrecorder.types.Computation; import net.amygdalum.testrecorder.types.DeserializerContext; import net.amygdalum.testrecorder.types.SerializedReferenceType; import net.amygdalum.testrecorder.types.SerializedValue; import net.amygdalum.testrecorder.types.TypeManager; import net.amygdalum.testrecorder.util.Types; public abstract class DefaultGenericCollectionAdaptor<T extends SerializedReferenceType> extends DefaultSetupGenerator<T> implements SetupGenerator<T> { public abstract Class<?>[] matchingTypes(); public abstract Type componentType(T value); public abstract Stream<SerializedValue> elements(T value); @Override public boolean matches(Type type) { return matchType(type).isPresent(); } public Optional<Class<?>> matchType(Type type) { return Stream.of(matchingTypes()) .filter(clazz -> clazz.isAssignableFrom(baseType(type))) .findFirst(); } @Override public Computation tryDeserialize(T value, Deserializer generator) { DeserializerContext context = generator.getContext(); TypeManager types = context.getTypes(); Type type = value.getType(); Type usedType = types.mostSpecialOf(value.getUsedTypes()).orElse(Object.class); boolean uniqueUsageType = value.getUsedTypes().length == 1 && Collection.class.isAssignableFrom(baseType(usedType)); Type componentType = componentType(value); Class<?> matchingType = matchType(type).get(); Type effectiveResultType = types.bestType(usedType, matchingType); Type temporaryType = uniqueUsageType ? effectiveResultType : types.bestType(type, effectiveResultType, matchingType); Type componentResultType = types.isHidden(componentType) ? typeArgument(temporaryType, 0).orElse(Object.class) : componentType; types.registerTypes(effectiveResultType, type, componentResultType); return context.forVariable(value, effectiveResultType, local -> { List<Computation> elementTemplates = elements(value) .map(element -> element.accept(generator)) .filter(element -> element != null) .collect(toList()); List<String> elements = elementTemplates.stream() .map(template -> context.adapt(template.getValue(), componentResultType, template.getType())) .collect(toList()); List<String> statements = elementTemplates.stream() .flatMap(template -> template.getStatements().stream()) .collect(toList()); String tempVar = local.getName(); if (!equalGenericTypes(effectiveResultType, temporaryType)) { tempVar = context.temporaryLocal(); } String set = types.isHidden(type) ? context.adapt(types.getWrappedName(type), temporaryType, types.wrapHidden(type)) : newObject(types.getConstructorTypeName(type)); String temporaryTypeName = Optional.of(temporaryType) .filter(t -> typeArguments(t).count() > 0) .filter(t -> typeArguments(t).allMatch(Types::isBound)) .map(t -> types.getVariableTypeName(t)) .orElse(types.getRawTypeName(temporaryType)); String setInit = assignLocalVariableStatement(temporaryTypeName, tempVar, set); statements.add(setInit); for (String element : elements) { String addElement = callMethodStatement(tempVar, "add", element); statements.add(addElement); } if (local.isDefined() && !local.isReady()) { statements.add(callMethodStatement(local.getName(), "addAll", tempVar)); } else if (context.needsAdaptation(effectiveResultType, temporaryType)) { tempVar = context.adapt(tempVar, effectiveResultType, temporaryType); statements.add(assignLocalVariableStatement(types.getVariableTypeName(effectiveResultType), local.getName(), tempVar)); } else if (!equalGenericTypes(effectiveResultType, temporaryType)) { statements.add(assignLocalVariableStatement(types.getVariableTypeName(effectiveResultType), local.getName(), tempVar)); } return variable(local.getName(), local.getType(), statements); }); } }
lgpl-3.0
HATB0T/RuneCraftery
forge/mcp/temp/src/minecraft/net/minecraft/server/dedicated/DedicatedServer.java
13490
package net.minecraft.server.dedicated; import cpw.mods.fml.relauncher.Side; import cpw.mods.fml.relauncher.SideOnly; import java.io.File; import java.io.IOException; import java.net.InetAddress; import java.util.ArrayList; import java.util.Collections; import java.util.List; import java.util.Random; import net.minecraft.command.ICommandSender; import net.minecraft.command.ServerCommand; import net.minecraft.crash.CrashReport; import net.minecraft.entity.player.EntityPlayer; import net.minecraft.logging.ILogAgent; import net.minecraft.logging.LogAgent; import net.minecraft.network.NetworkListenThread; import net.minecraft.network.rcon.IServer; import net.minecraft.network.rcon.RConThreadMain; import net.minecraft.network.rcon.RConThreadQuery; import net.minecraft.profiler.PlayerUsageSnooper; import net.minecraft.server.MinecraftServer; import net.minecraft.server.dedicated.CallableServerType; import net.minecraft.server.dedicated.CallableType; import net.minecraft.server.dedicated.DedicatedPlayerList; import net.minecraft.server.dedicated.DedicatedServerCommandThread; import net.minecraft.server.dedicated.DedicatedServerListenThread; import net.minecraft.server.dedicated.DedicatedServerSleepThread; import net.minecraft.server.dedicated.PropertyManager; import net.minecraft.server.gui.MinecraftServerGui; import net.minecraft.server.management.ServerConfigurationManager; import net.minecraft.util.ChunkCoordinates; import net.minecraft.util.CryptManager; import net.minecraft.util.MathHelper; import net.minecraft.world.EnumGameType; import net.minecraft.world.World; import net.minecraft.world.WorldSettings; import net.minecraft.world.WorldType; public class DedicatedServer extends MinecraftServer implements IServer { private final List field_71341_l = Collections.synchronizedList(new ArrayList()); private final ILogAgent field_98131_l; private RConThreadQuery field_71342_m; private RConThreadMain field_71339_n; private PropertyManager field_71340_o; private boolean field_71338_p; private EnumGameType field_71337_q; private NetworkListenThread field_71336_r; private boolean field_71335_s; public DedicatedServer(File p_i1508_1_) { super(p_i1508_1_); this.field_98131_l = new LogAgent("Minecraft-Server", (String)null, (new File(p_i1508_1_, "server.log")).getAbsolutePath()); new DedicatedServerSleepThread(this); } protected boolean func_71197_b() throws IOException { DedicatedServerCommandThread var1 = new DedicatedServerCommandThread(this); var1.setDaemon(true); var1.start(); this.func_98033_al().func_98233_a("Starting minecraft server version 1.6.4"); if(Runtime.getRuntime().maxMemory() / 1024L / 1024L < 512L) { this.func_98033_al().func_98236_b("To start the server with more ram, launch it as \"java -Xmx1024M -Xms1024M -jar minecraft_server.jar\""); } this.func_98033_al().func_98233_a("Loading properties"); this.field_71340_o = new PropertyManager(new File("server.properties"), this.func_98033_al()); if(this.func_71264_H()) { this.func_71189_e("127.0.0.1"); } else { this.func_71229_d(this.field_71340_o.func_73670_a("online-mode", true)); this.func_71189_e(this.field_71340_o.func_73671_a("server-ip", "")); } this.func_71251_e(this.field_71340_o.func_73670_a("spawn-animals", true)); this.func_71257_f(this.field_71340_o.func_73670_a("spawn-npcs", true)); this.func_71188_g(this.field_71340_o.func_73670_a("pvp", true)); this.func_71245_h(this.field_71340_o.func_73670_a("allow-flight", false)); this.func_71269_o(this.field_71340_o.func_73671_a("texture-pack", "")); this.func_71205_p(this.field_71340_o.func_73671_a("motd", "A Minecraft Server")); this.func_104055_i(this.field_71340_o.func_73670_a("force-gamemode", false)); this.func_143006_e(this.field_71340_o.func_73669_a("player-idle-timeout", 0)); if(this.field_71340_o.func_73669_a("difficulty", 1) < 0) { this.field_71340_o.func_73667_a("difficulty", Integer.valueOf(0)); } else if(this.field_71340_o.func_73669_a("difficulty", 1) > 3) { this.field_71340_o.func_73667_a("difficulty", Integer.valueOf(3)); } this.field_71338_p = this.field_71340_o.func_73670_a("generate-structures", true); int var2 = this.field_71340_o.func_73669_a("gamemode", EnumGameType.SURVIVAL.func_77148_a()); this.field_71337_q = WorldSettings.func_77161_a(var2); this.func_98033_al().func_98233_a("Default game type: " + this.field_71337_q); InetAddress var3 = null; if(this.func_71211_k().length() > 0) { var3 = InetAddress.getByName(this.func_71211_k()); } if(this.func_71215_F() < 0) { this.func_71208_b(this.field_71340_o.func_73669_a("server-port", 25565)); } this.func_98033_al().func_98233_a("Generating keypair"); this.func_71253_a(CryptManager.func_75891_b()); this.func_98033_al().func_98233_a("Starting Minecraft server on " + (this.func_71211_k().length() == 0?"*":this.func_71211_k()) + ":" + this.func_71215_F()); try { this.field_71336_r = new DedicatedServerListenThread(this, var3, this.func_71215_F()); } catch (IOException var16) { this.func_98033_al().func_98236_b("**** FAILED TO BIND TO PORT!"); this.func_98033_al().func_98231_b("The exception was: {0}", new Object[]{var16.toString()}); this.func_98033_al().func_98236_b("Perhaps a server is already running on that port?"); return false; } if(!this.func_71266_T()) { this.func_98033_al().func_98236_b("**** SERVER IS RUNNING IN OFFLINE/INSECURE MODE!"); this.func_98033_al().func_98236_b("The server will make no attempt to authenticate usernames. Beware."); this.func_98033_al().func_98236_b("While this makes the game possible to play without internet access, it also opens up the ability for hackers to connect with any username they choose."); this.func_98033_al().func_98236_b("To change this, set \"online-mode\" to \"true\" in the server.properties file."); } this.func_71210_a(new DedicatedPlayerList(this)); long var4 = System.nanoTime(); if(this.func_71270_I() == null) { this.func_71261_m(this.field_71340_o.func_73671_a("level-name", "world")); } String var6 = this.field_71340_o.func_73671_a("level-seed", ""); String var7 = this.field_71340_o.func_73671_a("level-type", "DEFAULT"); String var8 = this.field_71340_o.func_73671_a("generator-settings", ""); long var9 = (new Random()).nextLong(); if(var6.length() > 0) { try { long var11 = Long.parseLong(var6); if(var11 != 0L) { var9 = var11; } } catch (NumberFormatException var15) { var9 = (long)var6.hashCode(); } } WorldType var17 = WorldType.func_77130_a(var7); if(var17 == null) { var17 = WorldType.field_77137_b; } this.func_71191_d(this.field_71340_o.func_73669_a("max-build-height", 256)); this.func_71191_d((this.func_71207_Z() + 8) / 16 * 16); this.func_71191_d(MathHelper.func_76125_a(this.func_71207_Z(), 64, 256)); this.field_71340_o.func_73667_a("max-build-height", Integer.valueOf(this.func_71207_Z())); this.func_98033_al().func_98233_a("Preparing level \"" + this.func_71270_I() + "\""); this.func_71247_a(this.func_71270_I(), this.func_71270_I(), var9, var17, var8); long var12 = System.nanoTime() - var4; String var14 = String.format("%.3fs", new Object[]{Double.valueOf((double)var12 / 1.0E9D)}); this.func_98033_al().func_98233_a("Done (" + var14 + ")! For help, type \"help\" or \"?\""); if(this.field_71340_o.func_73670_a("enable-query", false)) { this.func_98033_al().func_98233_a("Starting GS4 status listener"); this.field_71342_m = new RConThreadQuery(this); this.field_71342_m.func_72602_a(); } if(this.field_71340_o.func_73670_a("enable-rcon", false)) { this.func_98033_al().func_98233_a("Starting remote control listener"); this.field_71339_n = new RConThreadMain(this); this.field_71339_n.func_72602_a(); } return true; } public boolean func_71225_e() { return this.field_71338_p; } public EnumGameType func_71265_f() { return this.field_71337_q; } public int func_71232_g() { return this.field_71340_o.func_73669_a("difficulty", 1); } public boolean func_71199_h() { return this.field_71340_o.func_73670_a("hardcore", false); } protected void func_71228_a(CrashReport p_71228_1_) { while(this.func_71278_l()) { this.func_71333_ah(); try { Thread.sleep(10L); } catch (InterruptedException var3) { var3.printStackTrace(); } } } public CrashReport func_71230_b(CrashReport p_71230_1_) { p_71230_1_ = super.func_71230_b(p_71230_1_); p_71230_1_.func_85056_g().func_71500_a("Is Modded", new CallableType(this)); p_71230_1_.func_85056_g().func_71500_a("Type", new CallableServerType(this)); return p_71230_1_; } protected void func_71240_o() { System.exit(0); } protected void func_71190_q() { super.func_71190_q(); this.func_71333_ah(); } public boolean func_71255_r() { return this.field_71340_o.func_73670_a("allow-nether", true); } public boolean func_71193_K() { return this.field_71340_o.func_73670_a("spawn-monsters", true); } public void func_70000_a(PlayerUsageSnooper p_70000_1_) { p_70000_1_.func_76472_a("whitelist_enabled", Boolean.valueOf(this.func_71334_ai().func_72383_n())); p_70000_1_.func_76472_a("whitelist_count", Integer.valueOf(this.func_71334_ai().func_72388_h().size())); super.func_70000_a(p_70000_1_); } public boolean func_70002_Q() { return this.field_71340_o.func_73670_a("snooper-enabled", true); } public void func_71331_a(String p_71331_1_, ICommandSender p_71331_2_) { this.field_71341_l.add(new ServerCommand(p_71331_1_, p_71331_2_)); } public void func_71333_ah() { while(!this.field_71341_l.isEmpty()) { ServerCommand var1 = (ServerCommand)this.field_71341_l.remove(0); this.func_71187_D().func_71556_a(var1.field_73701_b, var1.field_73702_a); } } public boolean func_71262_S() { return true; } public DedicatedPlayerList func_71334_ai() { return (DedicatedPlayerList)super.func_71203_ab(); } public NetworkListenThread func_71212_ac() { return this.field_71336_r; } public int func_71327_a(String p_71327_1_, int p_71327_2_) { return this.field_71340_o.func_73669_a(p_71327_1_, p_71327_2_); } public String func_71330_a(String p_71330_1_, String p_71330_2_) { return this.field_71340_o.func_73671_a(p_71330_1_, p_71330_2_); } public boolean func_71332_a(String p_71332_1_, boolean p_71332_2_) { return this.field_71340_o.func_73670_a(p_71332_1_, p_71332_2_); } public void func_71328_a(String p_71328_1_, Object p_71328_2_) { this.field_71340_o.func_73667_a(p_71328_1_, p_71328_2_); } public void func_71326_a() { this.field_71340_o.func_73668_b(); } public String func_71329_c() { File var1 = this.field_71340_o.func_73665_c(); return var1 != null?var1.getAbsolutePath():"No settings file"; } public boolean func_71279_ae() { return this.field_71335_s; } public String func_71206_a(EnumGameType p_71206_1_, boolean p_71206_2_) { return ""; } public boolean func_82356_Z() { return this.field_71340_o.func_73670_a("enable-command-block", false); } public int func_82357_ak() { return this.field_71340_o.func_73669_a("spawn-protection", super.func_82357_ak()); } public boolean func_96290_a(World p_96290_1_, int p_96290_2_, int p_96290_3_, int p_96290_4_, EntityPlayer p_96290_5_) { if(p_96290_1_.field_73011_w.field_76574_g != 0) { return false; } else if(this.func_71334_ai().func_72376_i().isEmpty()) { return false; } else if(this.func_71334_ai().func_72353_e(p_96290_5_.func_70005_c_())) { return false; } else if(this.func_82357_ak() <= 0) { return false; } else { ChunkCoordinates var6 = p_96290_1_.func_72861_E(); int var7 = MathHelper.func_76130_a(p_96290_2_ - var6.field_71574_a); int var8 = MathHelper.func_76130_a(p_96290_4_ - var6.field_71573_c); int var9 = Math.max(var7, var8); return var9 <= this.func_82357_ak(); } } public ILogAgent func_98033_al() { return this.field_98131_l; } public int func_110455_j() { return this.field_71340_o.func_73669_a("op-permission-level", 4); } public void func_143006_e(int p_143006_1_) { super.func_143006_e(p_143006_1_); this.field_71340_o.func_73667_a("player-idle-timeout", Integer.valueOf(p_143006_1_)); this.func_71326_a(); } // $FF: synthetic method public ServerConfigurationManager func_71203_ab() { return this.func_71334_ai(); } @SideOnly(Side.SERVER) public void func_120011_ar() { MinecraftServerGui.func_120016_a(this); this.field_71335_s = true; } }
lgpl-3.0