repo_name stringlengths 5 108 | path stringlengths 6 333 | size stringlengths 1 6 | content stringlengths 4 977k | license stringclasses 15
values |
|---|---|---|---|---|
lat-lon/deegree2-base | deegree2-core/src/main/java/org/deegree/ogcwebservices/getcapabilities/Protocol.java | 1699 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.ogcwebservices.getcapabilities;
import java.io.Serializable;
/**
* Protocols for DCPTypes.
*
* @author <a href="mailto:uzs6tr@uni-bonn.de">Axel Schaefer </a>
* @version $Revision$ $Date$
*/
public abstract class Protocol implements Serializable {
private static final long serialVersionUID = 5814960889174484055L;
}
| lgpl-2.1 |
Im-Jrotica/forge_latest | build/tmp/recompileMc/sources/net/minecraft/world/biome/BiomeSnow.java | 2149 | package net.minecraft.world.biome;
import java.util.Random;
import net.minecraft.entity.monster.EntityPolarBear;
import net.minecraft.entity.passive.EntityRabbit;
import net.minecraft.init.Blocks;
import net.minecraft.util.math.BlockPos;
import net.minecraft.world.World;
import net.minecraft.world.gen.feature.WorldGenAbstractTree;
import net.minecraft.world.gen.feature.WorldGenIcePath;
import net.minecraft.world.gen.feature.WorldGenIceSpike;
import net.minecraft.world.gen.feature.WorldGenTaiga2;
public class BiomeSnow extends Biome
{
private final boolean superIcy;
private final WorldGenIceSpike iceSpike = new WorldGenIceSpike();
private final WorldGenIcePath icePatch = new WorldGenIcePath(4);
public BiomeSnow(boolean superIcyIn, Biome.BiomeProperties properties)
{
super(properties);
this.superIcy = superIcyIn;
if (superIcyIn)
{
this.topBlock = Blocks.SNOW.getDefaultState();
}
this.spawnableCreatureList.clear();
this.spawnableCreatureList.add(new Biome.SpawnListEntry(EntityRabbit.class, 10, 2, 3));
this.spawnableCreatureList.add(new Biome.SpawnListEntry(EntityPolarBear.class, 1, 1, 2));
}
/**
* returns the chance a creature has to spawn.
*/
public float getSpawningChance()
{
return 0.07F;
}
public void decorate(World worldIn, Random rand, BlockPos pos)
{
if (this.superIcy)
{
for (int i = 0; i < 3; ++i)
{
int j = rand.nextInt(16) + 8;
int k = rand.nextInt(16) + 8;
this.iceSpike.generate(worldIn, rand, worldIn.getHeight(pos.add(j, 0, k)));
}
for (int l = 0; l < 2; ++l)
{
int i1 = rand.nextInt(16) + 8;
int j1 = rand.nextInt(16) + 8;
this.icePatch.generate(worldIn, rand, worldIn.getHeight(pos.add(i1, 0, j1)));
}
}
super.decorate(worldIn, rand, pos);
}
public WorldGenAbstractTree genBigTreeChance(Random rand)
{
return new WorldGenTaiga2(false);
}
} | lgpl-2.1 |
evlist/orbeon-forms | src/main/java/org/orbeon/oxf/xforms/XFormsModelSchemaValidator.java | 40186 | /**
* Copyright (C) 2010 Orbeon, Inc.
*
* This program is free software; you can redistribute it and/or modify it under the terms of the
* GNU Lesser General Public License as published by the Free Software Foundation; either version
* 2.1 of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
*
* The full text of the license is available at http://www.gnu.org/copyleft/lesser.html
*/
package org.orbeon.oxf.xforms;
import org.apache.commons.lang3.StringUtils;
import org.apache.log4j.Logger;
import org.dom4j.Attribute;
import org.dom4j.Element;
import org.dom4j.Node;
import org.dom4j.QName;
import org.orbeon.msv.datatype.xsd.DatatypeFactory;
import org.orbeon.msv.datatype.xsd.XSDatatype;
import org.orbeon.msv.grammar.Expression;
import org.orbeon.msv.grammar.Grammar;
import org.orbeon.msv.grammar.IDContextProvider2;
import org.orbeon.msv.grammar.xmlschema.*;
import org.orbeon.msv.reader.GrammarReaderController;
import org.orbeon.msv.reader.util.GrammarLoader;
import org.orbeon.msv.reader.xmlschema.XMLSchemaReader;
import org.orbeon.msv.relaxng.datatype.Datatype;
import org.orbeon.msv.relaxng.datatype.DatatypeException;
import org.orbeon.msv.util.DatatypeRef;
import org.orbeon.msv.util.StartTagInfo;
import org.orbeon.msv.util.StringRef;
import org.orbeon.msv.verifier.Acceptor;
import org.orbeon.msv.verifier.regexp.ExpressionAcceptor;
import org.orbeon.msv.verifier.regexp.REDocumentDeclaration;
import org.orbeon.msv.verifier.regexp.SimpleAcceptor;
import org.orbeon.msv.verifier.regexp.StringToken;
import org.orbeon.msv.verifier.regexp.xmlschema.XSAcceptor;
import org.orbeon.msv.verifier.regexp.xmlschema.XSREDocDecl;
import org.orbeon.oxf.cache.Cache;
import org.orbeon.oxf.cache.CacheKey;
import org.orbeon.oxf.cache.ObjectCache;
import org.orbeon.oxf.common.OrbeonLocationException;
import org.orbeon.oxf.common.ValidationException;
import org.orbeon.oxf.pipeline.api.ExternalContext;
import org.orbeon.oxf.processor.validation.SchemaValidationException;
import org.orbeon.oxf.resources.URLFactory;
import org.orbeon.oxf.util.IndentedLogger;
import org.orbeon.oxf.util.LoggerFactory;
import org.orbeon.oxf.util.NetUtils;
import org.orbeon.oxf.xforms.msv.IDConstraintChecker;
import org.orbeon.oxf.xml.ContentHandlerHelper;
import org.orbeon.oxf.xml.TransformerUtils;
import org.orbeon.oxf.xml.XMLConstants;
import org.orbeon.oxf.xml.XMLUtils;
import org.orbeon.oxf.xml.dom4j.Dom4jUtils;
import org.orbeon.oxf.xml.dom4j.ExtendedLocationData;
import org.orbeon.oxf.xml.dom4j.LocationData;
import org.xml.sax.InputSource;
import org.xml.sax.Locator;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.AttributesImpl;
import javax.xml.parsers.SAXParserFactory;
import java.io.IOException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
/**
* Provides XML Schema validation services for the XForms model.
*
* TODO: support multiple schemas
*
* TODO: "3.3.1 The model Element [...] The schema list may include URI fragments referring to elements located
* outside the current model elsewhere in the containing document; e.g. "#myschema"."
*/
public class XFormsModelSchemaValidator {
private static final ValidationContext validationContext = new ValidationContext();
private Element modelElement;
private IndentedLogger indentedLogger;
private Grammar schemaGrammar;
private String[] schemaURIs;
private List<Element> schemaElements;
// REDocumentDeclaration is not reentrant, but the validator is used by a single thread
private REDocumentDeclaration documentDeclaration;
public XFormsModelSchemaValidator(Element modelElement, IndentedLogger indentedLogger) {
this.modelElement = modelElement;
this.indentedLogger = indentedLogger;
// Check for external schemas
final String schemaAttribute = modelElement.attributeValue(XFormsConstants.SCHEMA_QNAME);
if (schemaAttribute != null)
this.schemaURIs = StringUtils.split(NetUtils.encodeHRRI(schemaAttribute, false));
// Check for inline schemas
// "3.3.1 The model Element [...] xs:schema elements located inside the current model need not be listed."
for (final Element schemaElement: Dom4jUtils.elements( modelElement, XMLConstants.XML_SCHEMA_QNAME)) {
if (schemaElements == null)
schemaElements = new ArrayList<Element>();
schemaElements.add(schemaElement);
}
}
public XFormsModelSchemaValidator(String schemaURI) {
this.schemaURIs = new String[] { schemaURI };
}
public boolean hasSchema() {
return schemaGrammar != null;
}
private static class MSVGrammarReaderController implements GrammarReaderController {
static private Logger logger = LoggerFactory.createLogger(MSVGrammarReaderController.class);
private final String baseURI;
private final SchemaInfo schemaInfo;
MSVGrammarReaderController(final String baseURI, final SchemaInfo schemaInfo) {
this.baseURI = baseURI;
this.schemaInfo = schemaInfo;
}
public void warning(final Locator[] locators, final String message) {
if (locators == null || locators.length == 0) {
logger.warn(message);
} else {
final String first = XMLUtils.toString(locators[0]);
final StringBuilder sb = new StringBuilder(first);
for (int i = 1; i < locators.length; i++) {
sb.append(',');
final String locMsg = XMLUtils.toString(locators[i]);
sb.append(locMsg);
}
sb.append(':');
sb.append(message);
final String logMessage = sb.toString();
logger.warn(logMessage);
}
}
public void error(final Locator[] locators, final String message, final Exception exception) {
final LocationData locationData = locators.length > 0 ? new LocationData(locators[0]) : null;
throw new SchemaValidationException(message, exception, locationData);
}
public InputSource resolveEntity(final String pid, final String sid) throws SAXException, IOException {
final URL url = URLFactory.createURL(baseURI, sid);
schemaInfo.addInclude(url);
final String urlString = url.toString();
return XMLUtils.ENTITY_RESOLVER.resolveEntity("", urlString);
}
}
private static class SchemaKey extends CacheKey {
final String urlString;
SchemaKey(final String urlString) {
setClazz(SchemaKey.class);
this.urlString = urlString;
}
@Override
public int hashCode() {
return urlString.hashCode();
}
@Override
public boolean equals(final Object other) {
final boolean ret;
if (other instanceof SchemaKey) {
final SchemaKey rhs = (SchemaKey) other;
// NOTE: Must NEVER use URL.equals(), see http://brian.pontarelli.com/2006/12/05/mr-gosling-why-did-you-make-url-equals-suck/
ret = urlString.equals(rhs.urlString);
} else {
ret = false;
}
return ret;
}
@Override
public void toXML(ContentHandlerHelper helper, Object validities) {
helper.element("url", new String[] { "class", getClazz().getName(), "validity", (validities != null) ? validities.toString() : null, "url", urlString });
}
}
private static class SchemaInfo {
private final ArrayList<URL> includes = new ArrayList<URL>(0);
private final ArrayList<Long> modTimes = new ArrayList<Long>(0);
private Grammar grammar;
void addInclude(final URL url) throws IOException {
// Get the time first. This way if there's a problem the array lengths will remain the same.
final long lastModified = NetUtils.getLastModified(url); // can be 0 if unknown
includes.add(url);
modTimes.add(lastModified);
}
boolean includesUpToDate() {
boolean ret = true;
final int size = includes.size();
for (int i = 0; ret && i < size; i++) {
final URL url = includes.get(i);
try {
final long lastModified = NetUtils.getLastModified(url); // can be 0 if unknown
final long lastTime = modTimes.get(i);
ret = lastModified == lastTime;
} catch (final IOException e) {
// We won't propagate here. Reason is that while an include may be missing it may just be the case
// that it isn't included anymore _and_ it has been removed. So, we return false and then on a
// reparse we will find out the truth.
ret = false;
}
}
return ret;
}
void setGrammar(final Grammar grammar) {
this.grammar = grammar;
}
Grammar getGrammar() {
return grammar;
}
}
private static class ValidationContext implements IDContextProvider2 {
private Element currentElement;
public void setCurrentElement(Element currentElement) {
this.currentElement = currentElement;
}
public String resolveNamespacePrefix(final String prefix) {
return Dom4jUtils.getNamespaceContext(currentElement).get(prefix);
}
public String getBaseUri() {
return null;
}
public boolean isUnparsedEntity(final String s) {
return false;
}
public boolean isNotation(final String s) {
return false;
}
public void onID(final Datatype dt, final StringToken st) {
}
}
private void addSchemaError(final Element element, final String errMsg) {
final String newErrorMessage;
if (errMsg == null) {
// Looks like if n is an element and errMsg == null then the problem is missing
// character data. No idea why MSV doesn't just give us the error msg itself.
newErrorMessage = "Missing character data.";
} else {
newErrorMessage = errMsg;
}
if (indentedLogger.isDebugEnabled())
indentedLogger.logDebug("schema", "validation error", "error", newErrorMessage);
InstanceData.addSchemaError(element);
}
private void addSchemaError(final Attribute attribute, final String schemaError) {
if (indentedLogger.isDebugEnabled())
indentedLogger.logDebug("schema", "validation error", "error", schemaError);
InstanceData.addSchemaError(attribute);
}
private boolean handleIDErrors(final IDConstraintChecker icc) {
boolean isValid = true;
for (ErrorInfo errorInfo = icc.clearErrorInfo(); errorInfo != null; errorInfo = icc.clearErrorInfo()) {
if (indentedLogger.isDebugEnabled())
indentedLogger.logDebug("schema", "validation error", "error", errorInfo.message);
addSchemaError(errorInfo.element, errorInfo.message);
isValid = false;
}
return isValid;
}
private boolean validateElement(final Element element, final Acceptor acceptor, final IDConstraintChecker icc, final boolean isReportErrors) {
boolean isElementValid = true;
// Create StartTagInfo
final StartTagInfo startTagInfo;
{
final String uri = element.getNamespaceURI();
final String name = element.getName();
final String qName = element.getQualifiedName();
final List attributesList = element.attributes();
final AttributesImpl attributes = new AttributesImpl();
for (Object anAttributesList: attributesList) {
final Attribute attribute = (Attribute) anAttributesList;
final String attributeURI = attribute.getNamespaceURI();
final String attributeName = attribute.getName();
final String attributeQName = attribute.getQualifiedName();
final String attributeValue = attribute.getValue();
attributes.addAttribute(attributeURI, attributeName, attributeQName, null, attributeValue);
}
validationContext.setCurrentElement(element);
startTagInfo = new StartTagInfo(uri, name, qName, attributes, validationContext);
}
final StringRef stringRef = new StringRef();
// Get child acceptor
final Acceptor childAcceptor;
{
Acceptor tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, null);
if (tempChildAcceptor == null) {
if (isReportErrors) {
tempChildAcceptor = acceptor.createChildAcceptor(startTagInfo, stringRef);
addSchemaError(element, stringRef.str);
isElementValid = false;
} else {
return false;
}
}
childAcceptor = tempChildAcceptor;
}
// Handle id errors
if (icc != null && isReportErrors) {
icc.onNextAcceptorReady(startTagInfo, childAcceptor, element);
isElementValid &= handleIDErrors(icc);
}
// Validate children
final DatatypeRef datatypeRef = new DatatypeRef();
final boolean childrenValid = validateChildren(element, childAcceptor, startTagInfo, icc, datatypeRef, isReportErrors);
if (!childrenValid) {
if (isReportErrors)
isElementValid = false;
else
return false;
}
// TODO: MSV doesn't allow getting the type if validity check fails. However, we would like to obtain datatype validity in XForms.
if (!childAcceptor.isAcceptState(null)) {
if (isReportErrors) {
childAcceptor.isAcceptState(stringRef);
addSchemaError(element, stringRef.str);
isElementValid = false;
} else {
return false;
}
} else {
// Attempt to set datatype name
setDataType(datatypeRef, element);
}
// Handle id errors
if (icc != null && isReportErrors) {
icc.endElement(element, datatypeRef.types);
isElementValid &= handleIDErrors(icc);
}
// Get back to parent acceptor
if (!acceptor.stepForward(childAcceptor, null)) {
if (isReportErrors) {
acceptor.stepForward(childAcceptor, stringRef);
addSchemaError(element, stringRef.str);
isElementValid = false;
} else {
return false;
}
}
if (isReportErrors) {
// Element may be invalid or not
return isElementValid;
} else {
// This element is valid
return true;
}
}
private void setDataType(DatatypeRef datatypeRef, Node node) {
if (datatypeRef.types != null && datatypeRef.types.length > 0) {
// This element is valid and has at least one assigned datatype
// Attempt to set datatype name
final Datatype datatype = datatypeRef.types[0];
if (datatype instanceof XSDatatype) {
final XSDatatype xsDatatype = (XSDatatype) datatype;
final String dataTypeURI = xsDatatype.getNamespaceUri();
final String dataTypeName = xsDatatype.getName();
if (dataTypeName != null && !dataTypeName.equals(""))
InstanceData.setSchemaType(node, QName.get(dataTypeName, "", dataTypeURI));
}
}
}
/**
* Validate an element following the XML Schema "lax" mode.
*
* @param element element to validate
*/
private boolean validateElementLax(final Element element) {
final String elementURI;
final String elementName;
// NOTE: We do some special processing for xsi:type to find if there is a type declared for it. If not, we do
// lax processing. However, it is not clear whether we should apply lax processing in this case or not. Maybe if
// an xsi:type is specified and not found, the element should just be invalid.
// TODO: should pass true?
final QName xsiType = Dom4jUtils.extractAttributeValueQName(element, XMLConstants.XSI_TYPE_QNAME, false);
if (xsiType != null) {
// Honor xsi:type
elementURI = xsiType.getNamespaceURI();
elementName = xsiType.getName();
} else {
// Use element name
elementURI = element.getNamespaceURI();
elementName = element.getName();
}
boolean isValid = true;
{
// Find expression for element type
final Expression expression;
{
// Find schema for type namespace
final XMLSchemaSchema schema = ((XMLSchemaGrammar) schemaGrammar).getByNamespace(elementURI);
if (schema != null) {
// Try to find the expression in the schema
final ElementDeclExp elementDeclExp = schema.elementDecls.get(elementName);
if (elementDeclExp != null) {
// Found element type
expression = elementDeclExp;
} else if (xsiType != null) {
// Try also complex type
expression = schema.complexTypes.get(elementName);
} else {
// No type found
expression = null;
}
} else {
// No schema so no expression
expression = null;
}
}
if (expression != null) {
// Found type for element, so validate element
final Acceptor acceptor = documentDeclaration.createAcceptor();
isValid &= validateElement(element, acceptor, null, true);
} else {
// Element does not have type, so try to validate attributes and children elements
// Attributes
if (false) {
// TODO: find out way of validating an attribute only
// TODO: should we also look at schema.attributeGroups?
final List attributesList = element.attributes();
for (final Iterator iterator = attributesList.iterator(); iterator.hasNext();) {
final Attribute attribute = (Attribute) iterator.next();
final String attributeURI = attribute.getNamespaceURI();
final String attributeName = attribute.getName();
// final String attributeQName = attribute.getQualifiedName();
// final String attributeValue = attribute.getValue();
// Find expression for element type
final Expression attributeExpression;
{
// Find schema for type namespace
final XMLSchemaSchema schema = ((XMLSchemaGrammar) schemaGrammar).getByNamespace(attributeURI);
if (schema != null) {
attributeExpression = schema.attributeDecls.get(attributeName);
} else {
attributeExpression = null;
}
}
if (attributeExpression != null) {
// final ExpressionAcceptor expressionAcceptor = new SimpleAcceptor(documentDeclaration, attributeExpression, null, null);
// // Validate attribute value
// final StringRef errorStringRef = new StringRef();
// final DatatypeRef datatypeRef = new DatatypeRef();
//
// if (!expressionAcceptor.onAttribute2(attributeURI, attributeName, attributeQName, attributeValue, validationContext, errorStringRef, datatypeRef)) {
// if (errorStringRef.str == null) // not sure if this can happen
// errorStringRef.str = "Error validating attribute";
// addSchemaError(attribute, errorStringRef.str);
// }
// if (!expressionAcceptor.onText2(attributeValue, validationContext, errorStringRef, datatypeRef)) {
// if (errorStringRef.str == null) // not sure if this can happen
// errorStringRef.str = "Error validating attribute";
// addSchemaError(attribute, errorStringRef.str);
// }
//
// // Check final acceptor state
// if (!expressionAcceptor.isAcceptState(errorStringRef)) {
// if (errorStringRef.str == null) // not sure if this can happen
// errorStringRef.str = "Error validating attribute";
// addSchemaError(attribute, errorStringRef.str);
// }
}
}
}
// Validate children elements
for (final Iterator iterator = element.elementIterator(); iterator.hasNext();) {
final Element childElement = (Element) iterator.next();
isValid &= validateElementLax(childElement);
}
}
}
return isValid;
}
/**
* Note that all of the attributes of element should be in startTagInfo.attributes. If they are out of sync it break
* the ability to access the attributes by index.
*/
private boolean validateChildren(final Element element, final Acceptor acceptor, final StartTagInfo startTagInfo,
final IDConstraintChecker icc, final DatatypeRef datatypeRef, final boolean isReportErrors) {
boolean isElementChildrenValid = true;
// Validate attributes
final StringRef stringRef = new StringRef();
{
final DatatypeRef attributeDatatypeRef = new DatatypeRef();
final int end = startTagInfo.attributes.getLength();
for (int i = 0; i < end; i++) {
final String uri = startTagInfo.attributes.getURI(i);
final String name = startTagInfo.attributes.getLocalName(i);
final String qName = startTagInfo.attributes.getQName(i);
final String value = startTagInfo.attributes.getValue(i);
final Attribute attribute = element.attribute(i);
if (!acceptor.onAttribute2(uri, name, qName, value, startTagInfo.context, null, attributeDatatypeRef)) {
if (isReportErrors) {
acceptor.onAttribute2(uri, name, qName, value, startTagInfo.context, stringRef, null);
addSchemaError(attribute, stringRef.str);
isElementChildrenValid = false;
} else {
return false;
}
}
// Attempt to set datatype name
setDataType(attributeDatatypeRef, attribute);
if (icc != null && isReportErrors) {
icc.feedAttribute(acceptor, attribute, attributeDatatypeRef.types);
isElementChildrenValid &= handleIDErrors(icc);
}
}
if (!acceptor.onEndAttributes(startTagInfo, null)) {
if (isReportErrors) {
acceptor.onEndAttributes(startTagInfo, stringRef);
addSchemaError(element, stringRef.str);
isElementChildrenValid = false;
} else {
return false;
}
}
}
// Get string care level here like in MSV Verifier.java
final int stringCareLevel = acceptor.getStringCareLevel();
// Validate children elements
for (final Iterator iterator = element.elementIterator(); iterator.hasNext();) {
final Element childElement = (Element) iterator.next();
final boolean isChildElementValid = validateElement(childElement, acceptor, icc, isReportErrors);
if (!isChildElementValid) {
if (isReportErrors) {
isElementChildrenValid = false;
} else {
return false;
}
}
}
// If we just iterate over nodes, i.e. use nodeIterator() ) then validation of char data ends up being
// incorrect. Specifically elements of type xs:string end up being invalid when they are empty. (Which is
// wrong.)
// TODO: this is very likely wrong as we get the whole text value of the element!!!
final String text = element.getText();
switch (stringCareLevel) {
case Acceptor.STRING_IGNORE:
{
if (text.length() > 0) {
// addSchemaError(elt, sr.str);
// TODO: Check this! It is not clear whether this should actually be tested
// as above. I have noticed that some documents that should pass validation
// actually do not with the above, namely with <xsd:element> with no type
// but the element actually containing character content. But is removing
// the test correct?
}
datatypeRef.types = null;
break;
}
case Acceptor.STRING_PROHIBITED:
{
final String trimmed = text.trim();
if (trimmed.length() > 0) {
if (isReportErrors) {
addSchemaError(element, stringRef.str);
isElementChildrenValid = false;
} else {
return false;
}
}
datatypeRef.types = null;
break;
}
case Acceptor.STRING_STRICT:
{
if (!acceptor.onText2(text, startTagInfo.context, null, datatypeRef)) {
if (isReportErrors) {
acceptor.onText2(text, startTagInfo.context, stringRef, null);
addSchemaError(element, stringRef.str);
isElementChildrenValid = false;
} else {
return false;
}
}
break;
}
}
if (isReportErrors) {
// Element children may be invalid or not
return isElementChildrenValid;
} else {
// The element children are valid
return true;
}
}
/**
* Load XForms model schemas.
*
* @param containingDocument current document
*/
public void loadSchemas(XFormsContainingDocument containingDocument) {
// Check for external schema
if (schemaURIs != null && schemaURIs.length > 0) {
// Resolve URL
// NOTE: We do not support "optimized" access here, we always use an URL, because loadGrammar() wants a URL
final String resolvedURLString = XFormsUtils.resolveServiceURL(containingDocument, modelElement, schemaURIs[0],
ExternalContext.Response.REWRITE_MODE_ABSOLUTE);
// Load associated grammar
schemaGrammar = loadCacheGrammar(resolvedURLString);
}
// Check for inline schema
if (schemaElements != null && schemaElements.size() > 0) {
schemaGrammar = loadInlineGrammar(null, schemaElements.get(0)); // TODO: specify baseURI
}
}
/**
* Load and cache a Grammar for a given schema URI.
*/
private Grammar loadCacheGrammar(final String absoluteSchemaURL) {
try {
final URL url = URLFactory.createURL(absoluteSchemaURL);
final long modificationTime = NetUtils.getLastModified(url); // can be 0 if unknown
final Cache cache = ObjectCache.instance();
final SchemaKey schemaKey = new SchemaKey(absoluteSchemaURL);
final SchemaInfo schemaInfo;
{
final Object cached = cache.findValid(schemaKey, modificationTime);
schemaInfo = cached == null ? null : (SchemaInfo) cached;
}
// Grammar is thread safe while REDocumentDeclaration is not so cache grammar
// instead of REDocumentDeclaration
final Grammar grammar;
if (schemaInfo == null || !schemaInfo.includesUpToDate()) {
final SchemaInfo newSchemaInfo = new SchemaInfo();
final InputSource is = XMLUtils.ENTITY_RESOLVER.resolveEntity("", absoluteSchemaURL);
final MSVGrammarReaderController controller = new MSVGrammarReaderController(absoluteSchemaURL, newSchemaInfo);
final SAXParserFactory factory = XMLUtils.getSAXParserFactory(XMLUtils.ParserConfiguration.XINCLUDE_ONLY);
grammar = GrammarLoader.loadSchema(is, controller, factory);
newSchemaInfo.setGrammar(grammar);
cache.add(schemaKey, modificationTime, newSchemaInfo);
} else {
grammar = schemaInfo.getGrammar();
}
return grammar;
} catch (Exception e) {
throw OrbeonLocationException.wrapException(e, new ExtendedLocationData(absoluteSchemaURL, -1, -1, "loading schema from URI"));
}
}
/**
* Load an inline schema.
*
* @param baseURI URI to resolve external dependencies
* @param schemaElement root element of the schema
* @return
*/
// private Grammar loadInlineGrammar(final String baseURI, final NodeInfo schemaElementInfo) {
private Grammar loadInlineGrammar(final String baseURI, final Element schemaElement) {
final SchemaInfo newSchemaInfo = new SchemaInfo(); // used for resolving external dependencies
// TODO: Use SchemaInfo to cache dependencies if any
final MSVGrammarReaderController controller = new MSVGrammarReaderController(baseURI, newSchemaInfo);
final SAXParserFactory saxParserFactory = XMLUtils.getSAXParserFactory(XMLUtils.ParserConfiguration.PLAIN);
final XMLSchemaReader reader = new XMLSchemaReader(controller, saxParserFactory);
// TransformerUtils.writeTinyTree(schemaElementInfo, reader);
// TODO: We create an entirely new dom4j document here because otherwise the transformation picks the whole document
TransformerUtils.writeDom4j(Dom4jUtils.createDocumentCopyParentNamespaces(schemaElement), reader);
return reader.getResult();
}
/**
* Apply schema validation to an instance. The instance may content a hint specifying whether to perform "lax",
* "strict", or "skip" validation.
*
* @param instance instance to validate
*/
public boolean validateInstance(XFormsInstance instance) {
if (schemaGrammar != null) {
// Create REDocumentDeclaration if needed
if (documentDeclaration == null) {
documentDeclaration = createDocumentDeclaration(schemaGrammar);
}
// Get validation mode ("lax" is the default)
boolean isValid = true;
if (instance.instance().isLaxValidation()) {
// Lax validation
final Element instanceRootElement = instance.underlyingDocumentOrNull().getRootElement();
isValid &= validateElementLax(instanceRootElement);
} else if (instance.instance().isStrictValidation()) {
// Strict validation
final Acceptor acceptor = documentDeclaration.createAcceptor();
final Element instanceRootElement = instance.underlyingDocumentOrNull().getRootElement();
final IDConstraintChecker idConstraintChecker = new IDConstraintChecker();
isValid &= validateElement(instanceRootElement, acceptor, idConstraintChecker, true);
idConstraintChecker.endDocument();
isValid &= handleIDErrors(idConstraintChecker);
} else {
// Skip validation
}
return isValid;
} else {
return true;
}
}
/**
* Check whether a node's value satisfies a simple schema type definition given by namespace URI and local name.
*
* @param value value to validate
* @param typeNamespaceURI namespace URI of the type ("" if no namespace)
* @param typeLocalname local name of the type
* @param typeQName QName of type type (for error handling)
* @param locationData LocationData to use in case of error
* @return validation error message, null if no error
*/
public String validateDatatype(String value, String typeNamespaceURI, String typeLocalname, String typeQName, LocationData locationData) {
if (typeNamespaceURI == null)
typeNamespaceURI = "";
// Create REDocumentDeclaration if needed
if (documentDeclaration == null) {
documentDeclaration = createDocumentDeclaration(schemaGrammar);
}
// Find expression to use to validate
final Expression contentModelExpression;
{
if (typeNamespaceURI.equals(XSAcceptor.XMLSchemaNamespace) ) {
// Handle built-in schema type
try {
contentModelExpression = schemaGrammar.getPool().createData(DatatypeFactory.getTypeByName(typeLocalname) );
} catch (DatatypeException e) {
throw new SchemaValidationException("Built-in schema type not found: " + typeLocalname, locationData);
}
} else {
// Find schema for type namespace
final XMLSchemaSchema schema = ((XMLSchemaGrammar) schemaGrammar).getByNamespace(typeNamespaceURI);
if (schema == null)
throw new SchemaValidationException("No schema found for namespace: " + typeNamespaceURI, locationData);
// Find simple type in schema
final SimpleTypeExp simpleTypeExpression = schema.simpleTypes.get(typeLocalname);
if (simpleTypeExpression != null) {
// There is a simple type definition
contentModelExpression = simpleTypeExpression;
} else {
// Find complex type in schema
final ComplexTypeExp complexTypeExpression = schema.complexTypes.get(typeLocalname);
if (complexTypeExpression != null) {
// There is a complex type definition
if (complexTypeExpression.simpleBaseType != null) {
// Complex type with simple content
// Here, we only validate the datatype part
// NOTE: Here we are guessing a little bit from MSV by looking at simpleBaseType. Is this 100% correct?
contentModelExpression = complexTypeExpression;
} else {
// XForms mandates simple types or complex types with simple content
throw new SchemaValidationException("Simple type or complex type with simple content required for type: " + typeQName, locationData);
}
} else {
// Find element declaration in schema
final ElementDeclExp elementDeclExp = schema.elementDecls.get(typeLocalname);
if (elementDeclExp != null) {
// There is an element type definition
final ElementDeclExp.XSElementExp xsElementExp = elementDeclExp.getElementExp();
final Expression contentModel = xsElementExp.contentModel;
if (contentModel instanceof ComplexTypeExp && ((ComplexTypeExp) contentModel).simpleBaseType != null) {
// Element complex type with simple content
// Here, we only validate the datatype part
// NOTE: Here again, we do some guesswork from MSV. Is this 100% correct?
contentModelExpression = contentModel;
} else {
throw new SchemaValidationException("Simple type or complex type with simple content required for type: " + typeQName, locationData);
}
} else {
// XForms mandates simple types or complex types with simple content
throw new SchemaValidationException("Simple type or complex type with simple content required for type: " + typeQName, locationData);
}
}
// TODO: Must also look at schema.attributeDecls?
}
}
}
// Create a simple acceptor
final ExpressionAcceptor expressionAcceptor = new SimpleAcceptor(documentDeclaration, contentModelExpression, null, null);
// Validate text
final StringRef errorStringRef = new StringRef();
final DatatypeRef datatypeRef = new DatatypeRef();
if (!expressionAcceptor.onText2(value, validationContext, errorStringRef, datatypeRef)) {
if (errorStringRef.str == null) // not sure if this can happen
errorStringRef.str = "Error validating simple type";
return errorStringRef.str;
}
// Check final acceptor state
if (!expressionAcceptor.isAcceptState(errorStringRef)) {
if (errorStringRef.str == null) // not sure if this can happen
errorStringRef.str = "Error validating simple type";
return errorStringRef.str;
}
// Value is valid
return null;
}
/**
* Create an REDocumentDeclaration.
*
* @param grammar Grammar to use
* @return REDocumentDeclaration for that Grammar
*/
private REDocumentDeclaration createDocumentDeclaration(Grammar grammar) {
if (grammar instanceof XMLSchemaGrammar)
return new XSREDocDecl((XMLSchemaGrammar) grammar);
else
return new REDocumentDeclaration(grammar);
}
/**
* Return the schema URIs specified on the model.
*
* @return array of schema URIs specified on the model, or null if none
*/
public String[] getSchemaURIs() {
return schemaURIs;
}
}
| lgpl-2.1 |
pubmed2ensembl/MartScript | src/org/ensembl/mart/util/FormattedSequencePrintStream.java | 8681 | /*
Copyright (C) 2003 EBI, GRL
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 org.ensembl.mart.util;
import java.io.OutputStream;
import java.io.PrintStream;
import java.io.UnsupportedEncodingException;
import java.util.logging.Logger;
/**
* Extended PrintStream to allow users to print fasta
* formatted sequence output with an unformatted header, and sequence formatted to a
* user-specified column width maximum, using a user supplied line ending.
* Users should use the normal PrintStream methods to write header elements.
* Users should use the various *Sequence methods to print out sequences.
* Note, the default line ending is a newline, but this can be over ridden.
*
* @author <a href="mailto:dlondon@ebi.ac.uk">Darin London</a>
* @author <a href="mailto:craig@ebi.ac.uk">Craig Melsopp</a>
*/
public class FormattedSequencePrintStream extends PrintStream {
private Logger logger = Logger.getLogger(FormattedSequencePrintStream.class.getName());
private final int maxColumnLen; // default, eg. no limit
private int currentColumn = 0;
private static final String DEFAULTLINEEND = "\n"; // default, but can be overridden
private final String LINEEND;
/**
* Constructor for a basic FormattedSequencePrintStream, with maxColumn and an underlying OutputStream.
* The default line ending, a newline, is used to add line endings to sequences.
* Autoflush is set to false.
*
* @param maxColumnLen - integer, column length max. A maxColumnLen of 0 signals that no formatting should occur
* @param out - underlying OutputStream for the PrintStream
*/
public FormattedSequencePrintStream(int maxColumnLen, OutputStream out) {
this(maxColumnLen, DEFAULTLINEEND, out, false);
}
public FormattedSequencePrintStream(int maxColumnLen, String lineEnd, OutputStream out) {
this(maxColumnLen, lineEnd, out, false);
}
/**
* Constructor for a FormattedSequencePrintStream, stating whether the underlying PrintStream should be in autoFlush
* mode, or not. The default line ending, a newline, is used to add line endings to sequences.
*
* @param maxColumnLen - integer, column length max. A maxColumnLen of 0 signals that no formatting should occur
* @param out - underlying OutputStream for the PrintStream
* @param autoFlush - boolean, if true, underlying PrintStream is set to autoFlush true
* @see java.io.PrintStream
*/
public FormattedSequencePrintStream(int maxColumnLen, OutputStream out, boolean autoFlush) {
this(maxColumnLen, DEFAULTLINEEND, out, autoFlush);
}
/**
* Constructor for a FormattedSequencePrintStream, setting the autoFlush and the lineEnd string to
* print when adding a line end to formatted sequence output. Useful for output such as HTML, where
* the newline should be </p> instead of \n.
*
* @param maxColumnLen - integer, column length max. A maxColumnLen of 0 signals that no formatting should occur
* @param lineEnd - String to end sequence lines with when the formatter inserts a new line to the sequences (default is newline).
* @param out - underlying OutputStream for the PrintStream
* @param autoFlush - boolean, if true, underlying PrintStream is set to autoFlush true
* @see java.io.PrintStream
*/
public FormattedSequencePrintStream(int maxColumnLen, String lineEnd, OutputStream out, boolean autoFlush) {
super(out, autoFlush);
this.maxColumnLen = maxColumnLen;
this.LINEEND = lineEnd;
}
/**
* Constructor for a FormattedSequencePrintStream, with a specified encoding.
*
* @param maxColumnLen - integer, column length max. A maxColumnLen of 0 signals that no formatting should occur
* @param out - underlying OutputStream for the PrintStream
* @param autoFlush - boolean, if true, underlying PrintStream is set to autoFlush true
* @param encoding - encoding to use for character/string conversion
* @throws java.io.UnsupportedEncodingException
* @see java.io.PrintStream
*/
public FormattedSequencePrintStream(int maxColumnLen, OutputStream out, String encoding) throws UnsupportedEncodingException {
this(maxColumnLen, DEFAULTLINEEND, out, false, encoding);
}
/**
* Constructor for a FormattedSequencePrintStream, with a specified lineEnd, autoFlush, and encoding.
*
* @param maxColumnLen - integer, column length max. A maxColumnLen of 0 signals that no formatting should occur
* @param out - underlying OutputStream for the PrintStream
* @param autoFlush - boolean, if true, underlying PrintStream is set to autoFlush true
* @param encoding - encoding to use for character/string conversion
* @throws java.io.UnsupportedEncodingException
* @see java.io.PrintStream
*/
public FormattedSequencePrintStream(int maxColumnLen, String lineEnd, OutputStream out, boolean autoFlush, String encoding) throws UnsupportedEncodingException {
super(out, autoFlush, encoding);
this.maxColumnLen = maxColumnLen;
this.LINEEND = lineEnd;
}
/**
* Write out a char of sequence, with formatting.
*
* @param x - char of sequence to be written
*/
public void printSequence(char x) {
if (currentColumn == maxColumnLen)
printLineAndReset();
print(x);
currentColumn++;
}
/**
* Write out a char[] object of sequence, with formatting.
*
* @param x - char[] with sequence to be printed
*/
public void printSequence(char[] x) {
int len = x.length;
int newlen = Math.min(len, maxColumnLen - currentColumn);
for (int i = 0; i < len; i += newlen, currentColumn += newlen) {
if (currentColumn == maxColumnLen)
printLineAndReset();
newlen = Math.min(newlen, len - i);
print(x,i,newlen);
}
}
private void print(char[] x, int off, int len) {
char[] newx = new char[len];
System.arraycopy(x, off, newx, 0, len);
print(newx);
}
/**
* Write out a String of sequence. Resolves to writeSequence(sequence.getBytes()).
* @param x
*/
public void printSequence(String x) {
writeSequence(x.getBytes());
}
/**
* Write out a byte of sequence, with formatting.
*
* @param b - byte of sequence to be printed
*/
public void writeSequence(byte b) {
if (currentColumn == maxColumnLen)
printLineAndReset();
write(b);
currentColumn++;
}
/**
* write an entire byte[] object containing sequence, with formatting.
*
* @param buf - byte[] containing sequence to be printed
*/
public void writeSequence(byte[] buf) {
writeSequence(buf, 0, buf.length);
}
/**
* write a portion of a byte[] object containing sequence, with formatting.
*
* @param buf - byte[] containing sequence bytes to be printed
* @param off - beginning offset, eg. byte[off] will be the first byte printed
* @param len - number of bytes to print, eg. byte[off] - byte[off + len - 1] will be printed
*/
public void writeSequence(byte[] buf, int off, int len) {
// if (logger.isLoggable(Level.WARNING))
// logger.warning("Recieved buf from off " + off + " to len " + len + "\n\n");
for (int i = off, newlen = Math.min(len - i, maxColumnLen - currentColumn); i < len; i += newlen, newlen = Math.min(len - i, maxColumnLen - currentColumn)) {
// if (logger.isLoggable(Level.WARNING))
// logger.warning( "maxColumnLen = "+ maxColumnLen + " currentColumn = " + currentColumn + " i = " + i + " newlen = " + newlen + "\nlen - i = " + (len - i) + " maxColumnLen - currentColumn = " + (maxColumnLen - currentColumn) + "\n");
write(buf,i,newlen);
currentColumn += newlen;
if (currentColumn == maxColumnLen)
printLineAndReset();
}
}
/**
* sets the columnCount to 0, to signal that a new output of sequence has begun
*/
public void resetColumnCount() {
currentColumn = 0;
}
private void printLineAndReset() {
print(LINEEND);
currentColumn = 0;
}
}
| lgpl-2.1 |
constpetrov/gpsExtractor | gps-e/src/gpsExtractor/tools/trk/TrackID.java | 2150 | package gpsExtractor.tools.trk;
import java.util.Date;
/**
* Created by IntelliJ IDEA.
* User: KPETROV
* Date: 22.09.2010
* Time: 11:56:06
* To change this template use File | Settings | File Templates.
*/
public class TrackID implements Comparable<TrackID>{
private final String fileName;
private final String trackName;
private final Date startDateTime;
public TrackID(String filename, String trackName, Date startDateTime) {
this.fileName = filename;
this.trackName = trackName;
this.startDateTime = startDateTime;
}
public String getFileName() {
return fileName;
}
public String getTrackName() {
return trackName;
}
public Date getStartDateTime() {
return startDateTime;
}
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
TrackID trackID = (TrackID) o;
if (fileName != null ? !fileName.equals(trackID.fileName) : trackID.fileName != null) return false;
if (startDateTime != null ? !startDateTime.equals(trackID.startDateTime) : trackID.startDateTime != null)
return false;
if (trackName != null ? !trackName.equals(trackID.trackName) : trackID.trackName != null) return false;
return true;
}
@Override
public int hashCode() {
int result = fileName != null ? fileName.hashCode() : 0;
result = 31 * result + (trackName != null ? trackName.hashCode() : 0);
result = 31 * result + (startDateTime != null ? startDateTime.hashCode() : 0);
return result;
}
public int compareTo(TrackID t){
if (this==t){
return 0;
}
if (this.equals(t)){
return 0;
}
if (fileName.compareTo(t.getFileName())!=0){
return fileName.compareTo(t.getFileName());
}
if (trackName.compareTo(t.getTrackName())!=0){
return trackName.compareTo(t.getTrackName());
}
return this.startDateTime.compareTo(t.getStartDateTime());
}
}
| lgpl-2.1 |
abhigrover101/zlog | src/java/src/test/java/com/cruzdb/TestBkClientClosed.java | 3316 | package com.cruzdb;
import java.util.ArrayList;
import java.util.Random;
import java.util.Enumeration;
import static org.junit.Assert.*;
import org.junit.*;
public class TestBkClientClosed{
@Test(expected=BKException.class)
public void openLedgerThrows() throws LogException,BKException{
BookKeeper bk = new BookKeeper("rbd","127.0.0.1",5678);
Random r = new Random();
String n = "" + r.nextInt();
LedgerHandle l = bk.createLedger(String.valueOf(n));
bk.close();
LedgerHandle l1 = bk.openLedger(String.valueOf(n));
assertEquals(n,l1.getId());
}
@Test(expected=BKException.class)
public void createLedgerthrows() throws LogException,BKException{
BookKeeper bk = new BookKeeper("rbd","127.0.0.1",5678);
bk.close();
Random r = new Random();
String n = "" + r.nextInt();
LedgerHandle l = bk.createLedger(String.valueOf(n));
assertEquals(n,l.getId());
}
@Test(expected=BKException.class)
public void addEntryThrows() throws LogException,BKException{
BookKeeper bk = new BookKeeper("rbd","127.0.0.1",5678);
Random r = new Random();
String n = "" + r.nextInt();
LedgerHandle l = bk.createLedger(String.valueOf(n));
bk.close();
long pos = l.addEntry("abc".getBytes());
}
@Test(expected=BKException.class)
public void readEntryThrows() throws LogException,BKException{
BookKeeper bk = new BookKeeper("rbd","127.0.0.1",5678);
Random r = new Random();
String n = "" + r.nextInt();
LedgerHandle l = bk.createLedger(String.valueOf(n));
long pos = l.addEntry("abc".getBytes());
bk.close();
Enumeration<LedgerEntry> e = l.readEntries(pos,pos);
String entry = new String(e.nextElement().getEntry());
assertEquals("abc",entry);
}
@Test(expected=BKException.class)
public void getIdThrows() throws LogException,BKException{
BookKeeper bk = new BookKeeper("rbd","127.0.0.1",5678);
Random r = new Random();
String n = "" + r.nextInt();
LedgerHandle l = bk.createLedger(String.valueOf(n));
bk.close();
String lid = l.getId();
assertEquals(n,lid);
}
@Test(expected=BKException.class)
public void readLastAddConfirmedThrows() throws LogException,BKException{
BookKeeper bk = new BookKeeper("rbd","127.0.0.1",5678);
Random r = new Random();
String n = "" + r.nextInt();
LedgerHandle l = bk.createLedger(String.valueOf(n));
long pos = l.addEntry("abc".getBytes());
bk.close();
long lac = l.readLastAddConfirmed();
assertEquals(pos,lac);
}
@Test(expected=BKException.class)
public void isClosedThrows() throws LogException,BKException{
BookKeeper bk = new BookKeeper("rbd","127.0.0.1",5678);
Random r = new Random();
String n = "" + r.nextInt();
LedgerHandle l = bk.createLedger(String.valueOf(n));
long pos = l.addEntry("abc".getBytes());
l.close();
bk.close();
boolean isClosed = l.isClosed();
assertEquals(true,isClosed);
}
@Test(expected=BKException.class)
public void CloseThrows() throws LogException,BKException{
BookKeeper bk = new BookKeeper("rbd","127.0.0.1",5678);
Random r = new Random();
String n = "" + r.nextInt();
LedgerHandle l = bk.createLedger(String.valueOf(n));
long pos = l.addEntry("abc".getBytes());
bk.close();
l.close();
boolean isClosed = l.isClosed();
assertEquals(true,isClosed);
}
}
| lgpl-2.1 |
mcarniel/oswing | srcdemo/demo7/TreeNodeVO.java | 682 | package demo7;
import org.openswing.swing.message.receive.java.ValueObjectImpl;
/**
* <p>Title: OpenSwing Framework</p>
* <p>Description: </p>
* <p>Copyright: Copyright (C) 2006 Mauro Carniel</p>
* <p> </p>
* @author Mauro Carniel
* @version 1.0
*/
public class TreeNodeVO extends ValueObjectImpl {
private String descrLevel;
private String codLevel;
public TreeNodeVO() {
}
public String getDescrLevel() {
return descrLevel;
}
public void setDescrLevel(String descrLevel) {
this.descrLevel = descrLevel;
}
public String getCodLevel() {
return codLevel;
}
public void setCodLevel(String codLevel) {
this.codLevel = codLevel;
}
}
| lgpl-2.1 |
cytoscape/cytoscape-impl | ding-impl/ding-presentation-impl/src/main/java/org/cytoscape/ding/impl/editor/SimpleRootPaneContainer.java | 5084 | package org.cytoscape.ding.impl.editor;
import java.awt.BorderLayout;
import java.awt.Component;
import java.awt.Container;
import java.awt.LayoutManager;
import javax.swing.JComponent;
import javax.swing.JLayeredPane;
import javax.swing.JRootPane;
import javax.swing.RootPaneContainer;
/*
* #%L
* Cytoscape Swing Application Impl (swing-application-impl)
* $Id:$
* $HeadURL:$
* %%
* Copyright (C) 2006 - 2021 The Cytoscape Consortium
* %%
* 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%
*/
@SuppressWarnings("serial")
public class SimpleRootPaneContainer extends JComponent implements RootPaneContainer {
/**
* The <code>JRootPane</code> instance that manages the <code>contentPane</code>
* and optional <code>menuBar</code> for this frame, as well as the <code>glassPane</code>.
*/
protected JRootPane rootPane;
/**
* If true then calls to <code>add</code> and <code>setLayout</code>
* will be forwarded to the <code>contentPane</code>. This is initially
* false, but is set to true when the <code>NetworkViewContainer</code> is constructed.
*/
private boolean rootPaneCheckingEnabled;
public SimpleRootPaneContainer() {
setRootPane(createDefaultRootPane());
setLayout(new BorderLayout());
add(getRootPane(), BorderLayout.CENTER);
}
@Override
public Container getContentPane() {
return getRootPane().getContentPane();
}
@Override
public void setContentPane(final Container c) {
Container oldValue = getContentPane();
getRootPane().setContentPane(c);
firePropertyChange("contentPane", oldValue, c);
}
@Override
public JLayeredPane getLayeredPane() {
return getRootPane().getLayeredPane();
}
@Override
public void setLayeredPane(JLayeredPane layered) {
final JLayeredPane oldValue = getLayeredPane();
getRootPane().setLayeredPane(layered);
firePropertyChange("layeredPane", oldValue, layered);
}
@Override
public Component getGlassPane() {
return getRootPane().getGlassPane();
}
@Override
public void setGlassPane(Component glass) {
Component oldValue = getGlassPane();
getRootPane().setGlassPane(glass);
firePropertyChange("glassPane", oldValue, glass);
}
@Override
public JRootPane getRootPane() {
return rootPane;
}
protected JRootPane createDefaultRootPane() {
return new JRootPane();
}
protected void setRootPane(JRootPane root) {
if (rootPane != null)
remove(rootPane);
JRootPane oldValue = getRootPane();
rootPane = root;
if (rootPane != null) {
boolean checkingEnabled = isRootPaneCheckingEnabled();
try {
setRootPaneCheckingEnabled(false);
add(rootPane, BorderLayout.CENTER);
} finally {
setRootPaneCheckingEnabled(checkingEnabled);
}
}
firePropertyChange("rootPane", oldValue, root);
}
/**
* Removes the specified component from the container. If
* <code>comp</code> is not the <code>rootPane</code>, this will forward
* the call to the <code>contentPane</code>. This will do nothing if
* <code>comp</code> is not a child of the <code>JFrame</code> or <code>contentPane</code>.
*/
@Override
public void remove(Component comp) {
final int oldCount = getComponentCount();
super.remove(comp);
if (oldCount == getComponentCount())
getContentPane().remove(comp);
}
/**
* Overridden to conditionally forward the call to the <code>contentPane</code>.
* Refer to {@link javax.swing.RootPaneContainer} for more information.
*/
@Override
public void setLayout(LayoutManager manager) {
if (isRootPaneCheckingEnabled())
getContentPane().setLayout(manager);
else
super.setLayout(manager);
}
/**
* This method is overridden to conditionally forward calls to the <code>contentPane</code>.
* By default, children are added to the <code>contentPane</code> instead
* of the frame, refer to {@link javax.swing.RootPaneContainer} for details.
*/
@Override
protected void addImpl(Component comp, Object constraints, int index) {
if (isRootPaneCheckingEnabled())
getContentPane().add(comp, constraints, index);
else
super.addImpl(comp, constraints, index);
}
private boolean isRootPaneCheckingEnabled() {
return rootPaneCheckingEnabled;
}
private void setRootPaneCheckingEnabled(boolean enabled) {
rootPaneCheckingEnabled = enabled;
}
}
| lgpl-2.1 |
shabanovd/exist | src/org/exist/security/xacml/XACMLSource.java | 4550 | /*
* eXist Open Source Native XML Database
* Copyright (C) 2001-06 The eXist Project
* http://exist-db.org
*
* This program is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public License
* as published by the Free Software Foundation; either version 2
* of the License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
*
* $Id$
*/
package org.exist.security.xacml;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URL;
import org.exist.source.*;
import org.exist.xmldb.XmldbURI;
/**
* This class represents the source of some content. It has
* a key, which uniquely identifies this source within its type.
* For possible type values, see {@link XACMLConstants XACMLConstants}.
*/
public class XACMLSource
{
private static final String FILE_PROTOCOL = "file";
private final String type;
private final String key;
public XACMLSource() { this(null, null); }
public XACMLSource(String type, String key)
{
this.type = type;
this.key = key;
}
public static XACMLSource getInstance(Class<?> source)
{
if(source == null)
{throw new NullPointerException("Source class cannot be null");}
return getInstance(source.getName());
}
public static XACMLSource getInstance(String sourceClassName)
{
if(sourceClassName == null)
{throw new NullPointerException("Source class name cannot be null");}
return new XACMLSource(XACMLConstants.CLASS_SOURCE_TYPE, sourceClassName);
}
public static XACMLSource getInstance(Source source)
{
if(source == null)
{throw new NullPointerException("Source cannot be null");}
if(source instanceof FileSource)
{return new XACMLSource(XACMLConstants.FILE_SOURCE_TYPE, ((FileSource)source).getFilePath());}
if(source instanceof URLSource)
{
final URL url = ((URLSource)source).getURL();
final String protocol = url.getProtocol();
final String host = url.getHost();
if(protocol.equals(FILE_PROTOCOL) && (host == null || host.length() == 0 || "localhost".equals(host) || "127.0.0.1".equals(host)))
{
final String path = url.getFile();
return new XACMLSource(XACMLConstants.FILE_SOURCE_TYPE, path);
}
final String key = url.toExternalForm();
final String type = (source instanceof ClassLoaderSource) ? XACMLConstants.CLASSLOADER_SOURCE_TYPE : XACMLConstants.URL_SOURCE_TYPE;
return new XACMLSource(type, key);
}
if(source instanceof StringSource || source instanceof StringSourceWithMapKey)
{return new XACMLSource(XACMLConstants.STRING_SOURCE_TYPE, XACMLConstants.STRING_SOURCE_TYPE);}
// Cocoon classes are not on classpath during compile time.
Class<?> class1;
try {
class1 = Class.forName("org.exist.source.CocoonSource");
final Method method1 = class1.getMethod("getInstance", org.exist.source.Source.class);
final Object o1 = method1.invoke(null, source);
final Method method2 = class1.getMethod("getKey", (java.lang.Class<?>[]) null);
final Object o2 = method2.invoke(o1, (Object[])null);
final String key = (String) o2;
System.out.println("Found CocoonSource with key "+key);
return new XACMLSource(XACMLConstants.COCOON_SOURCE_TYPE, key);
} catch (final Exception e) {
// just continue
}
if(source instanceof DBSource)
{
final XmldbURI key = ((DBSource)source).getDocumentPath();
/*
* TODO: not sure what implications using toString here has, when the key
* is really an XmldbURI?
*/
return new XACMLSource(XACMLConstants.DB_SOURCE_TYPE, key.toString());
}
throw new IllegalArgumentException("Unsupported source type '" + source.getClass().getName() + "'");
}
public String getType()
{
return type;
}
public String getKey()
{
return key;
}
public String createId()
{
return type.equals(XACMLConstants.STRING_SOURCE_TYPE) ? "[constructed]" : (type + ": '" + key + "'");
}
public String toString() {
return type+": "+key;
}
}
| lgpl-2.1 |
Jaapp-/app-to-app-communicator | app/src/test/java/org/tribler/app_to_appcommunicator/ExampleUnitTest.java | 327 | package org.tribler.app_to_appcommunicator;
import org.junit.Test;
import static org.junit.Assert.*;
/**
* To work on unit tests, switch the Test Artifact in the Build Variants view.
*/
public class ExampleUnitTest {
@Test
public void addition_isCorrect() throws Exception {
assertEquals(4, 2 + 2);
}
} | lgpl-2.1 |
concord-consortium/otrunk | src/java/org/concord/otrunk/OTrunkServiceEntry.java | 276 | /**
*
*/
package org.concord.otrunk;
public class OTrunkServiceEntry<T>
{
public T service;
public Class<T> serviceInterface;
public OTrunkServiceEntry(T service, Class<T> serviceInterface)
{
this.service = service;
this.serviceInterface = serviceInterface;
}
} | lgpl-2.1 |
soultek101/projectzulu1.7.10 | src/main/java/com/stek101/projectzulu/common/world2/blueprint/BPSetPyramidEdge.java | 9612 | package com.stek101.projectzulu.common.world2.blueprint;
import java.awt.Point;
import java.util.Random;
import net.minecraft.init.Blocks;
import net.minecraft.util.ChunkCoordinates;
import com.stek101.projectzulu.common.world.CellIndexDirection;
import com.stek101.projectzulu.common.world.dataobjects.BlockWithMeta;
import com.stek101.projectzulu.common.world2.MazeCell;
public class BPSetPyramidEdge implements BlueprintSet {
final OuterEdge outerWall = new OuterEdge();
final InnerEdge innerWall = new InnerEdge();
@Override
public boolean assignCellsWithBlueprints(MazeCell[][] cells, Point buildCoords, Random random) {
String buildName = getIdentifier();
if (buildCoords.x == 0 || buildCoords.y == 0 || buildCoords.x == cells.length - 1
|| buildCoords.y == cells[0].length - 1) {
buildName = buildName.concat("-").concat(outerWall.getIdentifier());
} else {
buildName = buildName.concat("-").concat(innerWall.getIdentifier());
}
cells[buildCoords.x][buildCoords.y].setBuildingProperties(buildName, getDirection(cells, buildCoords));
cells[buildCoords.x][buildCoords.y].rawState = -1;
return true;
}
private CellIndexDirection getDirection(MazeCell[][] cells, Point buildCoords) {
if (buildCoords.x == 0 && buildCoords.y == 0 || buildCoords.x == 1 && buildCoords.y == 1) {
return CellIndexDirection.NorthWestCorner;
} else if (buildCoords.x == cells.length - 1 && buildCoords.y == 0 || buildCoords.x == cells.length - 2
&& buildCoords.y == 1) {
return CellIndexDirection.NorthEastCorner;
} else if (buildCoords.x == 0 && buildCoords.y == cells[0].length - 1 || buildCoords.x == 1
&& buildCoords.y == cells[0].length - 2) {
return CellIndexDirection.SouthWestCorner;
} else if (buildCoords.x == cells.length - 1 && buildCoords.y == cells[0].length - 1
|| buildCoords.x == cells.length - 2 && buildCoords.y == cells[0].length - 2) {
return CellIndexDirection.SouthEastCorner;
}
if (buildCoords.x == 0) {
return CellIndexDirection.WestWall;
} else if (buildCoords.x == cells.length - 1) {
return CellIndexDirection.EastWall;
} else if (buildCoords.y == 0) {
return CellIndexDirection.NorthWall;
} else if (buildCoords.y == cells[0].length - 1) {
return CellIndexDirection.SouthWall;
}
if (buildCoords.x == 1) {
return CellIndexDirection.WestWall;
} else if (buildCoords.x == cells.length - 2) {
return CellIndexDirection.EastWall;
} else if (buildCoords.y == 1) {
return CellIndexDirection.NorthWall;
} else if (buildCoords.y == cells[0].length - 2) {
return CellIndexDirection.SouthWall;
}
if (buildCoords.x <= 1) {
return CellIndexDirection.WestWall;
} else if (buildCoords.x >= cells.length - 2) {
return CellIndexDirection.EastWall;
}
if (buildCoords.y <= 1) {
return CellIndexDirection.NorthWall;
} else if (buildCoords.y >= cells[0].length - 2) {
return CellIndexDirection.SouthWall;
}
return null;
}
@Override
public BlockWithMeta getBlockFromBlueprint(ChunkCoordinates piecePos, int cellSize, int cellHeight,
CellIndexDirection cellIndexDirection, Random random, String buildingID) {
String blueprintID = buildingID.split("-")[1];
if (blueprintID.equals(outerWall.getIdentifier())) {
return outerWall.getBlockFromBlueprint(piecePos, cellSize, cellHeight, random, cellIndexDirection);
} else if (blueprintID.equals(innerWall.getIdentifier())) {
return innerWall.getBlockFromBlueprint(piecePos, cellSize, cellHeight, random, cellIndexDirection);
}
throw new IllegalArgumentException("Blueprint ID parsed from " + buildingID + " does not exist.");
}
@Override
public boolean isApplicable(MazeCell[][] cells, Point buildCoords, Random random) {
if (buildCoords.x <= 1 || buildCoords.y <= 1 || buildCoords.x >= cells.length - 2
|| buildCoords.y >= cells[0].length - 2) {
return cells[buildCoords.x][buildCoords.y].rawState >= 0;
}
return false;
}
@Override
public String getIdentifier() {
return "PyramidEdge";
}
@Override
public int getWeight() {
return 0;
}
private class OuterEdge implements Blueprint {
@Override
public BlockWithMeta getBlockFromBlueprint(ChunkCoordinates piecePos, int cellSize, int cellHeight,
Random random, CellIndexDirection cellIndexDirection) {
int index = 0;
if (cellIndexDirection.isCorner()) {
int posX = piecePos.posX;
if (cellIndexDirection != CellIndexDirection.NorthWestCorner
&& cellIndexDirection != CellIndexDirection.SouthWestCorner) {
posX = (cellSize - 1) - piecePos.posX;
}
int posZ = piecePos.posZ;
if (cellIndexDirection != CellIndexDirection.NorthWestCorner
&& cellIndexDirection != CellIndexDirection.NorthEastCorner) {
posZ = (cellSize - 1) - piecePos.posZ;
}
if (piecePos.posY > posZ + index * cellSize || piecePos.posY > posX + index * cellSize) {
return new BlockWithMeta(Blocks.air);
} else if (piecePos.posY == posZ + index * cellSize || piecePos.posY == posX + index * cellSize) {
return new BlockWithMeta(Blocks.sandstone);
}
} else {
int pos = -1;
switch (cellIndexDirection) {
case NorthWall:
pos = piecePos.posZ;
break;
case SouthWall:
pos = (cellSize - 1) - piecePos.posZ;
break;
case WestWall:
pos = piecePos.posX;
break;
case EastWall:
pos = (cellSize - 1) - piecePos.posX;
break;
default:
pos = -1;
break;
}
if (pos > -1) {
if (piecePos.posY > pos + index * cellSize) {
return new BlockWithMeta(Blocks.air);
} else if (piecePos.posY == pos + index * cellSize) {
return new BlockWithMeta(Blocks.sandstone);
}
}
}
return new BlockWithMeta(Blocks.sandstone);
}
@Override
public int getWeight() {
return 1;
}
@Override
public String getIdentifier() {
return "OuterWall";
}
}
private class InnerEdge implements Blueprint {
@Override
public BlockWithMeta getBlockFromBlueprint(ChunkCoordinates piecePos, int cellSize, int cellHeight,
Random random, CellIndexDirection cellIndexDirection) {
int index = 1;
if (cellIndexDirection.isCorner()) {
int posX = piecePos.posX;
if (cellIndexDirection != CellIndexDirection.NorthWestCorner
&& cellIndexDirection != CellIndexDirection.SouthWestCorner) {
posX = (cellSize - 1) - piecePos.posX;
}
int posZ = piecePos.posZ;
if (cellIndexDirection != CellIndexDirection.NorthWestCorner
&& cellIndexDirection != CellIndexDirection.NorthEastCorner) {
posZ = (cellSize - 1) - piecePos.posZ;
}
if (piecePos.posY > posZ + index * cellSize || piecePos.posY > posX + index * cellSize) {
return new BlockWithMeta(Blocks.air);
} else if (piecePos.posY == posZ + index * cellSize || piecePos.posY == posX + index * cellSize) {
return new BlockWithMeta(Blocks.sandstone);
}
} else {
int pos = -1;
switch (cellIndexDirection) {
case NorthWall:
pos = piecePos.posZ;
break;
case SouthWall:
pos = (cellSize - 1) - piecePos.posZ;
break;
case WestWall:
pos = piecePos.posX;
break;
case EastWall:
pos = (cellSize - 1) - piecePos.posX;
break;
default:
pos = -1;
break;
}
if (pos > -1) {
if (piecePos.posY > pos + index * cellSize) {
return new BlockWithMeta(Blocks.air);
} else if (piecePos.posY == pos + index * cellSize) {
return new BlockWithMeta(Blocks.sandstone);
}
}
}
return new BlockWithMeta(Blocks.sandstone);
}
@Override
public int getWeight() {
return 1;
}
@Override
public String getIdentifier() {
return "InnerWall";
}
}
}
| lgpl-2.1 |
deegree/deegree3 | deegree-datastores/deegree-tilestores/deegree-tilestore-merge/src/main/java/org/deegree/tile/persistence/merge/MergingTile.java | 5107 | /*----------------------------------------------------------------------------
This file is part of deegree
Copyright (C) 2001-2013 by:
- Department of Geography, University of Bonn -
and
- lat/lon GmbH -
and
- Occam Labs UG (haftungsbeschränkt) -
and others
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
Contact information:
e-mail: info@deegree.org
website: http://www.deegree.org/
----------------------------------------------------------------------------*/
package org.deegree.tile.persistence.merge;
import static java.awt.Color.WHITE;
import static java.awt.image.BufferedImage.TYPE_3BYTE_BGR;
import java.awt.Color;
import java.awt.Graphics;
import java.awt.Image;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.awt.image.FilteredImageSource;
import java.awt.image.ImageFilter;
import java.awt.image.ImageProducer;
import java.awt.image.RGBImageFilter;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.util.List;
import javax.imageio.ImageIO;
import org.deegree.feature.FeatureCollection;
import org.deegree.geometry.Envelope;
import org.deegree.tile.Tile;
import org.deegree.tile.TileIOException;
/**
* {@link Tile} implementation used by {@link MergingTileStore}.
*
* @author <a href="mailto:Reijer.Copier@idgis.nl">Reijer Copier</a>
* @author <a href="mailto:schneider@occamlabs.de">Markus Schneider</a>
*
* @since 3.4
*/
class MergingTile implements Tile {
private final List<Tile> tiles;
MergingTile( final List<Tile> tiles ) {
this.tiles = tiles;
}
@Override
public BufferedImage getAsImage()
throws TileIOException {
Iterator<Tile> itr = tiles.iterator();
Tile firstTile = itr.next();
BufferedImage img = firstTile.getAsImage();
Graphics g = img.getGraphics();
while ( itr.hasNext() ) {
Tile nextTile = itr.next();
BufferedImage nextImage = nextTile.getAsImage();
if ( nextImage.getColorModel().hasAlpha() ) {
g.drawImage( nextImage, 0, 0, null );
} else {
g.drawImage( makeColorTranslucent( nextImage, WHITE ), 0, 0, null );
}
}
return img;
}
private Image makeColorTranslucent( final BufferedImage image, final Color translucentColor ) {
final int transparentRgb = translucentColor.getRGB();
final ImageFilter filter = new RGBImageFilter() {
public final int filterRGB( final int x, final int y, final int rgb ) {
if ( rgb == transparentRgb ) {
return Color.TRANSLUCENT;
}
return rgb;
}
};
final ImageProducer ip = new FilteredImageSource( image.getSource(), filter );
return Toolkit.getDefaultToolkit().createImage( ip );
}
@Override
public InputStream getAsStream()
throws TileIOException {
ByteArrayOutputStream output = new ByteArrayOutputStream();
try {
BufferedImage img = getAsImage();
if ( img.getTransparency() != BufferedImage.OPAQUE ) {
final int width = img.getWidth();
final int height = img.getHeight();
BufferedImage noTransparency = new BufferedImage( width, height, TYPE_3BYTE_BGR );
Graphics g = noTransparency.getGraphics();
g.setColor( Color.WHITE );
g.fillRect( 0, 0, width, height );
g.drawImage( img, 0, 0, null );
img = noTransparency;
}
ImageIO.write( img, "jpeg", output );
} catch ( IOException e ) {
throw new TileIOException( e );
}
return new ByteArrayInputStream( output.toByteArray() );
}
@Override
public Envelope getEnvelope() {
return tiles.get( 0 ).getEnvelope();
}
@Override
public FeatureCollection getFeatures( int i, int j, int limit )
throws UnsupportedOperationException {
throw new UnsupportedOperationException( "MergingTile does not support getFeatures" );
}
}
| lgpl-2.1 |
codelibs/jcifs | src/test/java/jcifs/tests/ConcurrencyTest.java | 18054 | /*
* © 2016 AgNO3 Gmbh & Co. KG
*
* 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 jcifs.tests;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertTrue;
import static org.junit.Assert.fail;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.net.MalformedURLException;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicInteger;
import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.Parameterized;
import org.junit.runners.Parameterized.Parameters;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import jcifs.CIFSContext;
import jcifs.SmbConstants;
import jcifs.SmbResource;
import jcifs.SmbSession;
import jcifs.internal.smb2.Smb2Constants;
import jcifs.internal.smb2.create.Smb2CloseRequest;
import jcifs.internal.smb2.create.Smb2CreateRequest;
import jcifs.smb.NtStatus;
import jcifs.smb.SmbException;
import jcifs.smb.SmbFile;
import jcifs.smb.SmbFileOutputStream;
import jcifs.smb.SmbSessionInternal;
import jcifs.smb.SmbTransportInternal;
import jcifs.smb.SmbTreeInternal;
import jcifs.util.transport.TransportException;
/**
* @author mbechler
*
*/
@RunWith ( Parameterized.class )
@SuppressWarnings ( "javadoc" )
public class ConcurrencyTest extends BaseCIFSTest {
static final Logger log = LoggerFactory.getLogger(ConcurrencyTest.class);
private ExecutorService executor;
public ConcurrencyTest ( String name, Map<String, String> properties ) {
super(name, properties);
}
@Parameters ( name = "{0}" )
public static Collection<Object> configs () {
return getConfigs("smb1", "noNTStatus", "noNTSmbs", "smb2", "smb30", "smb31");
}
@Override
@Before
public void setUp () throws Exception {
super.setUp();
this.executor = Executors.newCachedThreadPool();
}
@After
@Override
public void tearDown () throws Exception {
this.executor.shutdown();
this.executor.awaitTermination(10, TimeUnit.SECONDS);
super.tearDown();
}
@Test
public void testExclusiveLock () throws InterruptedException, MalformedURLException, UnknownHostException {
String fname = makeRandomName();
try ( SmbFile sr = getDefaultShareRoot();
SmbResource exclFile = new SmbFile(sr, fname) ) {
ExclusiveLockFirst f = new ExclusiveLockFirst(exclFile);
ExclusiveLockSecond s = new ExclusiveLockSecond(f, exclFile);
List<MultiTestCase> runnables = new ArrayList<>();
runnables.add(f);
runnables.add(s);
runMultiTestCase(runnables, 10);
}
}
@Test
public void testDeleteLocked () throws IOException {
String fname = makeRandomName();
try ( SmbFile sr = getDefaultShareRoot();
SmbResource exclFile = new SmbFile(sr, fname) ) {
try ( OutputStream s = exclFile.openOutputStream(false, SmbConstants.FILE_NO_SHARE) ) {
try {
exclFile.delete();
fail("Could remove locked file");
}
catch ( SmbException e ) {
if ( e.getNtStatus() == NtStatus.NT_STATUS_SHARING_VIOLATION ) {
return;
}
throw e;
}
}
finally {
exclFile.delete();
}
}
}
@Test
public void testOpenLocked () throws IOException {
String fname = makeRandomName();
try ( SmbFile sr = getDefaultShareRoot();
SmbResource exclFile = new SmbFile(sr, fname) ) {
try ( OutputStream s = exclFile.openOutputStream(false, SmbConstants.FILE_NO_SHARE);
InputStream is = exclFile.openInputStream(SmbConstants.FILE_NO_SHARE) ) {
fail("No sharing violation");
}
catch ( SmbException e ) {
if ( e.getNtStatus() == NtStatus.NT_STATUS_SHARING_VIOLATION ) {
return;
}
throw e;
}
finally {
exclFile.delete();
}
}
}
@Test
public void testOpenReadLocked () throws IOException {
String fname = makeRandomName();
try ( SmbFile sr = getDefaultShareRoot();
SmbResource exclFile = new SmbFile(sr, fname) ) {
exclFile.createNewFile();
try {
try ( InputStream is = exclFile.openInputStream(SmbConstants.FILE_NO_SHARE);
InputStream is2 = exclFile.openInputStream(SmbConstants.FILE_NO_SHARE) ) {
fail("No sharing violation");
}
catch ( SmbException e ) {
if ( e.getNtStatus() == NtStatus.NT_STATUS_SHARING_VIOLATION ) {
return;
}
throw e;
}
}
finally {
exclFile.delete();
}
}
}
private class ExclusiveLockFirst extends MultiTestCase {
private Object startedLock = new Object();
private volatile boolean started;
private Object shutdownLock = new Object();
private volatile boolean shutdown;
private SmbResource file;
/**
* @param smbFile
*
*/
public ExclusiveLockFirst ( SmbResource smbFile ) {
this.file = smbFile;
}
public void waitForStart () throws InterruptedException {
synchronized ( this.startedLock ) {
while ( !this.started ) {
this.startedLock.wait();
}
}
}
public void shutdown () {
this.shutdown = true;
synchronized ( this.shutdownLock ) {
this.shutdownLock.notify();
}
}
/**
* {@inheritDoc}
*
* @see java.lang.Runnable#run()
*/
@Override
public void run () {
try {
SmbResource f = this.file;
f.createNewFile();
try {
try ( OutputStream os = f.openOutputStream(false, SmbConstants.FILE_NO_SHARE) ) {
log.debug("Open1");
synchronized ( this.startedLock ) {
this.started = true;
this.startedLock.notify();
}
while ( !this.shutdown ) {
synchronized ( this.shutdownLock ) {
this.shutdownLock.wait();
}
}
}
catch ( InterruptedException e ) {
log.debug("Interrupted1", e);
}
log.debug("Closed1");
this.completed = true;
}
finally {
f.delete();
}
}
catch ( Exception e ) {
log.error("Test case failed", e);
}
}
}
@Test
public void testInterrupt () throws UnknownHostException, IOException, InterruptedException {
final Object lock = new Object();
final Thread t = Thread.currentThread();
this.executor.submit(new Runnable() {
@Override
public void run () {
try {
synchronized ( lock ) {
lock.wait(1000);
}
Thread.sleep(100);
t.interrupt();
}
catch ( InterruptedException e ) {
e.printStackTrace();
}
}
});
try {
CIFSContext c = getContext();
c = withTestNTLMCredentials(c);
try ( SmbTransportInternal trans = c.getTransportPool().getSmbTransport(c, getTestServer(), 0, false, true)
.unwrap(SmbTransportInternal.class);
SmbSession sess = trans.unwrap(SmbTransportInternal.class).getSmbSession(c, getTestServer(), null);
SmbTreeInternal tree = sess.unwrap(SmbSessionInternal.class).getSmbTree(getTestShare(), null).unwrap(SmbTreeInternal.class) ) {
if ( trans.isSMB2() ) {
Smb2CreateRequest create = new Smb2CreateRequest(sess.getConfig(), "\\foocc");
create.setCreateDisposition(Smb2CreateRequest.FILE_OPEN_IF);
create.setRequestedOplockLevel(Smb2CreateRequest.SMB2_OPLOCK_LEVEL_BATCH);
try {
tree.send(create);
Smb2CreateRequest create2 = new Smb2CreateRequest(sess.getConfig(), "\\foocc");
create2.setOverrideTimeout(1000);
create2.setCreateDisposition(Smb2CreateRequest.FILE_OPEN_IF);
create2.setRequestedOplockLevel(Smb2CreateRequest.SMB2_OPLOCK_LEVEL_BATCH);
create2.chain(new Smb2CloseRequest(sess.getConfig(), Smb2Constants.UNSPECIFIED_FILEID));
synchronized ( lock ) {
lock.notify();
}
tree.send(create2);
}
catch ( Exception e ) {
if ( e.getCause() instanceof TransportException && e.getCause().getCause() instanceof InterruptedException ) {
Smb2CreateRequest create3 = new Smb2CreateRequest(sess.getConfig(), "\\xyz");
create3.setOverrideTimeout(1000);
create3.setCreateDisposition(Smb2CreateRequest.FILE_OPEN_IF);
create3.chain(new Smb2CloseRequest(sess.getConfig(), Smb2Constants.UNSPECIFIED_FILEID));
}
else {
e.printStackTrace();
fail("Failed to interrupt sendrecv");
}
}
}
}
}
finally {
this.executor.shutdown();
this.executor.awaitTermination(5, TimeUnit.SECONDS);
}
}
private class ExclusiveLockSecond extends MultiTestCase {
private ExclusiveLockFirst first;
private SmbResource file;
/**
* @param f
* @param smbFile
*/
public ExclusiveLockSecond ( ExclusiveLockFirst f, SmbResource smbFile ) {
this.first = f;
this.file = smbFile;
}
/**
* {@inheritDoc}
*
* @see java.lang.Runnable#run()
*/
@Override
public void run () {
try {
SmbResource f = this.file;
this.first.waitForStart();
try ( OutputStream os = f.openOutputStream(false, SmbConstants.FILE_NO_SHARE) ) {
log.debug("Open2");
}
catch ( IOException e ) {
if ( e instanceof SmbException && ( (SmbException) e ).getNtStatus() == NtStatus.NT_STATUS_SHARING_VIOLATION ) {
this.completed = true;
return;
}
throw e;
}
finally {
this.first.shutdown();
}
}
catch ( Exception e ) {
log.error("Test case failed", e);
}
}
}
@Test
public void lockedWrites () throws InterruptedException, IOException {
int n = 45;
String fname = makeRandomName();
try ( SmbFile sr = getDefaultShareRoot();
SmbResource f = new SmbFile(sr, fname) ) {
try {
f.createNewFile();
final AtomicInteger failCount = new AtomicInteger();
final AtomicInteger writeCount = new AtomicInteger();
List<MultiTestCase> runnables = new ArrayList<>();
for ( int i = 0; i < n; i++ ) {
runnables.add(new LockedWritesTest(failCount, writeCount, new SmbFile(sr, fname)));
}
runMultiTestCase(runnables, 60);
int readCnt = 0;
try ( InputStream is = f.openInputStream(SmbConstants.FILE_NO_SHARE) ) {
while ( is.read() >= 0 ) {
readCnt++;
}
}
if ( log.isDebugEnabled() ) {
log.debug("Failures " + failCount.get() + " wrote " + writeCount.get() + " read " + readCnt);
}
assertEquals("Read less than we wrote", writeCount.get(), readCnt);
assertEquals(n, failCount.get() + writeCount.get());
}
finally {
f.delete();
}
}
}
private static class LockedWritesTest extends MultiTestCase {
private final AtomicInteger failCount;
private final SmbFile file;
private AtomicInteger writeCount;
/**
* @param failCount
* @param smbFile
*/
public LockedWritesTest ( AtomicInteger failCount, AtomicInteger writeCount, SmbFile smbFile ) {
this.failCount = failCount;
this.writeCount = writeCount;
this.file = smbFile;
}
/**
* {@inheritDoc}
*
* @see java.lang.Runnable#run()
*/
@Override
public void run () {
try ( SmbFileOutputStream out = this.file.openOutputStream(true, SmbConstants.FILE_NO_SHARE) ) {
out.write(0xAA);
this.writeCount.incrementAndGet();
this.completed = true;
}
catch ( IOException e ) {
if ( e instanceof SmbException && ( (SmbException) e ).getNtStatus() == NtStatus.NT_STATUS_SHARING_VIOLATION ) {
this.failCount.incrementAndGet();
this.completed = true;
return;
}
log.error("Unexpected error", e);
}
finally {
try {
this.file.close();
}
catch ( Exception e ) {
log.error("Failed to close");
}
}
}
}
@Test
public void testMultiThread () throws InterruptedException {
withTestNTLMCredentials(getContext());
List<MutiThreadTestCase> runnables = new ArrayList<>();
for ( int i = 0; i < 20; i++ ) {
runnables.add(new MutiThreadTestCase());
}
runMultiTestCase(runnables, 60);
}
private void runMultiTestCase ( List<? extends MultiTestCase> testcases, int timeoutSecs ) throws InterruptedException {
for ( Runnable r : testcases ) {
this.executor.submit(r);
}
this.executor.shutdown();
this.executor.awaitTermination(timeoutSecs, TimeUnit.SECONDS);
for ( MultiTestCase r : testcases ) {
assertTrue("Have not completed", r.completed);
}
}
private static abstract class MultiTestCase implements Runnable {
public MultiTestCase () {}
boolean completed;
}
private class MutiThreadTestCase extends MultiTestCase {
public MutiThreadTestCase () {}
@Override
public void run () {
try {
try ( SmbResource f = createTestFile() ) {
try {
// f.exists();
// try ( OutputStream os = f.openOutputStream(false, SmbConstants.FILE_NO_SHARE) ) {
// os.write(new byte[] {
// 1, 2, 3, 4, 5, 6, 7, 8
// });
// }
//
// try ( InputStream is = f.openInputStream(SmbConstants.FILE_NO_SHARE) ) {
// byte data[] = new byte[8];
// is.read(data);
// }
}
finally {
try {
f.delete();
}
catch ( IOException e ) {
System.err.println(f.getLocator().getUNCPath());
throw e;
}
}
}
this.completed = true;
}
catch (
IOException |
RuntimeException e ) {
log.error("Test case failed", e);
}
}
}
}
| lgpl-2.1 |
Pigatto17/BlockItem-Plus | src/main/java/com/pigatto17/blockitemplus/item/ItemCoalMixture.java | 327 | package com.pigatto17.blockitemplus.item;
import com.pigatto17.blockitemplus.creativetab.CreativeTabBIPItems;
public class ItemCoalMixture extends ItemBIP
{
public ItemCoalMixture()
{
super();
this.setUnlocalizedName("coalMixture");
this.setCreativeTab(CreativeTabBIPItems.BIP_ITEMS);
}
}
| lgpl-2.1 |
wolfc/jboss-common-beans | src/test/java/org/jboss/common/beans/property/LongEditorTestCase.java | 1769 | /*
* 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;
/**
* @author baranowb
*
*/
public class LongEditorTestCase extends PropertyEditorTester<Long> {
@Override
public String[] getInputData() {
return new String[] { "1", "-1", "0", "1000" };
}
@Override
public Object[] getOutputData() {
return new Object[] { Long.valueOf("1"), Long.valueOf("-1"), Long.valueOf("0"), Long.valueOf("1000") };
}
@Override
public String[] getConvertedToText() {
return new String[] { "1", "-1", "0", "1000" };
}
@Override
public Comparator<Long> getComparator() {
return null;
}
@Override
public Class getType() {
return Long.TYPE;
}
}
| lgpl-2.1 |
nybbs2003/jopenmetaverse | src/main/java/com/ngt/jopenmetaverse/shared/structureddata/OSDFormat.java | 1160 | /**
* 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.structureddata;
public enum OSDFormat
{
Xml (0),
Json (1),
Binary (2);
private int index;
OSDFormat(int index)
{
this.index = index;
}
public int getIndex()
{
return index;
}
} | lgpl-2.1 |
alkacon/opencms-core | src/org/opencms/widgets/A_CmsHtmlWidget.java | 3651 | /*
* This library is part of OpenCms -
* the Open Source Content Management System
*
* Copyright (c) Alkacon Software GmbH & Co. KG (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 GmbH & Co. KG, 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.widgets;
import org.opencms.file.CmsObject;
import org.opencms.i18n.CmsEncoder;
import org.opencms.util.CmsMacroResolver;
import java.util.Map;
/**
* Provides a widget that creates a rich input field using the matching component, for use on a widget dialog.<p>
*
* The matching component is determined by checking the installed editors for the best matching component to use.<p>
*
* @since 6.0.1
*/
public abstract class A_CmsHtmlWidget extends A_CmsWidget {
/**
* Creates a new html editing widget.<p>
*/
public A_CmsHtmlWidget() {
// empty constructor is required for class registration
super();
}
/**
* Creates a new html editing widget with the given configuration.<p>
*
* @param configuration the configuration to use
*/
public A_CmsHtmlWidget(String configuration) {
super(configuration);
}
/**
* @see org.opencms.widgets.A_CmsWidget#getConfiguration()
*/
@Override
public String getConfiguration() {
return super.getConfiguration();
}
/**
* Creates a CmsHtmlWidgetOption instance from the configuration string.
*
* @param cms the current CMS context
* @return the parsed option bean
*/
public CmsHtmlWidgetOption parseWidgetOptions(CmsObject cms) {
String configStr = getConfiguration();
if (cms != null) {
CmsMacroResolver resolver = new CmsMacroResolver();
resolver.setCmsObject(cms);
configStr = resolver.resolveMacros(configStr);
}
return new CmsHtmlWidgetOption(configStr);
}
/**
* @see org.opencms.widgets.I_CmsWidget#setConfiguration(java.lang.String)
*/
@Override
public void setConfiguration(String configuration) {
super.setConfiguration(configuration);
}
/**
* @see org.opencms.widgets.I_CmsWidget#setEditorValue(org.opencms.file.CmsObject, java.util.Map, org.opencms.widgets.I_CmsWidgetDialog, org.opencms.widgets.I_CmsWidgetParameter)
*/
@Override
public void setEditorValue(
CmsObject cms,
Map<String, String[]> formParameters,
I_CmsWidgetDialog widgetDialog,
I_CmsWidgetParameter param) {
String[] values = formParameters.get(param.getId());
if ((values != null) && (values.length > 0)) {
String val = CmsEncoder.decode(values[0], CmsEncoder.ENCODING_UTF_8);
param.setStringValue(cms, val);
}
}
} | lgpl-2.1 |
GrammaticalFramework/JPGF | src/org/grammaticalframework/reader/CncFun.java | 2139 | /* CncFun.java
* Copyright (C) 2010 Grégoire Détrez, Ramona Enache
*
* 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 org.grammaticalframework.reader;
public class CncFun {
private String name;
private Sequence[] sequences;
public CncFun(String _name, Sequence[] seqs)
{
name = _name;
this.sequences = seqs;
}
/**
* Accessors
*/
public String name() {
return this.name;
}
public Sequence[] sequences() {
return this.sequences;
}
public Sequence sequence(int index) {
return this.sequences[index];
}
public Symbol symbol(int seqIndex, int symbIndex) {
return this.sequences[seqIndex].symbol(symbIndex);
}
public int size() {
return this.sequences.length;
}
public String toString()
{
String ss = "Name : "+name + " , Indices : ";
for(int i=0; i < sequences.length; i++)
ss+=(" " + sequences[i]);
return ss;
}
// *************
// private String name;
// private int[] inds;
// public CncFun(String _name, int[] _inds)
// {name = _name;
// inds = _inds;
// }
// public String toString()
// {String ss = "Name : "+name + " , Indices : ";
// for(int i=0; i<inds.length; i++)
// ss+=(" "+inds[i]);
// return ss;
// }
// public String getName(){return name;}
// public int[] getInds(){return inds;}
// ^ ^ ^ ^ ^ ^ ^
}
| lgpl-2.1 |
geotools/geotools | modules/extension/xsd/xsd-core/src/main/java/org/geotools/xs/bindings/XSDerivationSetBinding.java | 2879 | /*
* GeoTools - The Open Source Java GIS Toolkit
* http://geotools.org
*
* (C) 2002-2008, 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.xs.bindings;
import javax.xml.namespace.QName;
import org.geotools.xs.XS;
import org.geotools.xsd.InstanceComponent;
import org.geotools.xsd.SimpleBinding;
/**
* Binding object for the type http://www.w3.org/2001/XMLSchema:derivationSet.
*
* <p>
*
* <pre>
* <code>
* <xs:simpleType name="derivationSet">
* <xs:annotation>
* <xs:documentation> A utility type, not for public use</xs:documentation>
* <xs:documentation> #all or (possibly empty) subset of
* {extension, restriction}</xs:documentation>
* </xs:annotation>
* <xs:union>
* <xs:simpleType>
* <xs:restriction base="xs:token">
* <xs:enumeration value="#all"/>
* </xs:restriction>
* </xs:simpleType>
* <xs:simpleType>
* <xs:list itemType="xs:reducedDerivationControl"/>
* </xs:simpleType>
* </xs:union>
* </xs:simpleType>
*
* </code>
* </pre>
*
* @generated
*/
public class XSDerivationSetBinding implements SimpleBinding {
/** @generated */
@Override
public QName getTarget() {
return XS.DERIVATIONSET;
}
/**
*
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated modifiable
*/
@Override
public int getExecutionMode() {
return AFTER;
}
/**
*
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated modifiable
*/
@Override
public Class getType() {
return null;
}
/**
*
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated modifiable
*/
@Override
public Object parse(InstanceComponent instance, Object value) throws Exception {
// TODO: implement me
return null;
}
/**
*
* <!-- begin-user-doc -->
* <!-- end-user-doc -->
*
* @generated modifiable
*/
@Override
public String encode(Object object, String value) {
// TODO: implement
return null;
}
}
| lgpl-2.1 |
myrridin/qz-print | pdfbox_1.8.4_qz/src/org/apache/pdfbox/pdmodel/interactive/documentnavigation/outline/PDDocumentOutline.java | 1490 | /*
* Licensed to the Apache Software Foundation (ASF) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* The ASF licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.apache.pdfbox.pdmodel.interactive.documentnavigation.outline;
import org.apache.pdfbox.cos.COSDictionary;
/**
* This represents an outline in a pdf document.
*
* @author <a href="mailto:ben@benlitchfield.com">Ben Litchfield</a>
* @version $Revision: 1.2 $
*/
public class PDDocumentOutline extends PDOutlineNode
{
/**
* Default Constructor.
*/
public PDDocumentOutline()
{
super();
node.setName( "Type", "Outlines" );
}
/**
* Constructor for an existing document outline.
*
* @param dic The storage dictionary.
*/
public PDDocumentOutline( COSDictionary dic )
{
super( dic );
}
}
| lgpl-2.1 |
agwe/jolie | jolie/src/jolie/OOITBuilder.java | 56497 | /*
* Copyright (C) 2006-2016 Fabrizio Montesi <famontesi@gmail.com>
*
* This library is free software; you can redistribute it and/or
* modify it under the terms of the GNU Lesser General Public
* License as published by the Free Software Foundation; either
* version 2.1 of the License, or (at your option) any later version.
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this library; if not, write to the Free Software
* Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
* MA 02110-1301 USA
*/
package jolie;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Deque;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Objects;
import java.util.Set;
import java.util.function.BiPredicate;
import jolie.lang.Constants;
import jolie.lang.Constants.ExecutionMode;
import jolie.lang.Constants.OperandType;
import jolie.lang.parse.CorrelationFunctionInfo;
import jolie.lang.parse.CorrelationFunctionInfo.CorrelationPairInfo;
import jolie.lang.parse.OLParser;
import jolie.lang.parse.OLVisitor;
import jolie.lang.parse.Scanner;
import jolie.lang.parse.ast.AddAssignStatement;
import jolie.lang.parse.ast.AssignStatement;
import jolie.lang.parse.ast.CompareConditionNode;
import jolie.lang.parse.ast.CompensateStatement;
import jolie.lang.parse.ast.CorrelationSetInfo;
import jolie.lang.parse.ast.CorrelationSetInfo.CorrelationVariableInfo;
import jolie.lang.parse.ast.CurrentHandlerStatement;
import jolie.lang.parse.ast.DeepCopyStatement;
import jolie.lang.parse.ast.DefinitionCallStatement;
import jolie.lang.parse.ast.DefinitionNode;
import jolie.lang.parse.ast.DivideAssignStatement;
import jolie.lang.parse.ast.DocumentationComment;
import jolie.lang.parse.ast.EmbeddedServiceNode;
import jolie.lang.parse.ast.ExecutionInfo;
import jolie.lang.parse.ast.ExitStatement;
import jolie.lang.parse.ast.ForEachArrayItemStatement;
import jolie.lang.parse.ast.ForEachSubNodeStatement;
import jolie.lang.parse.ast.ForStatement;
import jolie.lang.parse.ast.IfStatement;
import jolie.lang.parse.ast.InputPortInfo;
import jolie.lang.parse.ast.InstallFixedVariableExpressionNode;
import jolie.lang.parse.ast.InstallFunctionNode;
import jolie.lang.parse.ast.InstallStatement;
import jolie.lang.parse.ast.InterfaceDefinition;
import jolie.lang.parse.ast.InterfaceExtenderDefinition;
import jolie.lang.parse.ast.LinkInStatement;
import jolie.lang.parse.ast.LinkOutStatement;
import jolie.lang.parse.ast.MultiplyAssignStatement;
import jolie.lang.parse.ast.NDChoiceStatement;
import jolie.lang.parse.ast.NotificationOperationStatement;
import jolie.lang.parse.ast.NullProcessStatement;
import jolie.lang.parse.ast.OLSyntaxNode;
import jolie.lang.parse.ast.OneWayOperationDeclaration;
import jolie.lang.parse.ast.OneWayOperationStatement;
import jolie.lang.parse.ast.OperationDeclaration;
import jolie.lang.parse.ast.OutputPortInfo;
import jolie.lang.parse.ast.ParallelStatement;
import jolie.lang.parse.ast.PointerStatement;
import jolie.lang.parse.ast.PostDecrementStatement;
import jolie.lang.parse.ast.PostIncrementStatement;
import jolie.lang.parse.ast.PreDecrementStatement;
import jolie.lang.parse.ast.PreIncrementStatement;
import jolie.lang.parse.ast.Program;
import jolie.lang.parse.ast.ProvideUntilStatement;
import jolie.lang.parse.ast.RequestResponseOperationDeclaration;
import jolie.lang.parse.ast.RequestResponseOperationStatement;
import jolie.lang.parse.ast.RunStatement;
import jolie.lang.parse.ast.Scope;
import jolie.lang.parse.ast.SequenceStatement;
import jolie.lang.parse.ast.SolicitResponseOperationStatement;
import jolie.lang.parse.ast.SpawnStatement;
import jolie.lang.parse.ast.SubtractAssignStatement;
import jolie.lang.parse.ast.SynchronizedStatement;
import jolie.lang.parse.ast.ThrowStatement;
import jolie.lang.parse.ast.TypeCastExpressionNode;
import jolie.lang.parse.ast.UndefStatement;
import jolie.lang.parse.ast.ValueVectorSizeExpressionNode;
import jolie.lang.parse.ast.VariablePathNode;
import jolie.lang.parse.ast.WhileStatement;
import jolie.lang.parse.ast.courier.CourierChoiceStatement;
import jolie.lang.parse.ast.courier.CourierDefinitionNode;
import jolie.lang.parse.ast.courier.NotificationForwardStatement;
import jolie.lang.parse.ast.courier.SolicitResponseForwardStatement;
import jolie.lang.parse.ast.expression.AndConditionNode;
import jolie.lang.parse.ast.expression.ConstantBoolExpression;
import jolie.lang.parse.ast.expression.ConstantDoubleExpression;
import jolie.lang.parse.ast.expression.ConstantIntegerExpression;
import jolie.lang.parse.ast.expression.ConstantLongExpression;
import jolie.lang.parse.ast.expression.ConstantStringExpression;
import jolie.lang.parse.ast.expression.FreshValueExpressionNode;
import jolie.lang.parse.ast.expression.InlineTreeExpressionNode;
import jolie.lang.parse.ast.expression.InstanceOfExpressionNode;
import jolie.lang.parse.ast.expression.IsTypeExpressionNode;
import jolie.lang.parse.ast.expression.NotExpressionNode;
import jolie.lang.parse.ast.expression.OrConditionNode;
import jolie.lang.parse.ast.expression.ProductExpressionNode;
import jolie.lang.parse.ast.expression.SumExpressionNode;
import jolie.lang.parse.ast.expression.VariableExpressionNode;
import jolie.lang.parse.ast.expression.VoidExpressionNode;
import jolie.lang.parse.ast.types.TypeChoiceDefinition;
import jolie.lang.parse.ast.types.TypeDefinition;
import jolie.lang.parse.ast.types.TypeDefinitionLink;
import jolie.lang.parse.ast.types.TypeInlineDefinition;
import jolie.lang.parse.context.ParsingContext;
import jolie.net.AggregatedOperation;
import jolie.net.ext.CommProtocolFactory;
import jolie.net.ports.InputPort;
import jolie.net.ports.Interface;
import jolie.net.ports.InterfaceExtender;
import jolie.net.ports.OutputPort;
import jolie.process.AddAssignmentProcess;
import jolie.process.AssignmentProcess;
import jolie.process.CallProcess;
import jolie.process.CompensateProcess;
import jolie.process.CurrentHandlerProcess;
import jolie.process.DeepCopyProcess;
import jolie.process.DefinitionProcess;
import jolie.process.DivideAssignmentProcess;
import jolie.process.ExitProcess;
import jolie.process.ForEachArrayItemProcess;
import jolie.process.ForEachSubNodeProcess;
import jolie.process.ForProcess;
import jolie.process.IfProcess;
import jolie.process.InitDefinitionProcess;
import jolie.process.InputOperationProcess;
import jolie.process.InstallProcess;
import jolie.process.LinkInProcess;
import jolie.process.LinkOutProcess;
import jolie.process.MakePointerProcess;
import jolie.process.MultiplyAssignmentProcess;
import jolie.process.NDChoiceProcess;
import jolie.process.NotificationProcess;
import jolie.process.NullProcess;
import jolie.process.OneWayProcess;
import jolie.process.ParallelProcess;
import jolie.process.PostDecrementProcess;
import jolie.process.PostIncrementProcess;
import jolie.process.PreDecrementProcess;
import jolie.process.PreIncrementProcess;
import jolie.process.Process;
import jolie.process.ProvideUntilProcess;
import jolie.process.RequestResponseProcess;
import jolie.process.RunProcess;
import jolie.process.ScopeProcess;
import jolie.process.SequentialProcess;
import jolie.process.SolicitResponseProcess;
import jolie.process.SpawnProcess;
import jolie.process.SubtractAssignmentProcess;
import jolie.process.SynchronizedProcess;
import jolie.process.ThrowProcess;
import jolie.process.UndefProcess;
import jolie.process.WhileProcess;
import jolie.process.courier.ForwardNotificationProcess;
import jolie.process.courier.ForwardSolicitResponseProcess;
import jolie.runtime.ClosedVariablePath;
import jolie.runtime.CompareOperators;
import jolie.runtime.GlobalVariablePath;
import jolie.runtime.InstallFixedVariablePath;
import jolie.runtime.InvalidIdException;
import jolie.runtime.OneWayOperation;
import jolie.runtime.RequestResponseOperation;
import jolie.runtime.Value;
import jolie.runtime.VariablePath;
import jolie.runtime.VariablePathBuilder;
import jolie.runtime.correlation.CorrelationSet;
import jolie.runtime.correlation.CorrelationSet.CorrelationPair;
import jolie.runtime.embedding.EmbeddedServiceLoader;
import jolie.runtime.embedding.EmbeddedServiceLoader.EmbeddedServiceConfiguration;
import jolie.runtime.embedding.EmbeddedServiceLoaderCreationException;
import jolie.runtime.expression.AndCondition;
import jolie.runtime.expression.CastBoolExpression;
import jolie.runtime.expression.CastDoubleExpression;
import jolie.runtime.expression.CastIntExpression;
import jolie.runtime.expression.CastLongExpression;
import jolie.runtime.expression.CastStringExpression;
import jolie.runtime.expression.CompareCondition;
import jolie.runtime.expression.Expression;
import jolie.runtime.expression.Expression.Operand;
import jolie.runtime.expression.FreshValueExpression;
import jolie.runtime.expression.InlineTreeExpression;
import jolie.runtime.expression.InstanceOfExpression;
import jolie.runtime.expression.IsBoolExpression;
import jolie.runtime.expression.IsDefinedExpression;
import jolie.runtime.expression.IsDoubleExpression;
import jolie.runtime.expression.IsIntExpression;
import jolie.runtime.expression.IsLongExpression;
import jolie.runtime.expression.IsStringExpression;
import jolie.runtime.expression.NotExpression;
import jolie.runtime.expression.OrCondition;
import jolie.runtime.expression.ProductExpression;
import jolie.runtime.expression.SumExpression;
import jolie.runtime.expression.ValueVectorSizeExpression;
import jolie.runtime.expression.VoidExpression;
import jolie.runtime.typing.OneWayTypeDescription;
import jolie.runtime.typing.RequestResponseTypeDescription;
import jolie.runtime.typing.Type;
import jolie.util.ArrayListMultiMap;
import jolie.util.MultiMap;
import jolie.util.Pair;
/**
* Builds an interpretation tree by visiting a Jolie abstract syntax tree.
* @author Fabrizio Montesi
* @see OLVisitor
*/
public class OOITBuilder implements OLVisitor
{
private final Program program;
private boolean valid = true;
private final Interpreter interpreter;
private String currentOutputPort = null;
private Interface currentPortInterface = null;
private final Map< String, Boolean > isConstantMap;
private final Map< String, InputPort > inputPorts = new HashMap<>();
private final List< Pair< Type.TypeLink, TypeDefinition > > typeLinks = new ArrayList<>();
private final CorrelationFunctionInfo correlationFunctionInfo;
private ExecutionMode executionMode = Constants.ExecutionMode.SINGLE;
private boolean registerSessionStarters = false;
private InputPort currCourierInputPort = null;
private String currCourierOperationName = null;
private final Map< String, Map< String, AggregationConfiguration > > aggregationConfigurations =
new HashMap<>(); // Input port name -> (operation name -> aggregation configuration)
private final Map< String, InterfaceExtender > interfaceExtenders =
new HashMap<>();
private final Deque< OLSyntaxNode > lazyVisits = new LinkedList<>();
private boolean firstPass = true;
private static class AggregationConfiguration {
private final OutputPort defaultOutputPort;
private final Interface aggregatedInterface;
private final InterfaceExtender interfaceExtender;
public AggregationConfiguration(
OutputPort defaultOutputPort,
Interface aggregatedInterface,
InterfaceExtender interfaceExtender
) {
this.defaultOutputPort = defaultOutputPort;
this.aggregatedInterface = aggregatedInterface;
this.interfaceExtender = interfaceExtender;
}
}
/**
* Constructor.
* @param interpreter the Interpreter requesting the interpretation tree building
* @param program the Program to generate the interpretation tree from
* @param isConstantMap
* @param correlationFunctionInfo
* @see Program
*/
public OOITBuilder(
Interpreter interpreter,
Program program,
Map< String, Boolean > isConstantMap,
CorrelationFunctionInfo correlationFunctionInfo
) {
this.interpreter = interpreter;
this.program = new Program( program.context() );
this.isConstantMap = isConstantMap;
this.correlationFunctionInfo = correlationFunctionInfo;
Map< String, TypeDefinition > builtInTypes = OLParser.createTypeDeclarationMap( program.context() );
this.program.children().addAll( builtInTypes.values() );
this.program.children().addAll( program.children() );
}
private void error( ParsingContext context, String message )
{
valid = false;
String s = context.sourceName() + ":" + context.line() + ": " + message;
interpreter.logSevere( s );
}
private void error( ParsingContext context, Exception e )
{
valid = false;
e.printStackTrace();
error( context, e.getMessage() );
}
/**
* Launches the build process.
*
* The Program passed to the constructor gets visited and the Interpreter
* passed to the constructor is set with the necessary references
* to the interpretation tree.
* @return true if the build process is successful, false otherwise
*/
public boolean build()
{
visit( program );
checkForInit();
resolveTypeLinks();
lazyVisits();
buildCorrelationSets();
return valid;
}
private void lazyVisits()
{
firstPass = false;
OLSyntaxNode node;
while( (node = lazyVisits.poll()) != null ) {
node.accept( this );
}
}
private void visitLater( OLSyntaxNode n )
{
lazyVisits.add( n );
}
private void checkForInit()
{
try {
interpreter.getDefinition( "init" );
} catch( InvalidIdException e ) {
interpreter.register( "init",
new InitDefinitionProcess(
new ScopeProcess( "main", new InstallProcess( SessionThread.createDefaultFaultHandlers( interpreter ) ), false )
));
}
}
private void resolveTypeLinks()
{
Type type;
for( Pair< Type.TypeLink, TypeDefinition > pair : typeLinks ) {
type = types.get( pair.key().linkedTypeName() );
pair.key().setLinkedType( type );
if ( type == null ) {
error( pair.value().context(), "type link to " + pair.key().linkedTypeName() + " cannot be resolved" );
}
}
}
private void buildCorrelationSets()
{
Interpreter.SessionStarter starter;
Collection< String > operations;
VariablePath sessionVariablePath;
VariablePath messageVariablePath;
CorrelationSet currCorrelationSet;
Set< Interpreter.SessionStarter > starters = new HashSet<>();
List< VariablePath > correlationVariablePaths;
MultiMap< String, CorrelationPair > correlationMap;
for( CorrelationSetInfo csetInfo : correlationFunctionInfo.correlationSets() ) {
correlationVariablePaths = new ArrayList<>();
correlationMap = new ArrayListMultiMap<>();
for( CorrelationVariableInfo csetVariableInfo : csetInfo.variables() ) {
sessionVariablePath = buildCorrelationVariablePath( csetVariableInfo.correlationVariablePath() );
correlationVariablePaths.add( sessionVariablePath );
}
operations = correlationFunctionInfo.correlationSetOperations().get( csetInfo );
for( String operationName : operations ) {
for( CorrelationPairInfo pairInfo : correlationFunctionInfo.getOperationCorrelationPairs( operationName ) ) {
sessionVariablePath = buildCorrelationVariablePath( pairInfo.sessionPath() );
messageVariablePath = buildVariablePath( pairInfo.messagePath() );
correlationMap.put(
operationName,
new CorrelationPair( sessionVariablePath, messageVariablePath )
);
starter = interpreter.getSessionStarter( operationName );
if ( starter != null && starter.correlationInitializer() == null ) {
starters.add( starter );
}
}
}
currCorrelationSet = new CorrelationSet( correlationVariablePaths, correlationMap );
interpreter.addCorrelationSet( currCorrelationSet );
for( Interpreter.SessionStarter initStarter : starters ) {
initStarter.setCorrelationInitializer( currCorrelationSet );
}
starters.clear();
}
}
public void visit( ExecutionInfo n )
{
executionMode = n.mode();
interpreter.setExecutionMode( n.mode() );
}
public void visit( VariablePathNode n )
{}
public void visit( CorrelationSetInfo n )
{
// correlationSetInfoList.add( n );
}
public void visit( OutputPortInfo n )
{
final Process protocolConfigurationProcess =
( n.protocolConfiguration() != null ) ? buildProcess( n.protocolConfiguration() )
: NullProcess.getInstance();
final boolean isConstant = isConstantMap.computeIfAbsent( n.id(), k -> false );
currentOutputPort = n.id();
notificationTypes.put( currentOutputPort, new HashMap<>() );
solicitResponseTypes.put( currentOutputPort, new HashMap<>() );
for( OperationDeclaration decl : n.operations() ) {
decl.accept( this );
}
currentOutputPort = null;
interpreter.register( n.id(), new OutputPort(
interpreter,
n.id(),
n.protocolId(),
protocolConfigurationProcess,
n.location(),
getOutputPortInterface( n.id() ),
isConstant
)
);
}
private Interface getOutputPortInterface( String outputPortName )
{
Map< String, OneWayTypeDescription > oneWayMap = notificationTypes.get( outputPortName );
if ( oneWayMap == null ) {
oneWayMap = new HashMap< String, OneWayTypeDescription >();
}
Map< String, RequestResponseTypeDescription > rrMap = solicitResponseTypes.get( outputPortName );
if ( rrMap == null ) {
rrMap = new HashMap< String, RequestResponseTypeDescription >();
}
return new Interface( oneWayMap, rrMap );
}
public void visit( EmbeddedServiceNode n )
{
try {
final VariablePath path =
n.portId() == null ? null
: interpreter.getOutputPort( n.portId() ).locationVariablePath();
final EmbeddedServiceConfiguration embeddedServiceConfiguration =
n.type().equals( Constants.EmbeddedServiceType.INTERNAL )
? new EmbeddedServiceLoader.InternalEmbeddedServiceConfiguration( n.servicePath(), (Program) n.program() )
: new EmbeddedServiceLoader.ExternalEmbeddedServiceConfiguration( n.type(), n.servicePath() );
interpreter.addEmbeddedServiceLoader(
EmbeddedServiceLoader.create(
interpreter,
embeddedServiceConfiguration,
path
) );
} catch( EmbeddedServiceLoaderCreationException e ) {
error( n.context(), e );
} catch( InvalidIdException e ) {
error( n.context(), "could not find port " + n.portId() );
}
}
private AggregationConfiguration getAggregationConfiguration( String inputPortName, String operationName )
{
Map< String, AggregationConfiguration > map = aggregationConfigurations.get( inputPortName );
if ( map == null ) {
return null;
}
return map.get( operationName );
}
private void putAggregationConfiguration( String inputPortName, String operationName, AggregationConfiguration configuration )
{
Map< String, AggregationConfiguration > map = aggregationConfigurations.get( inputPortName );
if ( map == null ) {
map = new HashMap<>();
aggregationConfigurations.put( inputPortName, map );
}
map.put( operationName, configuration );
}
public void visit( InputPortInfo n )
{
currentPortInterface = new Interface(
new HashMap< String, OneWayTypeDescription >(),
new HashMap< String, RequestResponseTypeDescription >()
);
for( OperationDeclaration op : n.operations() ) {
op.accept( this );
}
Map< String, OutputPort > redirectionMap =
new HashMap< String, OutputPort > ();
OutputPort oPort = null;
for( Entry< String, String > entry : n.redirectionMap().entrySet() ) {
try {
oPort = interpreter.getOutputPort( entry.getValue() );
} catch( InvalidIdException e ) {
error( n.context(), "Unknown output port (" + entry.getValue() + ") in redirection for input port " + n.id() );
}
redirectionMap.put( entry.getKey(), oPort );
}
OutputPort outputPort;
Map< String, OneWayTypeDescription > outputPortNotificationTypes;
Map< String, RequestResponseTypeDescription > outputPortSolicitResponseTypes;
Map< String, AggregatedOperation > aggregationMap = new HashMap< String, AggregatedOperation >();
InterfaceExtender extender;
for( InputPortInfo.AggregationItemInfo item : n.aggregationList() ) {
String outputPortName = item.outputPortList()[0];
if ( item.interfaceExtender() == null ) {
extender = null;
} else {
extender = interfaceExtenders.get( item.interfaceExtender().name() );
}
try {
outputPort = interpreter.getOutputPort( outputPortName );
outputPortNotificationTypes = notificationTypes.get( outputPortName );
outputPortSolicitResponseTypes = solicitResponseTypes.get( outputPortName );
for( String operationName : outputPortNotificationTypes.keySet() ) {
aggregationMap.put( operationName, AggregatedOperation.createDirect( operationName, Constants.OperationType.ONE_WAY, outputPort ) );
putAggregationConfiguration( n.id(), operationName,
new AggregationConfiguration( outputPort, outputPort.getInterface(), extender ) );
}
for( String operationName : outputPortSolicitResponseTypes.keySet() ) {
aggregationMap.put( operationName, AggregatedOperation.createDirect( operationName, Constants.OperationType.REQUEST_RESPONSE, outputPort ) );
putAggregationConfiguration( n.id(), operationName,
new AggregationConfiguration( outputPort, outputPort.getInterface(), extender ) );
}
} catch( InvalidIdException e ) {
error( n.context(), e );
}
}
String pId = n.protocolId();
CommProtocolFactory protocolFactory = null;
VariablePath protocolConfigurationPath =
new VariablePathBuilder( true )
.add( Constants.INPUT_PORTS_NODE_NAME, 0 )
.add( n.id(), 0 )
.add( Constants.PROTOCOL_NODE_NAME, 0 )
.toVariablePath();
try {
protocolFactory = interpreter.commCore().getCommProtocolFactory( pId );
} catch( IOException e ) {
error( n.context(), e );
}
VariablePath locationPath =
new VariablePathBuilder( true )
.add( Constants.INPUT_PORTS_NODE_NAME, 0 )
.add( n.id(), 0 )
.add( Constants.LOCATION_NODE_NAME, 0 )
.toVariablePath();
locationPath = new ClosedVariablePath( locationPath, interpreter.globalValue() );
// Process assignLocation = new AssignmentProcess( locationPath, Value.create( n.location().toString() ) );
locationPath.getValue().setValue( n.location().toString() );
VariablePath protocolPath =
new VariablePathBuilder( true )
.add( Constants.INPUT_PORTS_NODE_NAME, 0 )
.add( n.id(), 0 )
.add( Constants.PROTOCOL_NODE_NAME, 0 )
.toVariablePath();
Process assignProtocol = new AssignmentProcess( protocolPath, Value.create( n.protocolId() ) );
Process[] confChildren = new Process[] { assignProtocol, buildProcess( n.protocolConfiguration() ) };
SequentialProcess protocolConfigurationSequence = new SequentialProcess( confChildren );
InputPort inputPort = new InputPort(
n.id(),
locationPath,
protocolConfigurationPath,
currentPortInterface,
aggregationMap,
redirectionMap
);
if ( n.location().toString().equals( Constants.LOCAL_LOCATION_KEYWORD ) ) {
try {
interpreter.commCore().addLocalInputPort( inputPort );
inputPorts.put( inputPort.name(), inputPort );
} catch( IOException e ) {
error( n.context(), e );
}
} else if ( protocolFactory != null || n.location().getScheme().equals( Constants.LOCAL_LOCATION_KEYWORD ) ) {
try {
interpreter.commCore().addInputPort(
inputPort,
protocolFactory,
protocolConfigurationSequence
);
inputPorts.put( inputPort.name(), inputPort );
} catch( IOException ioe ) {
error( n.context(), ioe );
}
} else {
error( n.context(), "Communication protocol extension for protocol " + pId + " not found." );
}
currentPortInterface = null;
}
private Process currProcess;
private Expression currExpression;
private Type currType;
boolean insideType = false;
private final Map< String, Type > types = new HashMap< String, Type >();
private final Map< String, Map< String, OneWayTypeDescription > > notificationTypes =
new HashMap< String, Map< String, OneWayTypeDescription > >(); // Maps output ports to their OW operation types
private final Map< String, Map< String, RequestResponseTypeDescription > > solicitResponseTypes =
new HashMap< String, Map< String, RequestResponseTypeDescription > >(); // Maps output ports to their RR operation types
public void visit( TypeInlineDefinition n )
{
boolean backupInsideType = insideType;
insideType = true;
if ( n.untypedSubTypes() ) {
currType = Type.create( n.nativeType(), n.cardinality(), true, null );
} else {
Map< String, Type > subTypes = new HashMap< String, Type >();
if ( n.subTypes() != null ) {
for( Entry< String, TypeDefinition > entry : n.subTypes() ) {
subTypes.put( entry.getKey(), buildType( entry.getValue() ) );
}
}
currType = Type.create(
n.nativeType(),
n.cardinality(),
false,
subTypes
);
}
insideType = backupInsideType;
if ( insideType == false && insideOperationDeclaration == false ) {
types.put( n.id(), currType );
}
}
public void visit( TypeDefinitionLink n )
{
Type.TypeLink link = Type.createLink( n.linkedTypeName(), n.cardinality() );
currType = link;
typeLinks.add( new Pair<>( link, n ) );
if ( insideType == false && insideOperationDeclaration == false ) {
types.put( n.id(), currType );
}
}
public void visit( Program p )
{
for( OLSyntaxNode node : p.children() )
node.accept( this );
}
private boolean insideOperationDeclaration = false;
private OneWayTypeDescription buildOneWayTypeDescription( OneWayOperationDeclaration decl )
{
if ( decl == null ) {
return null;
}
if ( currentOutputPort == null ) { // We are in an input port (TODO: why does this matter? junk code?)
return new OneWayTypeDescription( types.get( decl.requestType().id() ) );
} else {
return new OneWayTypeDescription( buildType( decl.requestType() ) );
}
}
private RequestResponseTypeDescription buildRequestResponseTypeDescription( RequestResponseOperationDeclaration decl )
{
if ( decl == null ) {
return null;
}
RequestResponseTypeDescription typeDescription;
Map< String, Type > faults = new HashMap< String, Type >();
if ( currentOutputPort == null ) { // We are in an input port (TODO: why does this matter? junk code?)
for( Entry< String, TypeDefinition > entry : decl.faults().entrySet() ) {
faults.put( entry.getKey(), types.get( entry.getValue().id() ) );
}
typeDescription = new RequestResponseTypeDescription(
types.get( decl.requestType().id() ),
types.get( decl.responseType().id() ),
faults
);
} else {
for( Entry< String, TypeDefinition > entry : decl.faults().entrySet() ) {
faults.put( entry.getKey(), types.get( entry.getValue().id() ) );
}
typeDescription = new RequestResponseTypeDescription(
buildType( decl.requestType() ),
buildType( decl.responseType() ),
faults
);
}
return typeDescription;
}
public void visit( OneWayOperationDeclaration decl )
{
boolean backup = insideOperationDeclaration;
insideOperationDeclaration = true;
OneWayTypeDescription typeDescription;
if ( currentOutputPort == null ) { // We are in an input port
// Register if not already present
typeDescription = buildOneWayTypeDescription( decl );
try {
interpreter.getOneWayOperation( decl.id() );
} catch( InvalidIdException e ) {
interpreter.register( decl.id(), new OneWayOperation( decl.id(), types.get( decl.requestType().id() ) ) );
}
} else {
typeDescription = buildOneWayTypeDescription( decl );
notificationTypes.get( currentOutputPort ).put( decl.id(), typeDescription );
}
if ( currentPortInterface != null ) {
currentPortInterface.oneWayOperations().put( decl.id(), typeDescription );
}
insideOperationDeclaration = backup;
}
public void visit( RequestResponseOperationDeclaration decl )
{
RequestResponseTypeDescription typeDescription;
if ( currentOutputPort == null ) {
// Register if not already present
try {
final RequestResponseOperation op = interpreter.getRequestResponseOperation( decl.id() );
typeDescription = op.typeDescription();
} catch( InvalidIdException e ) {
typeDescription = buildRequestResponseTypeDescription( decl );
interpreter.register(
decl.id(),
new RequestResponseOperation( decl.id(), typeDescription )
);
}
} else {
typeDescription = buildRequestResponseTypeDescription( decl );
solicitResponseTypes.get( currentOutputPort ).put( decl.id(), typeDescription );
}
if ( currentPortInterface != null ) {
currentPortInterface.requestResponseOperations().put( decl.id(), typeDescription );
}
}
public void visit( DefinitionNode n )
{
final DefinitionProcess def;
switch( n.id() ) {
case "main":
switch( executionMode ) {
case SINGLE:
// We are a single-session service, so we will not spawn sessions
registerSessionStarters = false;
def = new DefinitionProcess( buildProcess( n.body() ) );
break;
default:
registerSessionStarters = true;
def = new DefinitionProcess( buildProcess( n.body() ) );
registerSessionStarters = false;
break;
}
break;
case "init":
final Process[] initChildren = {
new InstallProcess( SessionThread.createDefaultFaultHandlers( interpreter ) ),
buildProcess( n.body() )
};
def = new InitDefinitionProcess( new ScopeProcess( "main", new SequentialProcess( initChildren ), false ) );
break;
default:
def = new DefinitionProcess( buildProcess( n.body() ) );
break;
}
interpreter.register( n.id(), def );
}
public void visit( ParallelStatement n )
{
Process[] children = new Process[ n.children().size() ];
int i = 0;
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
children[ i++ ] = currProcess;
}
currProcess = new ParallelProcess( children );
}
public void visit( SynchronizedStatement n )
{
n.body().accept( this );
currProcess = new SynchronizedProcess( n.id(), currProcess );
}
@Override
public void visit( SequenceStatement n )
{
final boolean origRegisterSessionStarters = registerSessionStarters;
registerSessionStarters = false;
final List< Process > children = new ArrayList<>( n.children().size() );
n.children().forEach( ( child ) -> {
children.add( buildProcess( child ) );
} );
currProcess = new SequentialProcess( children.toArray( new Process[0] ) );
if ( origRegisterSessionStarters && children.get( 0 ) instanceof InputOperationProcess ) {
// We must register this sequence as a starter guarded by the first input process
InputOperationProcess first = (InputOperationProcess) children.remove( 0 );
registerSessionStarter(
first,
new SequentialProcess( children.toArray( new Process[0] ) )
);
}
registerSessionStarters = origRegisterSessionStarters;
}
private void registerSessionStarter( InputOperationProcess guard, Process body )
{
guard.setSessionStarter( true );
interpreter.registerSessionStarter( guard, body );
}
public void visit( NDChoiceStatement n )
{
boolean origRegisterSessionStarters = registerSessionStarters;
registerSessionStarters = false;
List< Pair< InputOperationProcess, Process > > branches =
new ArrayList<>( n.children().size() );
InputOperationProcess guard;
for( Pair< OLSyntaxNode, OLSyntaxNode > pair : n.children() ) {
pair.key().accept( this );
try {
guard = (InputOperationProcess) currProcess;
pair.value().accept( this );
branches.add(
new Pair< InputOperationProcess, Process >( guard, currProcess )
);
if ( origRegisterSessionStarters ) {
registerSessionStarter( guard, currProcess );
}
} catch( Exception e ) {
e.printStackTrace();
}
}
currProcess = new NDChoiceProcess( branches.toArray( new Pair[0] ) );
registerSessionStarters = origRegisterSessionStarters;
}
public void visit( OneWayOperationStatement n )
{
boolean origRegisterSessionStarters = registerSessionStarters;
registerSessionStarters = false;
try {
InputOperationProcess inputProcess;
currProcess = inputProcess =
new OneWayProcess(
interpreter.getOneWayOperation( n.id() ),
buildVariablePath( n.inputVarPath() )
);
if ( origRegisterSessionStarters ) {
registerSessionStarter( inputProcess, NullProcess.getInstance() );
}
} catch( InvalidIdException e ) {
error( n.context(), e );
}
registerSessionStarters = origRegisterSessionStarters;
}
public void visit( RequestResponseOperationStatement n )
{
boolean origRegisterSessionStarters = registerSessionStarters;
registerSessionStarters = false;
Expression outputExpression = null;
if ( n.outputExpression() != null ) {
n.outputExpression().accept( this );
outputExpression = currExpression;
}
try {
InputOperationProcess inputProcess;
currProcess = inputProcess =
new RequestResponseProcess(
interpreter.getRequestResponseOperation( n.id() ),
buildVariablePath( n.inputVarPath() ),
outputExpression,
buildProcess( n.process() )
);
if ( origRegisterSessionStarters ) {
registerSessionStarter( inputProcess, NullProcess.getInstance() );
}
} catch( InvalidIdException e ) {
error( n.context(), e );
}
registerSessionStarters = origRegisterSessionStarters;
}
public void visit( NotificationOperationStatement n )
{
Expression outputExpression = null;
if ( n.outputExpression() != null ) {
n.outputExpression().accept( this );
outputExpression = currExpression;
}
try {
currProcess =
new NotificationProcess(
n.id(),
interpreter.getOutputPort( n.outputPortId() ),
outputExpression,
notificationTypes.get( n.outputPortId() ).get( n.id() )
);
} catch( InvalidIdException e ) {
error( n.context(), e );
}
}
public void visit( SolicitResponseOperationStatement n )
{
try {
Process installProcess = NullProcess.getInstance();
if ( n.handlersFunction() != null )
installProcess = new InstallProcess( getHandlersFunction( n.handlersFunction() ) );
currProcess =
new SolicitResponseProcess(
n.id(),
interpreter.getOutputPort( n.outputPortId() ),
buildExpression( n.outputExpression() ),
buildVariablePath( n.inputVarPath() ),
installProcess,
solicitResponseTypes.get( n.outputPortId() ).get( n.id() )
);
} catch( InvalidIdException e ) {
error( n.context(), e );
}
}
public void visit( LinkInStatement n )
{
currProcess = new LinkInProcess( n.id() );
}
public void visit( LinkOutStatement n )
{
currProcess = new LinkOutProcess( n.id() );
}
public void visit( ThrowStatement n )
{
Expression expression = null;
if ( n.expression() != null ) {
n.expression().accept( this );
expression = currExpression;
}
currProcess = new ThrowProcess( n.id(), expression );
}
public void visit( CompensateStatement n )
{
currProcess = new CompensateProcess( n.id() );
}
public void visit( Scope n )
{
n.body().accept( this );
currProcess = new ScopeProcess( n.id(), currProcess );
}
public void visit( InstallStatement n )
{
currProcess = new InstallProcess( getHandlersFunction( n.handlersFunction() ) );
}
private List< Pair< String, Process > > getHandlersFunction( InstallFunctionNode n )
{
List< Pair< String, Process > > pairs = new ArrayList<>( n.pairs().length );
for( Pair< String, OLSyntaxNode > pair : n.pairs() ) {
pair.value().accept( this );
pairs.add( new Pair< String, Process >( pair.key(), currProcess ) );
}
return pairs;
}
public void visit( AssignStatement n )
{
n.expression().accept( this );
AssignmentProcess p =
new AssignmentProcess(
buildVariablePath( n.variablePath() ),
currExpression
);
currProcess = p;
currExpression = p;
}
public void visit( AddAssignStatement n )
{
n.expression().accept( this );
AddAssignmentProcess p =
new AddAssignmentProcess(
buildVariablePath( n.variablePath() ),
currExpression );
currProcess = p;
currExpression = p;
}
public void visit( SubtractAssignStatement n )
{
n.expression().accept( this );
SubtractAssignmentProcess p =
new SubtractAssignmentProcess(
buildVariablePath( n.variablePath() ),
currExpression );
currProcess = p;
currExpression = p;
}
public void visit( MultiplyAssignStatement n )
{
n.expression().accept( this );
MultiplyAssignmentProcess p =
new MultiplyAssignmentProcess(
buildVariablePath( n.variablePath() ),
currExpression );
currProcess = p;
currExpression = p;
}
public void visit( DivideAssignStatement n )
{
n.expression().accept( this );
DivideAssignmentProcess p =
new DivideAssignmentProcess(
buildVariablePath( n.variablePath() ),
currExpression );
currProcess = p;
currExpression = p;
}
private VariablePath buildCorrelationVariablePath( VariablePathNode path )
{
VariablePathNode csetVarPathNode = new VariablePathNode( path.context(), VariablePathNode.Type.CSET );
csetVarPathNode.append( new Pair<OLSyntaxNode, OLSyntaxNode>(
new ConstantStringExpression( path.context(), Constants.CSETS ),
new ConstantIntegerExpression( path.context(), 0 )
));
csetVarPathNode.path().addAll( path.path() );
return buildVariablePath( csetVarPathNode );
}
private VariablePath buildVariablePath( VariablePathNode path )
{
if ( path == null )
return null;
final Expression backupExpr = currExpression;
Pair< Expression, Expression >[] internalPath = new Pair[ path.path().size() ];
int i = 0;
for( Pair< OLSyntaxNode, OLSyntaxNode > pair : path.path() ) {
pair.key().accept( this );
Expression keyExpr = currExpression;
if ( pair.value() != null ) {
pair.value().accept( this );
} else {
currExpression = null;
}
internalPath[ i++ ] = new Pair<>( keyExpr, currExpression );
}
currExpression = backupExpr;
return
path.isGlobal() ?
new GlobalVariablePath( internalPath )
:
new VariablePath( internalPath );
}
public void visit( PointerStatement n )
{
currProcess =
new MakePointerProcess(
buildVariablePath( n.leftPath() ),
buildVariablePath( n.rightPath() )
);
}
public void visit( DeepCopyStatement n )
{
currProcess =
new DeepCopyProcess(
buildVariablePath( n.leftPath() ),
buildExpression( n.rightExpression() )
);
}
public void visit( IfStatement n )
{
IfProcess.CPPair[] pairs = new IfProcess.CPPair[ n.children().size() ];
Process elseProcess = null;
Expression condition;
int i = 0;
for( Pair< OLSyntaxNode, OLSyntaxNode > pair : n.children() ) {
pair.key().accept( this );
condition = currExpression;
pair.value().accept( this );
pairs[ i++ ] = new IfProcess.CPPair( condition, currProcess );
}
if ( n.elseProcess() != null ) {
n.elseProcess().accept( this );
elseProcess = currProcess;
}
currProcess = new IfProcess( pairs, elseProcess );
}
public void visit( CurrentHandlerStatement n )
{
currProcess = CurrentHandlerProcess.getInstance();
}
public void visit( DefinitionCallStatement n )
{
currProcess = new CallProcess( n.id() );
}
public void visit( RunStatement n )
{
n.expression().accept( this );
currProcess = new RunProcess( currExpression );
}
public void visit( WhileStatement n )
{
n.condition().accept( this );
Expression condition = currExpression;
n.body().accept( this );
currProcess = new WhileProcess( condition, currProcess );
}
public void visit( OrConditionNode n )
{
Expression[] children = new Expression[ n.children().size() ];
int i = 0;
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
children[ i++ ] = currExpression;
}
currExpression = new OrCondition( children );
}
public void visit( AndConditionNode n )
{
Expression[] children = new Expression[ n.children().size() ];
int i = 0;
for( OLSyntaxNode node : n.children() ) {
node.accept( this );
children[ i++ ] = currExpression;
}
currExpression = new AndCondition( children );
}
public void visit( NotExpressionNode n )
{
n.expression().accept( this );
currExpression = new NotExpression( currExpression );
}
public void visit( CompareConditionNode n )
{
n.leftExpression().accept( this );
Expression left = currExpression;
n.rightExpression().accept( this );
Scanner.TokenType opType = n.opType();
final BiPredicate< Value, Value > operator =
opType == Scanner.TokenType.EQUAL ? CompareOperators.EQUAL
: opType == Scanner.TokenType.NOT_EQUAL ? CompareOperators.NOT_EQUAL
: opType == Scanner.TokenType.LANGLE ? CompareOperators.MINOR
: opType == Scanner.TokenType.RANGLE ? CompareOperators.MAJOR
: opType == Scanner.TokenType.MINOR_OR_EQUAL ? CompareOperators.MINOR_OR_EQUAL
: opType == Scanner.TokenType.MAJOR_OR_EQUAL ? CompareOperators.MAJOR_OR_EQUAL
: null;
Objects.requireNonNull( operator );
currExpression = new CompareCondition( left, currExpression, operator );
}
public void visit( FreshValueExpressionNode n )
{
currExpression = FreshValueExpression.getInstance();
}
public void visit( ConstantIntegerExpression n )
{
currExpression = Value.create( n.value() );
}
public void visit( ConstantLongExpression n )
{
currExpression = Value.create( n.value() );
}
public void visit( ConstantBoolExpression n )
{
currExpression = Value.create( n.value() );
}
public void visit( ConstantDoubleExpression n )
{
currExpression = Value.create( n.value() );
}
public void visit( ConstantStringExpression n )
{
currExpression = Value.create( n.value() );
}
public void visit( ProductExpressionNode n )
{
Operand[] operands = new Operand[ n.operands().size() ];
int i = 0;
for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) {
pair.value().accept( this );
operands[i++] = new Operand( pair.key(), currExpression );
}
currExpression = new ProductExpression( operands );
}
public void visit( SumExpressionNode n )
{
Operand[] operands = new Operand[ n.operands().size() ];
int i = 0;
for( Pair< OperandType, OLSyntaxNode > pair : n.operands() ) {
pair.value().accept( this );
operands[i++] = new Operand( pair.key(), currExpression );
}
currExpression = new SumExpression( operands );
}
public void visit( VariableExpressionNode n )
{
currExpression = buildVariablePath( n.variablePath() );
}
public void visit( InstallFixedVariableExpressionNode n )
{
currExpression =
new InstallFixedVariablePath(
buildVariablePath( n.variablePath() )
);
}
public void visit( NullProcessStatement n )
{
currProcess = NullProcess.getInstance();
}
public void visit( ExitStatement n )
{
currProcess = ExitProcess.getInstance();
}
public void visit( VoidExpressionNode n )
{
currExpression = new VoidExpression();
}
public void visit( ValueVectorSizeExpressionNode n )
{
currExpression = new ValueVectorSizeExpression( buildVariablePath( n.variablePath() ) );
}
public void visit( PreDecrementStatement n )
{
PreDecrementProcess p =
new PreDecrementProcess( buildVariablePath( n.variablePath() ) );
currProcess = p;
currExpression = p;
}
public void visit( PostDecrementStatement n )
{
PostDecrementProcess p =
new PostDecrementProcess( buildVariablePath( n.variablePath() ) );
currProcess = p;
currExpression = p;
}
public void visit( IsTypeExpressionNode n )
{
IsTypeExpressionNode.CheckType type = n.type();
if ( type == IsTypeExpressionNode.CheckType.DEFINED ) {
currExpression =
new IsDefinedExpression( buildVariablePath( n.variablePath() ) );
} else if ( type == IsTypeExpressionNode.CheckType.INT ) {
currExpression =
new IsIntExpression( buildVariablePath( n.variablePath() ) );
} else if ( type == IsTypeExpressionNode.CheckType.DOUBLE ) {
currExpression =
new IsDoubleExpression( buildVariablePath( n.variablePath() ) );
} else if ( type == IsTypeExpressionNode.CheckType.BOOL ) {
currExpression =
new IsBoolExpression( buildVariablePath( n.variablePath() ) );
} else if ( type == IsTypeExpressionNode.CheckType.LONG ) {
currExpression =
new IsLongExpression( buildVariablePath( n.variablePath() ) );
} else if ( type == IsTypeExpressionNode.CheckType.STRING ) {
currExpression =
new IsStringExpression( buildVariablePath( n.variablePath() ) );
}
}
public void visit( InlineTreeExpressionNode n )
{
Expression rootExpression = buildExpression( n.rootExpression() );
Pair< VariablePath, Expression >[] assignments = new Pair[ n.assignments().length ];
int i = 0;
for( Pair< VariablePathNode, OLSyntaxNode > pair : n.assignments() ) {
assignments[ i++ ] = new Pair< VariablePath, Expression >(
buildVariablePath( pair.key() ),
buildExpression( pair.value() )
);
}
currExpression = new InlineTreeExpression( rootExpression, assignments );
}
public void visit( InstanceOfExpressionNode n )
{
currExpression = new InstanceOfExpression( buildExpression( n.expression() ), buildType( n.type() ) );
}
public void visit( TypeCastExpressionNode n )
{
n.expression().accept( this );
switch( n.type() ) {
case INT:
currExpression = new CastIntExpression( currExpression );
break;
case DOUBLE:
currExpression = new CastDoubleExpression( currExpression );
break;
case STRING:
currExpression = new CastStringExpression( currExpression );
break;
case BOOL:
currExpression = new CastBoolExpression( currExpression );
break;
case LONG:
currExpression = new CastLongExpression( currExpression );
break;
}
}
public void visit( PreIncrementStatement n )
{
PreIncrementProcess p =
new PreIncrementProcess( buildVariablePath( n.variablePath() ) );
currProcess = p;
currExpression = p;
}
public void visit( PostIncrementStatement n )
{
PostIncrementProcess p =
new PostIncrementProcess( buildVariablePath( n.variablePath() ) );
currProcess = p;
currExpression = p;
}
public void visit( ForStatement n )
{
n.init().accept( this );
Process init = currProcess;
n.post().accept( this );
Process post = currProcess;
n.condition().accept( this );
Expression condition = currExpression;
n.body().accept( this );
currProcess = new ForProcess( init, condition, post, currProcess );
}
public void visit( ForEachArrayItemStatement n ) {
n.body().accept( this );
currProcess =
new ForEachArrayItemProcess(
buildVariablePath( n.keyPath() ),
buildVariablePath( n.targetPath() ),
currProcess
);
}
public void visit( ForEachSubNodeStatement n )
{
n.body().accept( this );
currProcess =
new ForEachSubNodeProcess(
buildVariablePath( n.keyPath() ),
buildVariablePath( n.targetPath() ),
currProcess
);
}
private Expression buildExpression( OLSyntaxNode n )
{
if ( n == null ) {
return null;
}
n.accept( this );
return currExpression;
}
private Process buildProcess( OLSyntaxNode n )
{
if ( n == null ) {
return null;
}
n.accept( this );
return currProcess;
}
private Type buildType( OLSyntaxNode n )
{
if ( n == null ) {
return null;
}
n.accept( this );
return currType;
}
public void visit( SpawnStatement n )
{
Process[] children = new Process[2];
children[ 0 ] = new InstallProcess( SessionThread.createDefaultFaultHandlers( interpreter ) );
children[ 1 ] = buildProcess( n.body() );
currProcess = new SpawnProcess(
buildVariablePath( n.indexVariablePath() ),
buildExpression( n.upperBoundExpression() ),
buildVariablePath( n.inVariablePath() ),
new SequentialProcess( children )
);
}
public void visit( UndefStatement n )
{
currProcess = new UndefProcess( buildVariablePath( n.variablePath() ) );
}
public void visit( InterfaceDefinition n ) {}
public void visit( DocumentationComment n ) {}
public void visit( InterfaceExtenderDefinition n )
{
Map< String, OneWayTypeDescription > oneWayDescs = new HashMap< String, OneWayTypeDescription >();
Map< String, RequestResponseTypeDescription > rrDescs = new HashMap< String, RequestResponseTypeDescription >();
for( Entry< String, OperationDeclaration > entry : n.operationsMap().entrySet() ) {
if ( entry.getValue() instanceof OneWayOperationDeclaration ) {
oneWayDescs.put( entry.getKey(), buildOneWayTypeDescription( (OneWayOperationDeclaration)entry.getValue() ) );
} else { // Request-Response
rrDescs.put( entry.getKey(), buildRequestResponseTypeDescription( (RequestResponseOperationDeclaration)entry.getValue() ) );
}
}
InterfaceExtender extender = new InterfaceExtender(
oneWayDescs,
rrDescs,
buildOneWayTypeDescription( n.defaultOneWayOperation() ),
buildRequestResponseTypeDescription( n.defaultRequestResponseOperation() )
);
interfaceExtenders.put( n.name(), extender );
}
public void visit( CourierDefinitionNode n )
{
if ( firstPass ) {
visitLater( n );
} else {
currCourierInputPort = inputPorts.get( n.inputPortName() );
if ( currCourierInputPort == null ) {
error( n.context(), "cannot find input port: " + n.inputPortName() );
} else {
n.body().accept( this );
if ( currCourierInputPort.location().toString().equals( Constants.LOCAL_LOCATION_KEYWORD ) ) {
interpreter.commCore().localListener().inputPort().aggregationMap().putAll( currCourierInputPort.aggregationMap() );
}
}
currCourierInputPort = null;
}
}
private OneWayOperation getExtendedOneWayOperation( String inputPortName, String operationName )
{
AggregationConfiguration conf = getAggregationConfiguration( inputPortName, operationName );
OneWayTypeDescription desc = conf.aggregatedInterface.oneWayOperations().get( operationName );
Type extenderType = null;
if ( conf.interfaceExtender != null ) {
OneWayTypeDescription extenderDesc = conf.interfaceExtender.getOneWayTypeDescription( operationName );
if ( extenderDesc != null ) {
extenderType = extenderDesc.requestType();
}
}
return new OneWayOperation(
operationName,
( extenderType == null ) ? desc.requestType() : Type.extend( desc.requestType(), extenderType )
);
}
private RequestResponseOperation getExtendedRequestResponseOperation( String inputPortName, String operationName )
{
AggregationConfiguration conf = getAggregationConfiguration( inputPortName, operationName );
RequestResponseTypeDescription desc = conf.aggregatedInterface.requestResponseOperations().get( operationName );
Map< String, Type > extendedFaultMap = new HashMap< String, Type >();
extendedFaultMap.putAll( desc.faults() );
Type requestExtenderType = null;
Type responseExtenderType = null;
if ( conf.interfaceExtender != null ) {
RequestResponseTypeDescription extenderDesc = conf.interfaceExtender.getRequestResponseTypeDescription( operationName );
if ( extenderDesc != null ) {
requestExtenderType = extenderDesc.requestType();
responseExtenderType = extenderDesc.responseType();
extendedFaultMap.putAll( extenderDesc.faults() );
}
}
return new RequestResponseOperation(
operationName,
new RequestResponseTypeDescription(
( requestExtenderType == null ) ?
desc.requestType() : Type.extend( desc.requestType(), requestExtenderType ),
( responseExtenderType == null ) ?
desc.responseType() : Type.extend( desc.responseType(), responseExtenderType ),
extendedFaultMap
)
);
}
public void visit( CourierChoiceStatement n )
{
for( CourierChoiceStatement.InterfaceOneWayBranch branch : n.interfaceOneWayBranches() ) {
for( Map.Entry< String, OperationDeclaration > entry : branch.interfaceDefinition.operationsMap().entrySet() ) {
if ( entry.getValue() instanceof OneWayOperationDeclaration ) {
currCourierOperationName = entry.getKey();
currCourierInputPort.aggregationMap().put(
entry.getKey(),
AggregatedOperation.createWithCourier(
getExtendedOneWayOperation( currCourierInputPort.name(), currCourierOperationName ),
buildVariablePath( branch.inputVariablePath ),
buildProcess( branch.body )
)
);
}
}
}
for( CourierChoiceStatement.InterfaceRequestResponseBranch branch : n.interfaceRequestResponseBranches() ) {
for( Map.Entry< String, OperationDeclaration > entry : branch.interfaceDefinition.operationsMap().entrySet() ) {
if ( entry.getValue() instanceof RequestResponseOperationDeclaration ) {
currCourierOperationName = entry.getKey();
currCourierInputPort.aggregationMap().put(
entry.getKey(),
AggregatedOperation.createWithCourier(
getExtendedRequestResponseOperation( currCourierInputPort.name(), currCourierOperationName ),
buildVariablePath( branch.inputVariablePath ), buildVariablePath( branch.outputVariablePath ),
buildProcess( branch.body )
)
);
}
}
}
for( CourierChoiceStatement.OperationOneWayBranch branch : n.operationOneWayBranches() ) {
currCourierOperationName = branch.operation;
currCourierInputPort.aggregationMap().put(
branch.operation,
AggregatedOperation.createWithCourier(
getExtendedOneWayOperation( currCourierInputPort.name(), currCourierOperationName ),
buildVariablePath( branch.inputVariablePath ),
buildProcess( branch.body )
)
);
}
for( CourierChoiceStatement.OperationRequestResponseBranch branch : n.operationRequestResponseBranches() ) {
currCourierOperationName = branch.operation;
currCourierInputPort.aggregationMap().put(
branch.operation,
AggregatedOperation.createWithCourier(
getExtendedRequestResponseOperation( currCourierInputPort.name(), currCourierOperationName ),
buildVariablePath( branch.inputVariablePath ), buildVariablePath( branch.outputVariablePath ),
buildProcess( branch.body )
)
);
}
currCourierOperationName = null;
}
public void visit( NotificationForwardStatement n )
{
AggregationConfiguration conf = getAggregationConfiguration( currCourierInputPort.name(), currCourierOperationName );
try {
OutputPort outputPort;
if ( n.outputPortName() != null ) {
outputPort = interpreter.getOutputPort( n.outputPortName() );
} else {
outputPort = conf.defaultOutputPort;
}
currProcess = new ForwardNotificationProcess(
currCourierOperationName,
outputPort,
buildVariablePath( n.outputVariablePath() ),
conf.aggregatedInterface.oneWayOperations().get( currCourierOperationName ),
(conf.interfaceExtender == null) ? null : conf.interfaceExtender.getOneWayTypeDescription( currCourierOperationName )
);
} catch( InvalidIdException e ) {
error( n.context(), e );
}
}
public void visit( ProvideUntilStatement n )
{
currProcess = new ProvideUntilProcess( (NDChoiceProcess)buildProcess( n.provide() ), (NDChoiceProcess)buildProcess( n.until() ) );
}
@Override
public void visit( TypeChoiceDefinition n )
{
final boolean wasInsideType = insideType;
insideType = true;
currType = Type.createChoice( n.cardinality(), buildType( n.left() ), buildType( n.right() ) );
insideType = wasInsideType;
if ( insideType == false && insideOperationDeclaration == false ) {
types.put( n.id(), currType );
}
}
public void visit( SolicitResponseForwardStatement n )
{
AggregationConfiguration conf = getAggregationConfiguration( currCourierInputPort.name(), currCourierOperationName );
try {
OutputPort outputPort;
if ( n.outputPortName() != null ) {
outputPort = interpreter.getOutputPort( n.outputPortName() );
} else {
outputPort = conf.defaultOutputPort;
}
currProcess = new ForwardSolicitResponseProcess(
currCourierOperationName,
outputPort,
buildVariablePath( n.outputVariablePath() ),
buildVariablePath( n.inputVariablePath() ),
conf.aggregatedInterface.requestResponseOperations().get( currCourierOperationName ),
(conf.interfaceExtender == null) ? null : conf.interfaceExtender.getRequestResponseTypeDescription( currCourierOperationName )
);
} catch( InvalidIdException e ) {
error( n.context(), e );
}
}
}
| lgpl-2.1 |
spotbugs/spotbugs | spotbugs/src/main/java/edu/umd/cs/findbugs/detect/IncompatMask.java | 6473 | /*
* FindBugs - Find bugs in Java programs
* Copyright (C) 2004-2006 University of Maryland
*
* 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 edu.umd.cs.findbugs.detect;
import org.apache.bcel.Const;
import org.apache.bcel.classfile.Code;
import edu.umd.cs.findbugs.BugInstance;
import edu.umd.cs.findbugs.BugReporter;
import edu.umd.cs.findbugs.OpcodeStack.Item;
import edu.umd.cs.findbugs.bcel.OpcodeStackDetector;
/**
* Find comparisons involving values computed with bitwise operations whose
* outcomes are fixed at compile time.
*
* @author Tom Truscott <trt@unx.sas.com>
* @author Tagir Valeev
*/
public class IncompatMask extends OpcodeStackDetector {
private final BugReporter bugReporter;
private int bitop = -1;
private boolean equality;
private Number arg1, arg2;
private Item bitresultItem;
public IncompatMask(BugReporter bugReporter) {
this.bugReporter = bugReporter;
}
static int populationCount(long i) {
return Long.bitCount(i);
}
@Override
public void visit(Code obj) {
arg1 = arg2 = null;
super.visit(obj);
}
private Number getArg() {
Object constValue = stack.getStackItem(0).getConstant();
if (!(constValue instanceof Number)) {
constValue = stack.getStackItem(1).getConstant();
}
if (!(constValue instanceof Long) && !(constValue instanceof Integer)) {
return null;
}
return (Number) constValue;
}
@Override
public void sawOpcode(int seen) {
switch (seen) {
case Const.IAND:
case Const.LAND:
arg1 = getArg();
bitop = Const.IAND;
return;
case Const.IOR:
case Const.LOR:
arg1 = getArg();
bitop = Const.IOR;
return;
case Const.LCMP:
if (checkItem(2)) {
arg2 = getArg();
}
return;
case Const.IF_ICMPEQ:
case Const.IF_ICMPNE:
if (checkItem(2)) {
arg2 = getArg();
equality = true;
}
break;
case Const.IFEQ:
case Const.IFNE:
if (arg1 instanceof Integer && checkItem(1)) {
arg2 = 0;
}
equality = true;
break;
case Const.IFLE:
case Const.IFLT:
case Const.IFGT:
case Const.IFGE:
if (arg1 instanceof Integer && checkItem(1)) {
arg2 = 0;
}
equality = false;
break;
default:
return;
}
if (arg1 == null || arg2 == null) {
return;
}
boolean isLong = arg1 instanceof Long;
if (!equality && arg2.longValue() == 0) {
long bits = getFlagBits(isLong, arg1.longValue());
boolean highbit = !isLong && (bits & 0x80000000) != 0 || isLong && bits < 0 && bits << 1 == 0;
boolean onlyLowBits = bits >>> 12 == 0;
BugInstance bug;
if (highbit) {
bug = new BugInstance(this, "BIT_SIGNED_CHECK_HIGH_BIT", (seen == Const.IFLE || seen == Const.IFGT) ? HIGH_PRIORITY
: NORMAL_PRIORITY);
} else {
bug = new BugInstance(this, "BIT_SIGNED_CHECK", onlyLowBits ? LOW_PRIORITY : NORMAL_PRIORITY);
}
bug.addClassAndMethod(this).addString(toHex(arg1) + " (" + arg1 + ")").addSourceLine(this);
bugReporter.reportBug(bug);
}
if (equality) {
long dif;
String t;
long val1 = arg1.longValue();
long val2 = arg2.longValue();
if (bitop == Const.IOR) {
dif = val1 & ~val2;
t = "BIT_IOR";
} else if (val1 != 0 || val2 != 0) {
dif = val2 & ~val1;
t = "BIT_AND";
} else {
dif = 1;
t = "BIT_AND_ZZ";
}
if (dif != 0) {
BugInstance bug = new BugInstance(this, t, HIGH_PRIORITY).addClassAndMethod(this);
if (!"BIT_AND_ZZ".equals(t)) {
bug.addString(toHex(arg1)).addString(toHex(arg2));
}
bug.addSourceLine(this);
bugReporter.reportBug(bug);
}
}
arg1 = arg2 = null;
bitresultItem = null;
}
private static String toHex(Number n) {
return "0x" + (n instanceof Long ? Long.toHexString(n.longValue()) : Integer.toHexString(n.intValue()));
}
private boolean checkItem(int n) {
if (bitresultItem != null) {
for (int i = 0; i < n; i++) {
if (stack.getStackItem(i) == bitresultItem) {
return true;
}
}
}
arg1 = arg2 = null;
bitresultItem = null;
return false;
}
@Override
public void afterOpcode(int seen) {
super.afterOpcode(seen);
switch (seen) {
case Const.IAND:
case Const.LAND:
case Const.IOR:
case Const.LOR:
if (stack.getStackDepth() > 0) {
bitresultItem = stack.getStackItem(0);
}
break;
default:
break;
}
}
static long getFlagBits(boolean isLong, long arg0) {
long bits = arg0;
if (isLong) {
if (populationCount(bits) > populationCount(~bits)) {
bits = ~bits;
}
} else if (populationCount(0xffffffffL & bits) > populationCount(0xffffffffL & ~bits)) {
bits = 0xffffffffL & ~bits;
}
return bits;
}
}
| lgpl-2.1 |
AlertMe/smackx-jingle | src/main/java/net/java/sip/communicator/impl/protocol/jabber/extensions/jingle/PayloadTypePacketExtension.java | 6152 | /*
* 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.impl.protocol.jabber.extensions.jingle;
import net.java.sip.communicator.impl.protocol.jabber.extensions.AbstractPacketExtension;
import java.util.List;
/**
* Represents the <tt>payload-type</tt> elements described in XEP-0167.
*
* @author Emil Ivov
*/
public class PayloadTypePacketExtension extends AbstractPacketExtension
{
/**
* The name of the "payload-type" element.
*/
public static final String ELEMENT_NAME = "payload-type";
/**
* The name of the <tt>channels</tt> <tt>payload-type</tt> argument.
*/
public static final String CHANNELS_ATTR_NAME = "channels";
/**
* The name of the <tt>clockrate</tt> SDP argument.
*/
public static final String CLOCKRATE_ATTR_NAME = "clockrate";
/**
* The name of the payload <tt>id</tt> SDP argument.
*/
public static final String ID_ATTR_NAME = "id";
/**
* The name of the <tt>maxptime</tt> SDP argument.
*/
public static final String MAXPTIME_ATTR_NAME = "maxptime";
/**
* The name of the <tt>name</tt> SDP argument.
*/
public static final String NAME_ATTR_NAME = "name";
/**
* The name of the <tt>ptime</tt> SDP argument.
*/
public static final String PTIME_ATTR_NAME = "ptime";
/**
* Creates a new {@link PayloadTypePacketExtension} instance.
*/
public PayloadTypePacketExtension()
{
super(null, ELEMENT_NAME);
}
/**
* Sets the number of channels in this payload type. If omitted, it will be
* assumed to contain one channel.
*
* @param channels the number of channels in this payload type.
*/
public void setChannels(int channels)
{
super.setAttribute(CHANNELS_ATTR_NAME, channels);
}
/**
* Returns the number of channels in this payload type.
*
* @return the number of channels in this payload type.
*/
public int getChannels()
{
/*
* XEP-0167: Jingle RTP Sessions says: if omitted, it MUST be assumed
* to contain one channel.
*/
return getAttributeAsInt(CHANNELS_ATTR_NAME, 1);
}
/**
* Specifies the sampling frequency in Hertz used by this encoding.
*
* @param clockrate the sampling frequency in Hertz used by this encoding.
*/
public void setClockrate(String clockrate)
{
super.setAttribute(CLOCKRATE_ATTR_NAME, clockrate);
}
/**
* Returns the sampling frequency in Hertz used by this encoding.
*
* @return the sampling frequency in Hertz used by this encoding.
*/
public String getClockrate()
{
return getAttributeAsString(CLOCKRATE_ATTR_NAME);
}
/**
* Specifies the payload identifier for this encoding.
*
* @param id the payload type id
*/
public void setId(int id)
{
super.setAttribute(ID_ATTR_NAME, id);
}
/**
* Returns the payload identifier for this encoding (as specified by RFC
* 3551 or a dynamic one).
*
* @return the payload identifier for this encoding (as specified by RFC
* 3551 or a dynamic one).
*/
public int getID()
{
return getAttributeAsInt(ID_ATTR_NAME);
}
/**
* Sets the maximum packet time as specified in RFC 4566.
*
* @param maxptime the maximum packet time as specified in RFC 4566
*/
public void setMaxptime(int maxptime)
{
setAttribute(MAXPTIME_ATTR_NAME, maxptime);
}
/**
* Returns maximum packet time as specified in RFC 4566.
*
* @return maximum packet time as specified in RFC 4566
*/
public int getMaxptime()
{
return getAttributeAsInt(MAXPTIME_ATTR_NAME);
}
/**
* Sets the packet time as specified in RFC 4566.
*
* @param ptime the packet time as specified in RFC 4566
*/
public void setPtime(int ptime)
{
super.setAttribute(PTIME_ATTR_NAME, ptime);
}
/**
* Returns packet time as specified in RFC 4566.
*
* @return packet time as specified in RFC 4566
*/
public int getPtime()
{
return getAttributeAsInt(PTIME_ATTR_NAME);
}
/**
* Sets the name of the encoding, or as per the XEP: the appropriate subtype
* of the MIME type. Setting this field is RECOMMENDED for static payload
* types, REQUIRED for dynamic payload types.
*
* @param name the name of this encoding.
*/
public void setName(String name)
{
setAttribute(NAME_ATTR_NAME, name);
}
/**
* Returns the name of the encoding, or as per the XEP: the appropriate
* subtype of the MIME type. Setting this field is RECOMMENDED for static
* payload types, REQUIRED for dynamic payload types.
*
* @return the name of the encoding, or as per the XEP: the appropriate
* subtype of the MIME type. Setting this field is RECOMMENDED for static
* payload types, REQUIRED for dynamic payload types.
*/
public String getName()
{
return getAttributeAsString(NAME_ATTR_NAME);
}
/**
* Adds an SDP parameter to the list that we already have registered for this
* payload type.
*
* @param parameter an SDP parameter for this encoding.
*/
public void addParameter(ParameterPacketExtension parameter)
{
//parameters are the only extensions we can have so let's use
//super's list.
super.addChildExtension(parameter);
}
/**
* Returns a <b>reference</b> to the the list of parameters currently
* registered for this payload type.
*
* @return a <b>reference</b> to the the list of parameters currently
* registered for this payload type.
*/
@SuppressWarnings("unchecked") // nothing we could do here.
public List<ParameterPacketExtension> getParameters()
{
return (List<ParameterPacketExtension>)super.getChildExtensions();
}
}
| lgpl-2.1 |
nybbs2003/jopenmetaverse | src/main/java/com/ngt/jopenmetaverse/shared/sim/events/avm/DisplayNameUpdateEventArgs.java | 1616 | /**
* 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.events.avm;
import com.ngt.jopenmetaverse.shared.sim.AvatarManager.AgentDisplayName;
import com.ngt.jopenmetaverse.shared.sim.events.EventArgs;
/// <summary>
/// Event args class for display name notification messages
/// </summary>
public class DisplayNameUpdateEventArgs extends EventArgs
{
private String oldDisplayName;
private AgentDisplayName displayName;
public String getOldDisplayName() {return oldDisplayName;}
public AgentDisplayName getDisplayName() {return displayName;}
public DisplayNameUpdateEventArgs(String oldDisplayName, AgentDisplayName displayName)
{
this.oldDisplayName = oldDisplayName;
this.displayName = displayName;
}
} | lgpl-2.1 |
pentaho/pentaho-commons-xul | swt/src/main/java/org/pentaho/ui/xul/swt/tags/SwtTab.java | 2595 | /*!
* 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-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.ui.xul.swt.tags;
import org.pentaho.ui.xul.XulComponent;
import org.pentaho.ui.xul.XulDomContainer;
import org.pentaho.ui.xul.components.XulTab;
import org.pentaho.ui.xul.containers.XulTabbox;
import org.pentaho.ui.xul.dom.Element;
import org.pentaho.ui.xul.swt.SwtElement;
public class SwtTab extends SwtElement implements XulTab {
private String label;
private boolean disabled = false;
private String onclick;
private XulTabbox tabbox;
public SwtTab( Element self, XulComponent parent, XulDomContainer domContainer, String tagName ) {
super( "tab" );
setManagedObject( "empty" );
}
public boolean isDisabled() {
return disabled;
}
public String getLabel() {
return label;
}
public String getOnclick() {
return onclick;
}
public void getTabbox() {
if ( tabbox == null ) {
if ( getParent() != null ) {
tabbox = (XulTabbox) getParent().getParent();
}
}
}
public void setDisabled( boolean disabled ) {
this.disabled = disabled;
getTabbox();
if ( tabbox != null ) {
tabbox.setTabDisabledAt( disabled, getParent().getChildNodes().indexOf( this ) );
}
}
public void setLabel( String label ) {
this.label = label;
getTabbox();
if ( tabbox != null ) {
( (SwtTabbox) tabbox ).updateTabState();
}
}
public void setOnclick( String onClick ) {
this.onclick = onClick;
}
@Override
public void layout() {
}
@Override
public void setVisible( boolean visible ) {
super.setVisible( visible );
getTabbox();
if ( tabbox != null ) {
( (SwtTabbox) tabbox ).setTabVisibleAt( visible, getParent().getChildNodes().indexOf( this ) );
( (SwtTabbox) tabbox ).layout();
}
}
}
| lgpl-2.1 |
Castlebin/oolong | src/main/java/COM/sootNsmoke/instructions/Fastore.java | 183 | package COM.sootNsmoke.instructions;
import COM.sootNsmoke.jvm.*;
public class Fastore extends NoArgsSequence
{
public Fastore()
{
super(0, -3, opc_fastore);
}
}
| lgpl-2.1 |
jfree/jfreechart | src/test/java/org/jfree/chart/labels/HighLowItemLabelGeneratorTest.java | 4161 | /* ===========================================================
* JFreeChart : a free chart library for the Java(tm) platform
* ===========================================================
*
* (C) Copyright 2000-2022, by David Gilbert and Contributors.
*
* Project Info: http://www.jfree.org/jfreechart/index.html
*
* 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.
*
* [Oracle and Java are registered trademarks of Oracle and/or its affiliates.
* Other names may be trademarks of their respective owners.]
*
* ----------------------------------
* HighLowItemLabelGeneratorTest.java
* ----------------------------------
* (C) Copyright 2003-2022, by David Gilbert and Contributors.
*
* Original Author: David Gilbert;
* Contributor(s): -;
*
*/
package org.jfree.chart.labels;
import java.text.DecimalFormat;
import java.text.NumberFormat;
import java.text.SimpleDateFormat;
import org.jfree.chart.TestUtils;
import org.jfree.chart.internal.CloneUtils;
import org.jfree.chart.api.PublicCloneable;
import org.junit.jupiter.api.Test;
import static org.junit.jupiter.api.Assertions.*;
/**
* Tests for the {@link HighLowItemLabelGenerator} class.
*/
public class HighLowItemLabelGeneratorTest {
/**
* Tests that the equals method can distinguish all fields.
*/
@Test
public void testEquals() {
HighLowItemLabelGenerator g1 = new HighLowItemLabelGenerator();
HighLowItemLabelGenerator g2 = new HighLowItemLabelGenerator();
assertEquals(g1, g2);
assertEquals(g2, g1);
g1 = new HighLowItemLabelGenerator(new SimpleDateFormat("d-MMM-yyyy"),
NumberFormat.getInstance());
assertNotEquals(g1, g2);
g2 = new HighLowItemLabelGenerator(new SimpleDateFormat("d-MMM-yyyy"),
NumberFormat.getInstance());
assertEquals(g1, g2);
g1 = new HighLowItemLabelGenerator(new SimpleDateFormat("d-MMM-yyyy"),
new DecimalFormat("0.000"));
assertNotEquals(g1, g2);
g2 = new HighLowItemLabelGenerator(new SimpleDateFormat("d-MMM-yyyy"),
new DecimalFormat("0.000"));
assertEquals(g1, g2);
}
/**
* Simple check that hashCode is implemented.
*/
@Test
public void testHashCode() {
HighLowItemLabelGenerator g1 = new HighLowItemLabelGenerator();
HighLowItemLabelGenerator g2 = new HighLowItemLabelGenerator();
assertEquals(g1, g2);
assertEquals(g1.hashCode(), g2.hashCode());
}
/**
* Confirm that cloning works.
*/
@Test
public void testCloning() throws CloneNotSupportedException {
HighLowItemLabelGenerator g1 = new HighLowItemLabelGenerator();
HighLowItemLabelGenerator g2 = CloneUtils.clone(g1);
assertNotSame(g1, g2);
assertSame(g1.getClass(), g2.getClass());
assertEquals(g1, g2);
}
/**
* Check to ensure that this class implements PublicCloneable.
*/
@Test
public void testPublicCloneable() {
HighLowItemLabelGenerator g1 = new HighLowItemLabelGenerator();
assertTrue(g1 instanceof PublicCloneable);
}
/**
* Serialize an instance, restore it, and check for equality.
*/
@Test
public void testSerialization() {
HighLowItemLabelGenerator g1 = new HighLowItemLabelGenerator();
HighLowItemLabelGenerator g2 = TestUtils.serialised(g1);
assertEquals(g1, g2);
}
}
| lgpl-2.1 |
1fechner/FeatureExtractor | sources/FeatureExtractor/lib/hibernate-release-5.1.0.Final/project/hibernate-core/src/test/java/org/hibernate/test/naturalid/mutable/cached/CachedMutableNaturalIdStrictReadWriteTest.java | 7171 | /*
* 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.test.naturalid.mutable.cached;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertNull;
import java.io.Serializable;
import java.util.Map;
import org.hibernate.Session;
import org.hibernate.cfg.Configuration;
import org.hibernate.stat.NaturalIdCacheStatistics;
import org.hibernate.testing.TestForIssue;
import org.hibernate.testing.cache.CachingRegionFactory;
import org.junit.Test;
public class CachedMutableNaturalIdStrictReadWriteTest extends
CachedMutableNaturalIdTest {
@Override
public void configure(Configuration cfg) {
super.configure(cfg);
cfg.setProperty( CachingRegionFactory.DEFAULT_ACCESSTYPE, "read-write" );
}
@Test
@TestForIssue( jiraKey = "HHH-9203" )
public void testToMapConversion() {
sessionFactory().getStatistics().clear();
final Session session = openSession();
session.getTransaction().begin();
final AllCached it = new AllCached( "IT" );
session.save( it );
session.getTransaction().commit();
session.close();
final NaturalIdCacheStatistics stats = sessionFactory().getStatistics().getNaturalIdCacheStatistics(
"hibernate.test." + AllCached.class.getName() + "##NaturalId"
);
final Map entries = stats.getEntries();
assertEquals( 1, entries.size() );
final Serializable[] cacheKey = (Serializable[]) entries.keySet().iterator().next();
assertEquals( 1, cacheKey.length );
assertEquals( it.getName(), cacheKey[0] );
assertNotNull( entries.get( cacheKey ) );
}
@Test
@TestForIssue( jiraKey = "HHH-7278" )
public void testInsertedNaturalIdCachedAfterTransactionSuccess() {
Session session = openSession();
session.getSessionFactory().getStatistics().clear();
session.beginTransaction();
Another it = new Another( "it");
session.save( it );
session.flush();
session.getTransaction().commit();
session.close();
session = openSession();
session.beginTransaction();
it = (Another) session.bySimpleNaturalId(Another.class).load("it");
assertNotNull(it);
session.delete(it);
session.getTransaction().commit();
assertEquals(1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
}
@Test
@TestForIssue( jiraKey = "HHH-7278" )
public void testInsertedNaturalIdNotCachedAfterTransactionFailure() {
Session session = openSession();
session.getSessionFactory().getStatistics().clear();
session.beginTransaction();
Another it = new Another( "it");
session.save( it );
session.flush();
session.getTransaction().rollback();
session.close();
session = openSession();
session.beginTransaction();
it = (Another) session.bySimpleNaturalId(Another.class).load("it");
assertNull(it);
assertEquals(0, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
}
@Test
@TestForIssue( jiraKey = "HHH-7278" )
public void testChangedNaturalIdCachedAfterTransactionSuccess() {
Session session = openSession();
session.beginTransaction();
Another it = new Another( "it");
session.save( it );
session.getTransaction().commit();
session.close();
session = openSession();
session.beginTransaction();
it = (Another) session.bySimpleNaturalId(Another.class).load("it");
assertNotNull(it);
it.setName("modified");
session.flush();
session.getTransaction().commit();
session.close();
session.getSessionFactory().getStatistics().clear();
session = openSession();
session.beginTransaction();
it = (Another) session.bySimpleNaturalId(Another.class).load("modified");
assertNotNull(it);
session.delete(it);
session.getTransaction().commit();
session.close();
assertEquals(1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
}
@Test
@TestForIssue( jiraKey = "HHH-7278" )
public void testChangedNaturalIdNotCachedAfterTransactionFailure() {
Session session = openSession();
session.beginTransaction();
Another it = new Another( "it");
session.save( it );
session.getTransaction().commit();
session.close();
session = openSession();
session.beginTransaction();
it = (Another) session.bySimpleNaturalId(Another.class).load("it");
assertNotNull(it);
it.setName("modified");
session.flush();
session.getTransaction().rollback();
session.close();
session.getSessionFactory().getStatistics().clear();
session = openSession();
session.beginTransaction();
it = (Another) session.bySimpleNaturalId(Another.class).load("modified");
assertNull(it);
it = (Another) session.bySimpleNaturalId(Another.class).load("it");
session.delete(it);
session.getTransaction().commit();
session.close();
assertEquals(0, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
}
@Test
@TestForIssue( jiraKey = "HHH-7309" )
public void testInsertUpdateEntity_NaturalIdCachedAfterTransactionSuccess() {
Session session = openSession();
session.getSessionFactory().getStatistics().clear();
session.beginTransaction();
Another it = new Another( "it");
session.save( it ); // schedules an InsertAction
it.setSurname("1234"); // schedules an UpdateAction, without bug-fix
// this will re-cache natural-id with identical key and at same time invalidate it
session.flush();
session.getTransaction().commit();
session.close();
session = openSession();
session.beginTransaction();
it = (Another) session.bySimpleNaturalId(Another.class).load("it");
assertNotNull(it);
session.delete(it);
session.getTransaction().commit();
assertEquals("In a strict access strategy we would excpect a hit here", 1, session.getSessionFactory().getStatistics().getNaturalIdCacheHitCount());
}
@Test
@TestForIssue( jiraKey = "HHH-9200" )
public void testNaturalIdCacheStatisticsReset() {
final String naturalIdCacheRegion = "hibernate.test.org.hibernate.test.naturalid.mutable.cached.Another##NaturalId";
sessionFactory().getStatistics().clear();
Session session = openSession();
session.beginTransaction();
final Another it = new Another( "IT");
session.save( it );
session.getTransaction().commit();
session.close();
NaturalIdCacheStatistics statistics = sessionFactory().getStatistics().getNaturalIdCacheStatistics( naturalIdCacheRegion );
assertEquals( 1, statistics.getPutCount() );
sessionFactory().getStatistics().clear();
// Refresh statistics reference.
statistics = sessionFactory().getStatistics().getNaturalIdCacheStatistics( naturalIdCacheRegion );
assertEquals( 0, statistics.getPutCount() );
session = openSession();
session.beginTransaction();
session.delete( it );
session.getTransaction().commit();
session.clear();
}
}
| lgpl-2.1 |
varkhan/VCom4j | Serv/P2PConnect/src/net/varkhan/serv/p2p/message/transport/MesgTransport.java | 2675 | /**
*
*/
package net.varkhan.serv.p2p.message.transport;
import net.varkhan.serv.p2p.message.MesgPayload;
import net.varkhan.serv.p2p.message.dispatch.MesgReceiver;
import net.varkhan.serv.p2p.connect.PeerAddress;
import java.io.IOException;
/**
* <b/>A message channel.</b>
* <p/>
* This interface specifies a physical message communication device, and the
* operations needed to receive and send messages.
* <p/>
* @author varkhan
* @date Nov 12, 2009
* @time 12:02:30 AM
*/
public interface MesgTransport {
public PeerAddress endpoint();
/**********************************************************************************
** Life-cycle management
**/
/**
* Indicates whether the channel is started and able to handle messages
*
* @return {@code true} if the channel transport layer is ready to handle outgoing messages,
* and the listening thread is handling incoming messages
*/
public boolean isStarted();
/**
* Starts sending and receiving messages.
*
* @throws java.io.IOException if the channel could not bind to an address
*/
public void start() throws IOException;
/**
* Stops sending and receiving messages.
*
* @throws java.io.IOException if the channel could not free resources
*/
public void stop() throws IOException;
/**********************************************************************************
** Message transmission handling
**/
/**
* Send a method call message through this channel.
*
*
* @param src the source location
* @param dst the destination location
* @param method the identifier for the remote method
* @param message the message to send
* @param handler the call reply handler, or {@literal null} to ignore replies
*
* @throws java.io.IOException if a communication or format error occurred while sending or receiving
*/
public boolean call(PeerAddress src, PeerAddress dst, String method, MesgPayload message, MesgReceiver handler) throws IOException;
/**
* Send a reply message through this channel.
*
*
*
* @param src the source location
* @param dst the destination location
* @param method the identifier for the remote method
* @param message the message to send
* @param sequence the call sequence id
* @throws java.io.IOException if a communication or format error occurred while sending or receiving
*/
public boolean repl(PeerAddress src, PeerAddress dst, String method, MesgPayload message, long sequence) throws IOException;
}
| lgpl-2.1 |
deegree/deegree3 | deegree-core/deegree-core-commons/src/main/java/org/deegree/commons/xml/schema/GrammarPool.java | 2426 | //$HeadURL: svn+ssh://mschneider@svn.wald.intevation.org/deegree/base/trunk/resources/eclipse/files_template.xml $
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.commons.xml.schema;
import org.apache.xerces.util.SymbolTable;
import org.apache.xerces.util.XMLGrammarPoolImpl;
/**
* Xerces <code>XMLGrammarPool</code> implementation that wraps a Xerces <code>SymbolTable</code>.
*
* TODO can Grammars be parsed individually?
*
* @author <a href="mailto:schneider@lat-lon.de">Markus Schneider</a>
* @author last edited by: $Author: schneider $
*
* @version $Revision: $, $Date: $
*/
class GrammarPool extends XMLGrammarPoolImpl {
private SymbolTable sym;
/**
* Creates a new {@link GrammarPool} instance based on the given Xerces <code>SymbolTable</code>.
*
* @param sym
* Xerces <code>SymbolTable</code>, never <code>null</code>
*/
GrammarPool( SymbolTable sym ) {
this.sym = sym;
}
/**
* Returns the wrapped <code>SymbolTable</code>.
*
* @return Xerces <code>SymbolTable</code>, never <code>null</code>
*/
SymbolTable getSymbolTable() {
return sym;
}
}
| lgpl-2.1 |
0xbb/jitsi | src/net/java/sip/communicator/impl/protocol/jabber/IncomingFileTransferRequestJabberImpl.java | 8440 | /*
* 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.impl.protocol.jabber;
import java.io.*;
import java.util.*;
import net.java.sip.communicator.impl.protocol.jabber.extensions.thumbnail.*;
import net.java.sip.communicator.service.protocol.*;
import net.java.sip.communicator.service.protocol.FileTransfer;
import net.java.sip.communicator.service.protocol.event.*;
import net.java.sip.communicator.util.*;
import org.jivesoftware.smack.*;
import org.jivesoftware.smack.filter.*;
import org.jivesoftware.smack.packet.*;
import org.jivesoftware.smack.util.StringUtils;
import org.jivesoftware.smackx.filetransfer.*;
/**
* Jabber implementation of the incoming file transfer request
*
* @author Nicolas Riegel
* @author Yana Stamcheva
*/
public class IncomingFileTransferRequestJabberImpl
implements IncomingFileTransferRequest
{
/**
* The logger for this class.
*/
private static final Logger logger =
Logger.getLogger(IncomingFileTransferRequestJabberImpl.class);
private String id;
/**
* The Jabber file transfer request.
*/
private final FileTransferRequest fileTransferRequest;
private final OperationSetFileTransferJabberImpl fileTransferOpSet;
private final ProtocolProviderServiceJabberImpl jabberProvider;
private Contact sender;
private String thumbnailCid;
private byte[] thumbnail;
/**
* Creates an <tt>IncomingFileTransferRequestJabberImpl</tt> based on the
* given <tt>fileTransferRequest</tt>, coming from the Jabber protocol.
*
* @param jabberProvider the protocol provider
* @param fileTransferOpSet file transfer operation set
* @param fileTransferRequest the request coming from the Jabber protocol
*/
public IncomingFileTransferRequestJabberImpl(
ProtocolProviderServiceJabberImpl jabberProvider,
OperationSetFileTransferJabberImpl fileTransferOpSet,
FileTransferRequest fileTransferRequest)
{
this.jabberProvider = jabberProvider;
this.fileTransferOpSet = fileTransferOpSet;
this.fileTransferRequest = fileTransferRequest;
String fromUserID
= fileTransferRequest.getRequestor();
OperationSetPersistentPresenceJabberImpl opSetPersPresence
= (OperationSetPersistentPresenceJabberImpl)
jabberProvider
.getOperationSet(OperationSetPersistentPresence.class);
sender = opSetPersPresence.findContactByID(fromUserID);
if(sender == null)
{
ChatRoom privateContactRoom
= ((OperationSetMultiUserChatJabberImpl)
jabberProvider.getOperationSet(
OperationSetMultiUserChat.class))
.getChatRoom(StringUtils.parseBareAddress(fromUserID));
if(privateContactRoom != null)
{
sender = ((OperationSetPersistentPresenceJabberImpl)
jabberProvider.getOperationSet(
OperationSetPersistentPresence.class))
.createVolatileContact(fromUserID, true);
privateContactRoom.updatePrivateContactPresenceStatus(sender);
}
}
this.id = String.valueOf( System.currentTimeMillis())
+ String.valueOf(hashCode());
}
/**
* Returns the <tt>Contact</tt> making this request.
*
* @return the <tt>Contact</tt> making this request
*/
public Contact getSender()
{
return sender;
}
/**
* Returns the description of the file corresponding to this request.
*
* @return the description of the file corresponding to this request
*/
public String getFileDescription()
{
return fileTransferRequest.getDescription();
}
/**
* Returns the name of the file corresponding to this request.
*
* @return the name of the file corresponding to this request
*/
public String getFileName()
{
return fileTransferRequest.getFileName();
}
/**
* Returns the size of the file corresponding to this request.
*
* @return the size of the file corresponding to this request
*/
public long getFileSize()
{
return fileTransferRequest.getFileSize();
}
/**
* Accepts the file and starts the transfer.
*
* @return a boolean : <code>false</code> if the transfer fails,
* <code>true</code> otherwise
*/
public FileTransfer acceptFile(File file)
{
AbstractFileTransfer incomingTransfer = null;
IncomingFileTransfer jabberTransfer = fileTransferRequest.accept();
try
{
incomingTransfer
= new IncomingFileTransferJabberImpl(
id, sender, file, jabberTransfer);
FileTransferCreatedEvent event
= new FileTransferCreatedEvent(incomingTransfer, new Date());
fileTransferOpSet.fireFileTransferCreated(event);
jabberTransfer.recieveFile(file);
new OperationSetFileTransferJabberImpl
.FileTransferProgressThread(
jabberTransfer, incomingTransfer, getFileSize()).start();
}
catch (XMPPException e)
{
if (logger.isDebugEnabled())
logger.debug("Receiving file failed.", e);
}
return incomingTransfer;
}
/**
* Refuses the file transfer request.
*/
public void rejectFile()
{
fileTransferRequest.reject();
fileTransferOpSet.fireFileTransferRequestRejected(
new FileTransferRequestEvent(fileTransferOpSet, this, new Date()));
}
/**
* The unique id.
* @return the id.
*/
public String getID()
{
return id;
}
/**
* Returns the thumbnail contained in this request.
*
* @return the thumbnail contained in this request
*/
public byte[] getThumbnail()
{
return thumbnail;
}
/**
* Sets the thumbnail content-ID.
* @param cid the thumbnail content-ID
*/
public void createThumbnailListeners(String cid)
{
this.thumbnailCid = cid;
if (jabberProvider.getConnection() != null)
{
jabberProvider.getConnection().addPacketListener(
new ThumbnailResponseListener(),
new AndFilter( new PacketTypeFilter(IQ.class),
new IQTypeFilter(IQ.Type.RESULT)));
}
}
/**
* The <tt>ThumbnailResponseListener</tt> listens for events triggered by
* the reception of a <tt>ThumbnailIQ</tt> packet. The packet is examined
* and a file transfer request event is fired when the thumbnail is
* extracted.
*/
private class ThumbnailResponseListener implements PacketListener
{
public void processPacket(Packet packet)
{
// If this is not an IQ packet, we're not interested.
if (!(packet instanceof ThumbnailIQ))
return;
if (logger.isDebugEnabled())
logger.debug("Thumbnail response received.");
ThumbnailIQ thumbnailResponse = (ThumbnailIQ) packet;
if (thumbnailResponse.getCid() != null
&& thumbnailResponse.getCid().equals(thumbnailCid))
{
thumbnail = thumbnailResponse.getData();
// Create an event associated to this global request.
FileTransferRequestEvent fileTransferRequestEvent
= new FileTransferRequestEvent(
fileTransferOpSet,
IncomingFileTransferRequestJabberImpl.this,
new Date());
// Notify the global listener that a request has arrived.
fileTransferOpSet.fireFileTransferRequest(
fileTransferRequestEvent);
}
else
{
//TODO: RETURN <item-not-found/>
}
if (jabberProvider.getConnection() != null)
{
jabberProvider.getConnection()
.removePacketListener(this);
}
}
}
}
| lgpl-2.1 |
treejames/Android-Image-Cache | src/edu/mit/mobile/android/imagecache/DiskCache.java | 9127 | package edu.mit.mobile.android.imagecache;
/*
* Copyright (C) 2011 MIT Mobile Experience Lab
*
* 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
*/
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import android.util.Log;
/**
* A simple disk cache.
*
* @author <a href="mailto:spomeroy@mit.edu">Steve Pomeroy</a>
*
* @param <K>
* the key to store/retrieve the value
* @param <V>
* the value that will be stored to disk
*/
// TODO add automatic cache cleanup so low disk conditions can be met
public abstract class DiskCache<K, V> {
private static final String TAG = "DiskCache";
private MessageDigest hash;
private final File mCacheBase;
private final String mCachePrefix, mCacheSuffix;
/**
* Creates a new disk cache with no cachePrefix or cacheSuffix
*
* @param cacheBase
*/
public DiskCache(File cacheBase) {
this(cacheBase, null, null);
}
/**
* Creates a new disk cache.
*
* @param cacheBase
* The base directory within which all the cache files will be stored.
* @param cachePrefix
* If you want a prefix to the filenames, place one here. Otherwise, pass null.
* @param cacheSuffix
* A suffix to the cache filename. Null is also ok here.
*/
public DiskCache(File cacheBase, String cachePrefix, String cacheSuffix) {
mCacheBase = cacheBase;
mCachePrefix = cachePrefix;
mCacheSuffix = cacheSuffix;
try {
hash = MessageDigest.getInstance("SHA-1");
} catch (final NoSuchAlgorithmException e) {
try {
hash = MessageDigest.getInstance("MD5");
} catch (final NoSuchAlgorithmException e2) {
final RuntimeException re = new RuntimeException("No available hashing algorithm");
re.initCause(e2);
throw re;
}
}
}
/**
* Gets the cache filename for the given key.
*
* @param key
* @return
*/
protected File getFile(K key) {
return new File(mCacheBase, (mCachePrefix != null ? mCachePrefix : "") + hash(key)
+ (mCacheSuffix != null ? mCacheSuffix : ""));
}
/**
* Writes the value stored in the cache to disk by calling
* {@link #toDisk(Object, Object, OutputStream)}.
*
* @param key
* The key to find the value.
* @param value
* the data to be written to disk.
*/
public synchronized void put(K key, V value) throws IOException, FileNotFoundException {
final File saveHere = getFile(key);
final OutputStream os = new FileOutputStream(saveHere);
toDisk(key, value, os);
os.close();
}
/**
* Writes the contents of the InputStream straight to disk. It is the caller's responsibility to
* ensure it's the same type as what would be written with
* {@link #toDisk(Object, Object, OutputStream)}
*
* @param key
* @param value
* @throws IOException
* @throws FileNotFoundException
*/
public void putRaw(K key, InputStream value) throws IOException, FileNotFoundException {
final File saveHere = getFile(key);
final File tempFile = new File(saveHere.getAbsolutePath() + ".temp");
boolean allGood = false;
try {
final OutputStream os = new FileOutputStream(tempFile);
inputStreamToOutputStream(value, os);
os.close();
synchronized (this) {
// overwrite
saveHere.delete();
tempFile.renameTo(saveHere);
}
allGood = true;
} finally {
// clean up on any exception
if (!allGood) {
saveHere.delete();
tempFile.delete();
}
}
}
/**
* Reads from an inputstream, dumps to an outputstream
*
* @param is
* @param os
* @throws IOException
*/
static public void inputStreamToOutputStream(InputStream is, OutputStream os)
throws IOException {
final int bufsize = 8196 * 10;
final byte[] cbuf = new byte[bufsize];
for (int readBytes = is.read(cbuf, 0, bufsize); readBytes > 0; readBytes = is.read(cbuf, 0,
bufsize)) {
os.write(cbuf, 0, readBytes);
}
}
/**
* Reads the value from disk using {@link #fromDisk(Object, InputStream)}.
*
* @param key
* @return The value for key or null if the key doesn't map to any existing entries.
*/
public synchronized V get(K key) throws IOException {
final File readFrom = getFile(key);
if (!readFrom.exists()) {
return null;
}
final InputStream is = new FileInputStream(readFrom);
final V out = fromDisk(key, is);
is.close();
return out;
}
/**
* Checks the disk cache for a given key.
*
* @param key
* @return true if the disk cache contains the given key
*/
public synchronized boolean contains(K key) {
final File readFrom = getFile(key);
return readFrom.exists();
}
/**
* Removes the item from the disk cache.
*
* @param key
* @return true if the cached item has been removed or was already removed, false if it was not
* able to be removed.
*/
public synchronized boolean clear(K key) {
final File readFrom = getFile(key);
if (!readFrom.exists()) {
return true;
}
return readFrom.delete();
}
/**
* Clears the cache files from disk.
*
* Note: this only clears files that match the given prefix/suffix.
*
* @return true if the operation succeeded without error. It is possible that it will fail and
* the cache ends up being partially cleared.
*/
public synchronized boolean clear() {
boolean success = true;
for (final File cacheFile : mCacheBase.listFiles(mCacheFileFilter)) {
if (!cacheFile.delete()) {
// throw new IOException("cannot delete cache file");
Log.e(TAG, "error deleting " + cacheFile);
success = false;
}
}
return success;
}
/**
* @return the size of the cache as it is on disk.
*/
public int getCacheSize() {
return mCacheBase.listFiles(mCacheFileFilter).length;
}
private final CacheFileFilter mCacheFileFilter = new CacheFileFilter();
private class CacheFileFilter implements FileFilter {
@Override
public boolean accept(File pathname) {
final String path = pathname.getName();
return (mCachePrefix != null ? path.startsWith(mCachePrefix) : true)
&& (mCacheSuffix != null ? path.endsWith(mCacheSuffix) : true);
}
};
/**
* Implement this to do the actual disk writing. Do not close the OutputStream; it will be
* closed for you.
*
* @param key
* @param in
* @param out
*/
protected abstract void toDisk(K key, V in, OutputStream out);
/**
* Implement this to do the actual disk reading.
*
* @param key
* @param in
* @return a new instance of {@link V} containing the contents of in.
*/
protected abstract V fromDisk(K key, InputStream in);
/**
* Using the key's {@link Object#toString() toString()} method, generates a string suitable for
* using as a filename.
*
* @param key
* @return a string uniquely representing the the key.
*/
public String hash(K key) {
final byte[] ba;
synchronized (hash) {
hash.update(key.toString().getBytes());
ba = hash.digest();
}
final BigInteger bi = new BigInteger(1, ba);
final String result = bi.toString(16);
if (result.length() % 2 != 0) {
return "0" + result;
}
return result;
}
}
| lgpl-2.1 |
rFlex/SCJavaTools | src/main/java/me/corsin/javatools/exception/StackTraceUtils.java | 763 | package me.corsin.javatools.exception;
import java.io.PrintWriter;
import java.io.StringWriter;
public class StackTraceUtils {
public static String stackTraceToString(Throwable t) {
if (t != null) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
t.printStackTrace(pw);
return sw.toString();
} else {
return null;
}
}
public static String stackTraceToHTMLString(Throwable t) {
return stackTraceToHTMLString(t, " ", "<br>");
}
public static String stackTraceToHTMLString(Throwable t, String tab, String newLine) {
String text = stackTraceToString(t);
if (text == null) {
return null;
} else {
return text.replace("\n", newLine)
.replace("\t", tab);
}
}
}
| lgpl-2.1 |
lat-lon/deegree2-base | deegree2-core/src/main/java/org/deegree/ogcwebservices/wass/wss/operation/RequestParameter.java | 2167 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.ogcwebservices.wass.wss.operation;
/**
* Encapsulate the requestparameter of a DoServiceRequest.
*
* @author <a href="mailto:bezema@lat-lon.de">Rutger Bezema</a>
* @author last edited by: $Author$
*
* @version 2.0, $Revision$, $Date$
*
* @since 2.0
*/
public class RequestParameter {
private String parameter = null;
private String id = null;
/**
* @param parameter
* @param id
*/
public RequestParameter( String parameter, String id ) {
this.parameter = parameter;
this.id = id;
}
/**
* @return Returns the id.
*/
public String getId() {
return id;
}
/**
* @return Returns the parameter.
*/
public String getParameter() {
return parameter;
}
}
| lgpl-2.1 |
Tictim/TTMPMOD | libs_n/gregtech/loaders/oreprocessing/ProcessingStick.java | 1397 | package gregtech.loaders.oreprocessing;
import gregtech.api.enums.GT_Values;
import gregtech.api.enums.Materials;
import gregtech.api.enums.OrePrefixes;
import gregtech.api.util.GT_OreDictUnificator;
import gregtech.api.util.GT_Utility;
import net.minecraft.item.ItemStack;
public class ProcessingStick implements gregtech.api.interfaces.IOreRecipeRegistrator {
public ProcessingStick() {
OrePrefixes.stick.add(this);
}
public void registerOre(OrePrefixes aPrefix, Materials aMaterial, String aOreDictName, String aModName, ItemStack aStack) {
if (!aMaterial.contains(gregtech.api.enums.SubTag.NO_WORKING))
GT_Values.RA.addCutterRecipe(GT_Utility.copyAmount(1L, new Object[]{aStack}), GT_OreDictUnificator.get(OrePrefixes.bolt, aMaterial, 4L), null, (int) Math.max(aMaterial.getMass() * 2L, 1L), 4);
if (!aMaterial.contains(gregtech.api.enums.SubTag.NO_SMASHING)) {
GT_Values.RA.addForgeHammerRecipe(GT_Utility.copyAmount(2L, new Object[]{aStack}), GT_OreDictUnificator.get(OrePrefixes.stickLong, aMaterial, 1L), (int) Math.max(aMaterial.getMass(), 1L), 16);
GT_Values.RA.addWiremillRecipe(GT_Utility.copyAmount(1L, new Object[]{aStack}), GT_Utility.copy(new Object[]{GT_OreDictUnificator.get(OrePrefixes.wireGt01, aMaterial, 1L), GT_OreDictUnificator.get(OrePrefixes.wireFine, aMaterial, 4L)}), 50, 4);
}
}
}
| lgpl-2.1 |
JiriOndrusek/wildfly-core | platform-mbean/src/main/java/org/jboss/as/platform/mbean/RuntimeResourceDefinition.java | 9168 | /*
*
* JBoss, Home of Professional Open Source.
* Copyright 2013, 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.as.platform.mbean;
import static org.jboss.as.platform.mbean.PlatformMBeanConstants.RUNTIME_PATH;
import java.util.Arrays;
import java.util.List;
import org.jboss.as.controller.AttributeDefinition;
import org.jboss.as.controller.SimpleAttributeDefinitionBuilder;
import org.jboss.as.controller.SimpleMapAttributeDefinition;
import org.jboss.as.controller.SimpleResourceDefinition;
import org.jboss.as.controller.StringListAttributeDefinition;
import org.jboss.as.controller.access.management.SensitiveTargetAccessConstraintDefinition;
import org.jboss.as.controller.client.helpers.MeasurementUnit;
import org.jboss.as.controller.operations.global.ReadResourceHandler;
import org.jboss.as.controller.registry.ManagementResourceRegistration;
import org.jboss.dmr.ModelType;
/**
* @author Tomaz Cerar (c) 2013 Red Hat Inc.
*/
class RuntimeResourceDefinition extends SimpleResourceDefinition {
private static AttributeDefinition UPTIME = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.UPTIME, ModelType.LONG, false)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
private static AttributeDefinition START_TIME = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.START_TIME, ModelType.LONG, false)
.setMeasurementUnit(MeasurementUnit.MILLISECONDS)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
//todo convert to proper list! new StringListAttributeDefinition.Builder(PlatformMBeanConstants.SYSTEM_PROPERTIES)
private static AttributeDefinition SYSTEM_PROPERTIES = new SimpleMapAttributeDefinition.Builder(PlatformMBeanConstants.SYSTEM_PROPERTIES,true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.SYSTEM_PROPERTY)
.build();
private static AttributeDefinition INPUT_ARGUMENTS = new StringListAttributeDefinition.Builder(PlatformMBeanConstants.INPUT_ARGUMENTS)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.JVM)
.setRequired(false)
.build();
private static AttributeDefinition VM_NAME = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.VM_NAME, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
private static AttributeDefinition VM_VENDOR = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.VM_VENDOR, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
private static AttributeDefinition VM_VERSION = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.VM_VERSION, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
private static AttributeDefinition SPEC_NAME = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.SPEC_NAME, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
private static AttributeDefinition SPEC_VENDOR = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.SPEC_VENDOR, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
private static AttributeDefinition SPEC_VERSION = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.SPEC_VERSION, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
private static AttributeDefinition MANAGEMENT_SPEC_VERSION = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.MANAGEMENT_SPEC_VERSION, ModelType.STRING, false)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.build();
private static AttributeDefinition CLASS_PATH = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.CLASS_PATH, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.JVM)
.build();
private static AttributeDefinition LIBRARY_PATH = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.LIBRARY_PATH, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.JVM)
.build();
private static AttributeDefinition BOOT_CLASS_PATH_SUPPORTED = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.BOOT_CLASS_PATH_SUPPORTED, ModelType.BOOLEAN, false)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.JVM)
.build();
private static AttributeDefinition BOOT_CLASS_PATH = SimpleAttributeDefinitionBuilder.create(PlatformMBeanConstants.BOOT_CLASS_PATH, ModelType.STRING, true)
.setStorageRuntime()
.setRuntimeServiceNotRequired()
.setAccessConstraints(SensitiveTargetAccessConstraintDefinition.JVM)
.build();
private static final List<AttributeDefinition> METRICS = Arrays.asList(
UPTIME
);
private static final List<AttributeDefinition> READ_ATTRIBUTES = Arrays.asList(
PlatformMBeanConstants.NAME,
VM_NAME,
VM_VENDOR,
VM_VERSION,
SPEC_NAME,
SPEC_VENDOR,
SPEC_VERSION,
MANAGEMENT_SPEC_VERSION,
CLASS_PATH,
LIBRARY_PATH,
BOOT_CLASS_PATH_SUPPORTED,
BOOT_CLASS_PATH,
INPUT_ARGUMENTS,
START_TIME,
SYSTEM_PROPERTIES
);
public static final List<String> RUNTIME_READ_ATTRIBUTES = Arrays.asList(
PlatformMBeanConstants.NAME.getName(),
VM_NAME.getName(),
VM_VENDOR.getName(),
VM_VERSION.getName(),
SPEC_NAME.getName(),
SPEC_VENDOR.getName(),
SPEC_VERSION.getName(),
MANAGEMENT_SPEC_VERSION.getName(),
CLASS_PATH.getName(),
LIBRARY_PATH.getName(),
BOOT_CLASS_PATH_SUPPORTED.getName(),
BOOT_CLASS_PATH.getName(),
INPUT_ARGUMENTS.getName(),
START_TIME.getName(),
SYSTEM_PROPERTIES.getName()
);
public static final List<String> RUNTIME_METRICS = Arrays.asList(
UPTIME.getName()
);
static final RuntimeResourceDefinition INSTANCE = new RuntimeResourceDefinition();
private RuntimeResourceDefinition() {
super(new Parameters(RUNTIME_PATH,
PlatformMBeanUtil.getResolver(PlatformMBeanConstants.RUNTIME)).setRuntime());
}
@Override
public void registerAttributes(ManagementResourceRegistration registration) {
super.registerAttributes(registration);
if (PlatformMBeanUtil.JVM_MAJOR_VERSION > 6) {
registration.registerReadOnlyAttribute(PlatformMBeanConstants.OBJECT_NAME, RuntimeMXBeanAttributeHandler.INSTANCE);
}
for (AttributeDefinition attribute : READ_ATTRIBUTES) {
registration.registerReadOnlyAttribute(attribute, RuntimeMXBeanAttributeHandler.INSTANCE);
}
for (AttributeDefinition attribute : METRICS) {
registration.registerMetric(attribute, RuntimeMXBeanAttributeHandler.INSTANCE);
}
}
@Override
public void registerOperations(ManagementResourceRegistration resourceRegistration) {
super.registerOperations(resourceRegistration);
resourceRegistration.registerOperationHandler(ReadResourceHandler.DEFINITION, RuntimeMXBeanReadResourceHandler.INSTANCE);
}
}
| lgpl-2.1 |
mbatchelor/pentaho-reporting | designer/report-designer/src/main/java/org/pentaho/reporting/designer/core/editor/drilldown/DrillDownParameterTableModel.java | 13488 | /*!
* 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-2017 Hitachi Vantara.. All rights reserved.
*/
package org.pentaho.reporting.designer.core.editor.drilldown;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.pentaho.reporting.designer.core.Messages;
import org.pentaho.reporting.designer.core.editor.drilldown.model.DrillDownParameter;
import org.pentaho.reporting.designer.core.util.table.ElementMetaDataTableModel;
import org.pentaho.reporting.designer.core.util.table.GroupedName;
import org.pentaho.reporting.designer.core.util.table.GroupingHeader;
import org.pentaho.reporting.designer.core.util.table.GroupingModel;
import org.pentaho.reporting.designer.core.util.table.TableStyle;
import org.pentaho.reporting.engine.classic.core.metadata.AttributeMetaData;
import org.pentaho.reporting.libraries.base.util.ObjectUtilities;
import javax.swing.table.AbstractTableModel;
import java.beans.PropertyEditor;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashSet;
public class DrillDownParameterTableModel extends AbstractTableModel
implements ElementMetaDataTableModel, GroupingModel {
private static class PlainParameterComparator implements Comparator {
public int compare( final Object o1, final Object o2 ) {
final DrillDownParameter parameter1 = (DrillDownParameter) o1;
final DrillDownParameter parameter2 = (DrillDownParameter) o2;
if ( parameter1 == null && parameter2 == null ) {
return 0;
}
if ( parameter1 == null ) {
return -1;
}
if ( parameter2 == null ) {
return 1;
}
if ( parameter1.getPosition() < parameter2.getPosition() ) {
return -1;
}
if ( parameter1.getPosition() > parameter2.getPosition() ) {
return 1;
}
return parameter1.getName().compareTo( parameter2.getName() );
}
}
private static class GroupedParameterComparator implements Comparator {
public int compare( final Object o1, final Object o2 ) {
final DrillDownParameter parameter1 = (DrillDownParameter) o1;
final DrillDownParameter parameter2 = (DrillDownParameter) o2;
if ( parameter1 == null && parameter2 == null ) {
return 0;
}
if ( parameter1 == null ) {
return -1;
}
if ( parameter2 == null ) {
return 1;
}
final DrillDownParameter.Type type1 = parameter1.getType();
final DrillDownParameter.Type type2 = parameter2.getType();
final int compareType = type1.compareTo( type2 );
if ( compareType != 0 ) {
return compareType;
}
if ( parameter1.getPosition() < parameter2.getPosition() ) {
return -1;
}
if ( parameter1.getPosition() > parameter2.getPosition() ) {
return 1;
}
return parameter1.getName().compareTo( parameter2.getName() );
}
}
private static final Log logger = LogFactory.getLog( DrillDownParameterTableModel.class );
private static final DrillDownParameter[] EMPTY_ELEMENTS = new DrillDownParameter[ 0 ];
private static final GroupingHeader[] EMPTY_GROUPINGS = new GroupingHeader[ 0 ];
private HashSet filteredParameterNames;
private String[] filteredParameterNamesArray;
private GroupingHeader[] groupings;
private TableStyle tableStyle;
private DrillDownParameter[] elements;
private DrillDownParameter[] groupedElements;
private String[] extraFields;
/**
* Constructs a default <code>DefaultTableModel</code> which is a table of zero columns and zero rows.
*/
public DrillDownParameterTableModel() {
this.filteredParameterNamesArray = new String[ 0 ];
this.filteredParameterNames = new HashSet();
this.tableStyle = TableStyle.GROUPED;
this.elements = EMPTY_ELEMENTS;
this.groupings = EMPTY_GROUPINGS;
this.groupedElements = EMPTY_ELEMENTS;
this.extraFields = new String[ 0 ];
}
public String[] getExtraFields() {
return extraFields.clone();
}
public void setExtraFields( final String[] extraFields ) {
this.extraFields = extraFields.clone();
}
/**
* Returns the number of rows in the model. A <code>JTable</code> uses this method to determine how many rows it
* should display. This method should be quick, as it is called frequently during rendering.
*
* @return the number of rows in the model
* @see #getColumnCount
*/
public int getRowCount() {
return groupedElements.length;
}
/**
* Returns the number of columns in the model. A <code>JTable</code> uses this method to determine how many columns it
* should create and display by default.
*
* @return the number of columns in the model
* @see #getRowCount
*/
public int getColumnCount() {
return 2;
}
/**
* Returns a default name for the column using spreadsheet conventions: A, B, C, ... Z, AA, AB, etc. If
* <code>column</code> cannot be found, returns an empty string.
*
* @param column the column being queried
* @return a string containing the default name of <code>column</code>
*/
public String getColumnName( final int column ) {
if ( column == 0 ) {
return Messages.getString( "DrillDownParameterTable.ParameterName" );
}
return Messages.getString( "DrillDownParameterTable.ParameterValue" );
}
public TableStyle getTableStyle() {
return tableStyle;
}
public void setTableStyle( final TableStyle tableStyle ) {
if ( tableStyle == null ) {
throw new NullPointerException();
}
this.tableStyle = tableStyle;
updateData( getData() );
}
private DrillDownParameter[] filter( final DrillDownParameter[] elements ) {
final ArrayList<DrillDownParameter> retval = new ArrayList<DrillDownParameter>( elements.length );
for ( int i = 0; i < elements.length; i++ ) {
final DrillDownParameter element = elements[ i ];
if ( filteredParameterNames.contains( element.getName() ) ) {
continue;
}
retval.add( element );
}
return retval.toArray( new DrillDownParameter[ retval.size() ] );
}
protected void updateData( final DrillDownParameter[] elements ) {
this.elements = elements.clone();
final DrillDownParameter[] metaData = filter( elements );
if ( tableStyle == TableStyle.ASCENDING ) {
Arrays.sort( metaData, new PlainParameterComparator() );
this.groupings = new GroupingHeader[ metaData.length ];
this.groupedElements = metaData;
} else if ( tableStyle == TableStyle.DESCENDING ) {
Arrays.sort( metaData, Collections.reverseOrder( new PlainParameterComparator() ) );
this.groupings = new GroupingHeader[ metaData.length ];
this.groupedElements = metaData;
} else {
Arrays.sort( metaData, new GroupedParameterComparator() );
int groupCount = 0;
if ( metaData.length > 0 ) {
DrillDownParameter.Type oldValue = null;
for ( int i = 0; i < metaData.length; i++ ) {
if ( groupCount == 0 ) {
groupCount = 1;
final DrillDownParameter firstdata = metaData[ i ];
oldValue = firstdata.getType();
continue;
}
final DrillDownParameter data = metaData[ i ];
final DrillDownParameter.Type grouping = data.getType();
if ( ( ObjectUtilities.equal( oldValue, grouping ) ) == false ) {
oldValue = grouping;
groupCount += 1;
}
}
}
final DrillDownParameter[] groupedMetaData = new DrillDownParameter[ metaData.length + groupCount ];
this.groupings = new GroupingHeader[ groupedMetaData.length ];
int targetIdx = 0;
GroupingHeader group = null;
for ( int sourceIdx = 0; sourceIdx < metaData.length; sourceIdx++ ) {
final DrillDownParameter data = metaData[ sourceIdx ];
if ( sourceIdx == 0 ) {
group = new GroupingHeader( data.getType().toString() );
groupings[ targetIdx ] = group;
targetIdx += 1;
} else {
final String newgroup = data.getType().toString();
if ( ( ObjectUtilities.equal( newgroup, group.getHeaderText() ) ) == false ) {
group = new GroupingHeader( newgroup );
groupings[ targetIdx ] = group;
targetIdx += 1;
}
}
groupings[ targetIdx ] = group;
groupedMetaData[ targetIdx ] = data;
targetIdx += 1;
}
this.groupedElements = groupedMetaData;
}
fireTableDataChanged();
}
/**
* Returns the value for the cell at <code>columnIndex</code> and <code>rowIndex</code>.
*
* @param rowIndex the row whose value is to be queried
* @param columnIndex the column whose value is to be queried
* @return the value Object at the specified cell
*/
public Object getValueAt( final int rowIndex, final int columnIndex ) {
final DrillDownParameter metaData = groupedElements[ rowIndex ];
if ( metaData == null ) {
return groupings[ rowIndex ];
}
switch( columnIndex ) {
case 0:
return new GroupedName( metaData, metaData.getName(), metaData.getType().toString() );
case 1:
return metaData.getFormulaFragment();
default:
throw new IndexOutOfBoundsException();
}
}
/**
* Returns false. This is the default implementation for all cells.
*
* @param rowIndex the row being queried
* @param columnIndex the column being queried
* @return false
*/
public boolean isCellEditable( final int rowIndex, final int columnIndex ) {
final DrillDownParameter metaData = groupedElements[ rowIndex ];
if ( metaData == null ) {
return false;
}
switch( columnIndex ) {
case 0:
return metaData.getType() == DrillDownParameter.Type.MANUAL;
case 1:
return true;
default:
throw new IndexOutOfBoundsException();
}
}
public void setValueAt( final Object aValue, final int rowIndex, final int columnIndex ) {
final DrillDownParameter metaData = groupedElements[ rowIndex ];
if ( metaData == null ) {
return;
}
switch( columnIndex ) {
case 0:
if ( aValue instanceof GroupedName ) {
final GroupedName name = (GroupedName) aValue;
metaData.setName( name.getName() );
fireTableDataChanged();
}
return;
case 1: {
if ( aValue == null ) {
metaData.setFormulaFragment( null );
} else {
metaData.setFormulaFragment( String.valueOf( aValue ) );
}
fireTableDataChanged();
break;
}
default:
throw new IndexOutOfBoundsException();
}
}
public Class getClassForCell( final int row, final int column ) {
final DrillDownParameter metaData = groupedElements[ row ];
if ( metaData == null ) {
return GroupingHeader.class;
}
if ( column == 0 ) {
return GroupedName.class;
}
return String.class;
}
public PropertyEditor getEditorForCell( final int row, final int column ) {
return null;
}
public String getValueRole( final int row, final int column ) {
if ( column == 0 ) {
return AttributeMetaData.VALUEROLE_VALUE; // NON-NLS
}
return AttributeMetaData.VALUEROLE_FORMULA;// NON-NLS
}
public String[] getExtraFields( final int row, final int column ) {
return extraFields;
}
public GroupingHeader getGroupHeader( final int index ) {
return groupings[ index ];
}
public boolean isHeaderRow( final int index ) {
return groupedElements[ index ] == null;
}
public String[] getFilteredParameterNames() {
return filteredParameterNamesArray.clone();
}
public void setFilteredParameterNames( final String[] names ) {
this.filteredParameterNamesArray = names.clone();
this.filteredParameterNames.clear();
this.filteredParameterNames.addAll( Arrays.asList( names ) );
updateData( elements );
}
public void setData( final DrillDownParameter[] parameter ) {
updateData( parameter );
}
public DrillDownParameter[] getData() {
return elements.clone();
}
public DrillDownParameter[] getGroupedData() {
return groupedElements.clone();
}
public DrillDownParameter.Type getParameterType( final int row ) {
final DrillDownParameter downParameter = groupedElements[ row ];
if ( downParameter != null ) {
return downParameter.getType();
}
return null;
}
public boolean isPreferred( final int row ) {
final DrillDownParameter downParameter = groupedElements[ row ];
if ( downParameter != null ) {
return downParameter.isPreferred();
}
return true;
}
}
| lgpl-2.1 |
mcarniel/oswing | src/org/openswing/swing/table/columns/client/CheckBoxColumnBeanInfo.java | 3319 | package org.openswing.swing.table.columns.client;
import java.beans.*;
import org.openswing.swing.client.*;
/**
* <p>Title: Benetton - Gestione Imballi</p>
* <p>Description: </p>
* <p>Copyright: Copyright (c) 2005 Benetton spa</p>
* <p>Company: Tecnoinformatica spa</p>
* @author Mauro Carniel
* @version 1.0
*/
public class CheckBoxColumnBeanInfo extends SimpleBeanInfo {
private Class beanClass = CheckBoxColumn.class;
private String iconColor16x16Filename = "CheckBoxColumn16.png";
private String iconColor32x32Filename = "CheckBoxColumn.png";
private String iconMono16x16Filename = "CheckBoxColumn16.png";
private String iconMono32x32Filename = "CheckBoxColumn.png";
public CheckBoxColumnBeanInfo() {
}
public PropertyDescriptor[] getPropertyDescriptors() {
try {
PropertyDescriptor _allowNullValue = new PropertyDescriptor("allowNullValue", beanClass, "isAllowNullValue", "setAllowNullValue");
PropertyDescriptor _columnName = new PropertyDescriptor("columnName", beanClass, "getColumnName", "setColumnName");
_columnName.setPropertyEditorClass(BooleanAttributeNameEditor.class);
PropertyDescriptor _showDeSelectAllInPopupMenu = new PropertyDescriptor("showDeSelectAllInPopupMenu", beanClass, "isShowDeSelectAllInPopupMenu", "setShowDeSelectAllInPopupMenu");
PropertyDescriptor _deSelectAllCells = new PropertyDescriptor("deSelectAllCells", beanClass, "isDeSelectAllCells", "setDeSelectAllCells");
PropertyDescriptor _enableInReadOnlyMode = new PropertyDescriptor("enableInReadOnlyMode", beanClass, "isEnableInReadOnlyMode", "setEnableInReadOnlyMode");
PropertyDescriptor _negativeValue = new PropertyDescriptor("negativeValue", beanClass, "getNegativeValue", "setNegativeValue");
PropertyDescriptor _positiveValue = new PropertyDescriptor("positiveValue", beanClass, "getPositiveValue", "setPositiveValue");
PropertyDescriptor[] pds = new PropertyDescriptor[] {
_allowNullValue,
_columnName,
_deSelectAllCells,
_enableInReadOnlyMode,
_negativeValue,
_positiveValue,
_showDeSelectAllInPopupMenu
};
return pds;
}
catch(IntrospectionException ex) {
ex.printStackTrace();
return null;
}
}
public java.awt.Image getIcon(int iconKind) {
switch (iconKind) {
case BeanInfo.ICON_COLOR_16x16:
return iconColor16x16Filename != null ? loadImage(iconColor16x16Filename) : null;
case BeanInfo.ICON_COLOR_32x32:
return iconColor32x32Filename != null ? loadImage(iconColor32x32Filename) : null;
case BeanInfo.ICON_MONO_16x16:
return iconMono16x16Filename != null ? loadImage(iconMono16x16Filename) : null;
case BeanInfo.ICON_MONO_32x32:
return iconMono32x32Filename != null ? loadImage(iconMono32x32Filename) : null;
}
return null;
}
public BeanInfo[] getAdditionalBeanInfo() {
Class superclass = beanClass.getSuperclass();
try {
BeanInfo superBeanInfo = Introspector.getBeanInfo(superclass);
return new BeanInfo[] { superBeanInfo };
}
catch(IntrospectionException ex) {
ex.printStackTrace();
return null;
}
}
}
| lgpl-2.1 |
JoseluGames/MinecraftModdingDoneRight | src/main/java/com/jlgm/mmdr/block/BlockExampleHalfSlab.java | 1029 | package com.jlgm.mmdr.block;
import net.minecraft.block.BlockSlab;
import net.minecraft.block.material.Material;
import net.minecraft.block.properties.IProperty;
import net.minecraft.block.properties.PropertyBool;
import net.minecraft.block.state.IBlockState;
import net.minecraft.item.ItemStack;
public class BlockExampleHalfSlab extends BlockExampleSlab{
public BlockExampleHalfSlab(Material materialIn) {
super(materialIn);
IBlockState blockState = this.blockState.getBaseState();
blockState = blockState.withProperty(VARIANT_PROPERTY, false);
if(!this.isDouble()){
blockState = blockState.withProperty(HALF, EnumBlockHalf.BOTTOM);
}
this.setDefaultState(blockState);
}
@Override
public String getUnlocalizedName(int meta) {
return this.getUnlocalizedName();
}
@Override
public boolean isDouble() {
return false;
}
@Override
public IProperty<?> getVariantProperty() {
return VARIANT_PROPERTY;
}
@Override
public Comparable<?> getTypeForItem(ItemStack stack) {
return null;
}
}
| lgpl-2.1 |
maxbiostat/beast-mcmc | src/dr/app/bss/PartitionData.java | 35609 | /*
* PartitionData.java
*
* Copyright (c) 2002-2015 Alexei Drummond, Andrew Rambaut and Marc Suchard
*
* This file is part of BEAST.
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership and licensing.
*
* BEAST 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.
*
* BEAST 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 BEAST; if not, write to the
* Free Software Foundation, Inc., 51 Franklin St, Fifth Floor,
* Boston, MA 02110-1301 USA
*/
package dr.app.bss;
import java.io.Serializable;
import dr.evomodel.branchmodel.BranchModel;
import dr.evomodel.branchmodel.HomogeneousBranchModel;
import dr.evomodel.siteratemodel.GammaSiteRateModel;
import dr.evomodel.substmodel.EmpiricalRateMatrix;
import dr.evomodel.substmodel.FrequencyModel;
import dr.evomodel.substmodel.nucleotide.GTR;
import dr.evomodel.substmodel.codon.GY94CodonModel;
import dr.evomodel.substmodel.nucleotide.HKY;
import dr.evomodel.substmodel.codon.MG94HKYCodonModel;
import dr.evomodel.substmodel.nucleotide.TN93;
import dr.evolution.coalescent.CoalescentSimulator;
import dr.evolution.coalescent.ConstantPopulation;
import dr.evolution.coalescent.DemographicFunction;
import dr.evolution.coalescent.ExponentialGrowth;
import dr.evolution.datatype.AminoAcids;
import dr.evolution.datatype.Codons;
import dr.evolution.datatype.DataType;
import dr.evolution.datatype.Nucleotides;
import dr.evolution.sequence.Sequence;
import dr.evolution.util.Taxa;
import dr.evolution.util.Units;
import dr.evomodel.branchratemodel.BranchRateModel;
import dr.evomodel.branchratemodel.DiscretizedBranchRates;
import dr.evomodel.branchratemodel.StrictClockBranchRates;
import dr.evomodel.substmodel.aminoacid.*;
import dr.oldevomodel.sitemodel.SiteModel;
import dr.evomodel.tree.TreeModel;
import dr.evoxml.TaxaParser;
import dr.inference.distribution.ExponentialDistributionModel;
import dr.inference.distribution.InverseGaussianDistributionModel;
import dr.inference.distribution.LogNormalDistributionModel;
import dr.inference.distribution.ParametricDistributionModel;
import dr.inference.model.Parameter;
import dr.inferencexml.distribution.DistributionModelParser;
import dr.inferencexml.distribution.InverseGaussianDistributionModelParser;
import dr.inferencexml.distribution.LogNormalDistributionModelParser;
/**
* @author Filip Bielejec
* @version $Id$
*/
@SuppressWarnings("serial")
public class PartitionData implements Serializable {
public PartitionData() {
}// END: Constructor
public int from = 1;
public int to = 10;
public int every = 1;
public int createPartitionSiteCount() {
return ((to - from) / every) + 1;
}
public void resetIdrefs() {
resetClockModelIdref();
resetFrequencyModelIdref();
resetSiteRateModelIdref();
resetSubstitutionModelIdref();
resetTreeModelIdref();
resetDemographicModelIdref();
resetTaxaIdref();
}
// ///////////////////////
// ---TREE ANNOTATING---//
// ///////////////////////
// private LinkedHashMap<NodeRef, int[]> sequenceMap;
//
// public void setSequenceMap(LinkedHashMap<NodeRef, int[]> sequenceMap) {
// this.sequenceMap = sequenceMap;
// }
//
// public LinkedHashMap<NodeRef, int[]> getSequenceMap() {
// return sequenceMap;
// }
// /////////////////////////
// ---DEMOGRAPHIC MODEL---//
// /////////////////////////
//TODO: LogisticGrowth.getInverseIntensity
public static final int lastImplementedIndex = 3;
public int demographicModelIndex = 0;
public String demographicModelIdref = Utils.DEMOGRAPHIC_MODEL;
public void resetDemographicModelIdref() {
this.demographicModelIdref = Utils.DEMOGRAPHIC_MODEL;
}
public static String[] demographicModels = {
"No Model (user-specified tree)",
"Constant Population",
"Exponential Growth (Growth Rate)",
"Exponential Growth (Doubling Time)",
// "Logistic Growth (Growth Rate)",
// "Logistic Growth (Doubling Time)",
// "Expansion (Growth Rate)",
// "Expansion (Doubling Time)",
};
public static String[] demographicParameterNames = new String[] {
"Population Size", // Constant Population
"Population Size", // Exponential Growth (Growth Rate)
"Growth Rate", // Exponential Growth (Growth Rate)
"Population Size", // Exponential Growth (Doubling Time)
"Doubling Time", // Exponential Growth (Doubling Time)
// "Population Size", // Logistic Growth (Growth Rate)
// "Growth Rate", // Logistic Growth (Growth Rate)
// "Logistic Shape (Half-life)", // Logistic Growth (Growth Rate)
// "Population Size", // Logistic Growth (Doubling Time)
// "Doubling Time", // Logistic Growth (Doubling Time)
// "Logistic Shape (Half-life)", // Logistic Growth (Doubling Time)
// "Population Size", // Expansion (Growth Rate)
// "Ancestral Proportion", // Expansion (Growth Rate)
// "Growth Rate", // Expansion (Growth Rate)
// "Population Size", // Expansion (Doubling Time)
// "Ancestral Proportion", // Expansion (Doubling Time)
// "Doubling Time", // Expansion (Doubling Time)
};
public static int[][] demographicParameterIndices = {
{ }, // No model
{ 0 }, // Constant Population
{ 1, 2 }, // Exponential Growth (Growth Rate)
{ 3, 4 }, // Exponential Growth (Doubling Time)
// { 5, 6, 7 }, // Logistic Growth (Growth Rate)
// { 8, 9, 10 }, // Logistic Growth (Doubling Time)
// { 11, 12, 13 }, // Expansion (Growth Rate)
// { 14, 15, 16 } // Expansion (Doubling Time)
};
public double[] demographicParameterValues = new double[] {
/*Constant Population*/
1000.0, // Population Size
/*Exponential Growth (Growth Rate)*/
1000.0, // Population Size
0.5, // Growth Rate
/*Exponential Growth (Doubling Time)*/
1000.0, // Population Size
10.0, // Doubling Time
// /*Logistic Growth (Growth Rate)*/
// 1000.0, // Population Size
// 0.5, // Growth Rate
// 50.0, // Logistic Shape (Half-life)
// 1000.0, // Population Size
// 10.0, // Doubling Time
// 50.0, // Logistic Shape (Half-life)
// 1000.0, // Population Size
// 0.1, // Ancestral Proportion
// 0.5, // Growth Rate
// 1000.0, // Population Size
// 0.1, // Ancestral Proportion
// 10.0 // Doubling Time
};
public DemographicFunction createDemographicFunction() {
DemographicFunction demographicFunction = null;
if (this.demographicModelIndex == 0) { // No model
// do nothing
} else if (this.demographicModelIndex == 1) {// Constant Population
demographicFunction = new ConstantPopulation(Units.Type.YEARS);
((ConstantPopulation)demographicFunction).setN0(demographicParameterValues[0]);
} else if (this.demographicModelIndex == 2) {// Exponential Growth (Growth Rate)
demographicFunction = new ExponentialGrowth(Units.Type.YEARS);
((ExponentialGrowth) demographicFunction).setN0(demographicParameterValues[1]);
((ExponentialGrowth) demographicFunction).setGrowthRate(demographicParameterValues[2]);
} else if (this.demographicModelIndex == 3) {// Exponential Growth (Doubling Time)
demographicFunction = new ExponentialGrowth(Units.Type.YEARS);
((ExponentialGrowth) demographicFunction).setN0(demographicParameterValues[3]);
((ExponentialGrowth) demographicFunction).setDoublingTime(demographicParameterValues[4]);
// } else if (this.demographicModelIndex == 4) {// Logistic Growth (Growth Rate)
//
// demographicFunction = new LogisticGrowth(Units.Type.YEARS);
// ((LogisticGrowth) demographicFunction).setN0(demographicParameterValues[5]);
// ((LogisticGrowth) demographicFunction).setGrowthRate(demographicParameterValues[6]);
// ((LogisticGrowth) demographicFunction).setTime50(demographicParameterValues[7]);
//
// } else if (this.demographicModelIndex == 5) {// Logistic Growth (Doubling Time)
//
// demographicFunction = new LogisticGrowth(Units.Type.YEARS);
// ((LogisticGrowth) demographicFunction).setN0(demographicParameterValues[8]);
// ((LogisticGrowth) demographicFunction).setDoublingTime(demographicParameterValues[9]);
// ((LogisticGrowth) demographicFunction).setTime50(demographicParameterValues[10]);
//
// } else if (this.demographicModelIndex == 6) {// Expansion (Growth Rate)
//
// demographicFunction = new Expansion(Units.Type.YEARS);
// ((Expansion) demographicFunction).setN0(demographicParameterValues[11]);
// ((Expansion) demographicFunction).setProportion(demographicParameterValues[12]);
// ((Expansion) demographicFunction).setGrowthRate(demographicParameterValues[13]);
//
// } else if (this.demographicModelIndex == 7) {// Expansion (Doubling Time)
//
// demographicFunction = new Expansion(Units.Type.YEARS);
// ((Expansion) demographicFunction).setN0(demographicParameterValues[14]);
// ((Expansion) demographicFunction).setProportion(demographicParameterValues[15]);
// ((Expansion) demographicFunction).setDoublingTime(demographicParameterValues[16]);
} else {
System.out.println("Not yet implemented");
}
return demographicFunction;
}// END: createDemographicFunction
// ////////////
// ---TAXA---//
// ////////////
public TreesTableRecord record = null;
public String taxaIdref = TaxaParser.TAXA;
public void resetTaxaIdref() {
this.taxaIdref = TaxaParser.TAXA;
}
// //////////////////
// ---TREE MODEL---//
// //////////////////
// public Tree tree = null;
public String treeModelIdref = TreeModel.TREE_MODEL;
public void resetTreeModelIdref() {
this.treeModelIdref = TreeModel.TREE_MODEL;
}
public TreeModel createTreeModel() {
TreeModel treeModel = null;
if (this.demographicModelIndex == 0 && this.record.isTreeSet()) {
treeModel = new TreeModel(this.record.getTree());
} else if( (this.demographicModelIndex > 0 && this.demographicModelIndex <= lastImplementedIndex) && this.record.isTreeSet()) {
Taxa taxa = new Taxa(this.record.getTree().asList());
CoalescentSimulator topologySimulator = new CoalescentSimulator();
treeModel = new TreeModel(topologySimulator.simulateTree(taxa, createDemographicFunction()));
} else if((this.demographicModelIndex > 0 && this.demographicModelIndex <= lastImplementedIndex) && this.record.isTaxaSet()) {
Taxa taxa = this.record.getTaxa();
CoalescentSimulator topologySimulator = new CoalescentSimulator();
treeModel = new TreeModel(topologySimulator.simulateTree(taxa, createDemographicFunction()));
// } else if (this.demographicModelIndex == 0 && this.record.taxaSet) {
// throw new RuntimeException("Data and demographic model incompatible for partition ");
} else {
throw new RuntimeException("Data and demographic model incompatible.");
}// END: demo model check
return treeModel;
}//END: createTreeModel
// /////////////////
// ---DATA TYPE---//
// /////////////////
public int dataTypeIndex = 0;
public static String[] dataTypes = { "Nucleotide", //
"Codon", //
"Amino acid" //
};
public DataType createDataType() {
DataType dataType = null;
if (this.dataTypeIndex == 0) { // Nucleotide
dataType = Nucleotides.INSTANCE;
} else if (this.dataTypeIndex == 1) { // Codon
dataType = Codons.UNIVERSAL;
} else if (this.dataTypeIndex == 2) { // AminoAcid
dataType = AminoAcids.INSTANCE;
} else {
System.out.println("Not yet implemented");
}
return dataType;
}// END: createDataType
// ///////////////////////////
// ---SUBSTITUTION MODELS---//
// ///////////////////////////
public int substitutionModelIndex = 0;
public String substitutionModelIdref = Utils.SUBSTITUTION_MODEL;
public void resetSubstitutionModelIdref() {
this.substitutionModelIdref = Utils.SUBSTITUTION_MODEL;
}
public static String[] substitutionModels = { "HKY", //
"GTR", //
"TN93", //
"GY94CodonModel", //
"MG94CodonModel",
"Blosum62", //
"CPREV", //
"Dayhoff", //
"FLU", //
"JTT", //
"LG", //
"MTREV", //
"WAG" //
};
public static int[] substitutionCompatibleDataTypes = { 0, // HKY
0, // GTR
0, // TN93
1, // GY94CodonModel
1, // MG94CodonModel
2, // Blosum62
2, // CPREV
2, // Dayhoff
2, // FLU
2, // JTT
2, // LG
2, // MTREV
2 // WAG
};
public static String[] substitutionParameterNames = new String[] {
"Kappa value", // HKY
"AC", // GTR
"AG", // GTR
"AT", // GTR
"CG", // GTR
"CT", // GTR
"GT", // GTR
"Kappa 1 (A-G)", // TN93
"Kappa 2 (C-T)", // TN93
"Omega value", // GY94CodonModel
"Kappa value", // GY94CodonModel
"Alpha value", // MG94CodonModel
"Beta value", // MG94CodonModel
"Kappa value" // MG94CodonModel
};
public static int[][] substitutionParameterIndices = { { 0 }, // HKY
{ 1, 2, 3, 4, 5, 6 }, // GTR
{ 7, 8 }, // TN93
{ 9, 10 }, // GY94CodonModel
{11, 12, 13}, // MG94CodonModel
{}, // Blosum62
{}, // CPREV
{}, // Dayhoff
{}, // FLU
{}, // JTT
{}, // LG
{}, // MTREV
{} // WAG
};
public double[] substitutionParameterValues = new double[] { 1.0, // Kappa-value
1.0, // AC
1.0, // AG
1.0, // AT
1.0, // CG
1.0, // CT
1.0, // GT
1.0, // Kappa 1
1.0, // Kappa 2
0.1, // Omega value
1.0, // Kappa value
10.0, // Alpha value
1.0, // Beta value
1.0 // kappa value
};
public BranchModel createBranchModel() {
BranchModel branchModel = null;
if (this.substitutionModelIndex == 0) { // HKY
Parameter kappa = new Parameter.Default(1, substitutionParameterValues[0]);
FrequencyModel frequencyModel = this.createFrequencyModel();
HKY hky = new HKY(kappa, frequencyModel);
branchModel = new HomogeneousBranchModel(hky);
} else if (this.substitutionModelIndex == 1) { // GTR
Parameter ac = new Parameter.Default(1,
substitutionParameterValues[1]);
Parameter ag = new Parameter.Default(1,
substitutionParameterValues[2]);
Parameter at = new Parameter.Default(1,
substitutionParameterValues[3]);
Parameter cg = new Parameter.Default(1,
substitutionParameterValues[4]);
Parameter ct = new Parameter.Default(1,
substitutionParameterValues[5]);
Parameter gt = new Parameter.Default(1,
substitutionParameterValues[6]);
FrequencyModel frequencyModel = this.createFrequencyModel();
GTR gtr = new GTR(ac, ag, at, cg, ct, gt, frequencyModel);
branchModel = new HomogeneousBranchModel(gtr);
} else if (this.substitutionModelIndex == 2) { // TN93
Parameter kappa1 = new Parameter.Default(1,
substitutionParameterValues[7]);
Parameter kappa2 = new Parameter.Default(1,
substitutionParameterValues[8]);
FrequencyModel frequencyModel = this.createFrequencyModel();
TN93 tn93 = new TN93(kappa1, kappa2, frequencyModel);
branchModel = new HomogeneousBranchModel(tn93);
} else if (this.substitutionModelIndex == 3) { // Yang Codon Model
FrequencyModel frequencyModel = this.createFrequencyModel();
Parameter kappa = new Parameter.Default(1,
substitutionParameterValues[9]);
Parameter omega = new Parameter.Default(1,
substitutionParameterValues[10]);
GY94CodonModel yangCodonModel = new GY94CodonModel(
Codons.UNIVERSAL, omega, kappa, frequencyModel);
branchModel = new HomogeneousBranchModel(yangCodonModel);
} else if(this.substitutionModelIndex == 4) { // MG94CodonModel
FrequencyModel frequencyModel = this.createFrequencyModel();
Parameter alpha = new Parameter.Default(1, substitutionParameterValues[11]);
Parameter beta = new Parameter.Default(1, substitutionParameterValues[12]);
Parameter kappa = new Parameter.Default(1, substitutionParameterValues[13]);
MG94HKYCodonModel mg94 = new MG94HKYCodonModel(Codons.UNIVERSAL, alpha, beta, kappa, frequencyModel);
branchModel = new HomogeneousBranchModel(mg94);
} else if (this.substitutionModelIndex == 5) { // Blosum62
FrequencyModel frequencyModel = this.createFrequencyModel();
EmpiricalRateMatrix rateMatrix = Blosum62.INSTANCE;
EmpiricalAminoAcidModel empiricalAminoAcidModel = new EmpiricalAminoAcidModel(
rateMatrix, frequencyModel);
branchModel = new HomogeneousBranchModel(
empiricalAminoAcidModel);
} else if (this.substitutionModelIndex == 6) { // CPREV
FrequencyModel frequencyModel = this.createFrequencyModel();
EmpiricalRateMatrix rateMatrix = CPREV.INSTANCE;
EmpiricalAminoAcidModel empiricalAminoAcidModel = new EmpiricalAminoAcidModel(
rateMatrix, frequencyModel);
branchModel = new HomogeneousBranchModel(
empiricalAminoAcidModel);
} else if (this.substitutionModelIndex == 7) { // Dayhoff
FrequencyModel frequencyModel = this.createFrequencyModel();
EmpiricalRateMatrix rateMatrix = Dayhoff.INSTANCE;
EmpiricalAminoAcidModel empiricalAminoAcidModel = new EmpiricalAminoAcidModel(
rateMatrix, frequencyModel);
branchModel = new HomogeneousBranchModel(
empiricalAminoAcidModel);
} else if (this.substitutionModelIndex == 8) { // JTT
FrequencyModel frequencyModel = this.createFrequencyModel();
EmpiricalRateMatrix rateMatrix = JTT.INSTANCE;
EmpiricalAminoAcidModel empiricalAminoAcidModel = new EmpiricalAminoAcidModel(
rateMatrix, frequencyModel);
branchModel = new HomogeneousBranchModel(
empiricalAminoAcidModel);
} else if (this.substitutionModelIndex == 9) { // LG
FrequencyModel frequencyModel = this.createFrequencyModel();
EmpiricalRateMatrix rateMatrix = LG.INSTANCE;
EmpiricalAminoAcidModel empiricalAminoAcidModel = new EmpiricalAminoAcidModel(
rateMatrix, frequencyModel);
branchModel = new HomogeneousBranchModel(
empiricalAminoAcidModel);
} else if (this.substitutionModelIndex == 10) { // MTREV
FrequencyModel frequencyModel = this.createFrequencyModel();
EmpiricalRateMatrix rateMatrix = MTREV.INSTANCE;
EmpiricalAminoAcidModel empiricalAminoAcidModel = new EmpiricalAminoAcidModel(
rateMatrix, frequencyModel);
branchModel = new HomogeneousBranchModel(
empiricalAminoAcidModel);
} else if (this.substitutionModelIndex == 11) { // WAG
FrequencyModel frequencyModel = this.createFrequencyModel();
EmpiricalRateMatrix rateMatrix = WAG.INSTANCE;
EmpiricalAminoAcidModel empiricalAminoAcidModel = new EmpiricalAminoAcidModel(
rateMatrix, frequencyModel);
branchModel = new HomogeneousBranchModel(
empiricalAminoAcidModel);
} else {
System.out.println("Not yet implemented");
}
return branchModel;
}// END: createBranchSubstitutionModel
// ////////////////////////
// ---FREQUENCY MODELS---//
// ////////////////////////
public String frequencyModelIdref = Utils.FREQUENCY_MODEL;
public void resetFrequencyModelIdref() {
this.frequencyModelIdref = Utils.FREQUENCY_MODEL;
}
public int frequencyModelIndex = 0;
public static String[] frequencyModels = { "Nucleotide frequencies", //
"Codon frequencies", //
"Amino acid frequencies"
};
public static int[] frequencyCompatibleDataTypes = { 0, // Nucleotide
1, // Codon
2 // Amino acid
};
public static String[] frequencyParameterNames = new String[] {
"A frequency", // Nucleotide frequencies
"C frequency", // Nucleotide frequencies
"G frequency", // Nucleotide frequencies
"T frequency", // Nucleotide frequencies
"AAA frequency", // Codon frequencies
"AAC frequency", //
"AAG frequency", //
"AAT frequency", //
"ACA frequency", //
"ACC frequency", //
"ACG frequency", //
"ACT frequency", //
"AGA frequency", //
"AGC frequency", //
"AGG frequency", //
"AGT frequency", //
"ATA frequency", //
"ATC frequency", //
"ATG frequency", //
"ATT frequency", //
"CAA frequency", //
"CAC frequency", //
"CAG frequency", //
"CAT frequency", //
"CCA frequency", //
"CCC frequency", //
"CCG frequency", //
"CCT frequency", //
"CGA frequency", //
"CGC frequency", //
"CGG frequency", //
"CGT frequency", //
"CTA frequency", //
"CTC frequency", //
"CTG frequency", //
"CTT frequency", //
"GAA frequency", //
"GAC frequency", //
"GAG frequency", //
"GAT frequency", //
"GCA frequency", //
"GCC frequency", //
"GCG frequency", //
"GCT frequency", //
"GGA frequency", //
"GGC frequency", //
"GGG frequency", //
"GGT frequency", //
"GTA frequency", //
"GTC frequency", //
"GTG frequency", //
"GTT frequency", //
"TAC frequency", //
"TAT frequency", //
"TCA frequency", //
"TCC frequency", //
"TCG frequency", //
"TCT frequency", //
"TGC frequency", //
"TGG frequency", //
"TGT frequency", //
"TTA frequency", //
"TTC frequency", //
"TTG frequency", //
"TTT frequency", // Codon frequencies
"amino acid frequency 1", //
"amino acid frequency 2", //
"amino acid frequency 3", //
"amino acid frequency 4", //
"amino acid frequency 5", //
"amino acid frequency 6", //
"amino acid frequency 7", //
"amino acid frequency 8", //
"amino acid frequency 9", //
"amino acid frequency 10", //
"amino acid frequency 11", //
"amino acid frequency 12", //
"amino acid frequency 13", //
"amino acid frequency 14", //
"amino acid frequency 15", //
"amino acid frequency 16", //
"amino acid frequency 17", //
"amino acid frequency 18", //
"amino acid frequency 19", //
"amino acid frequency 20" //
};
public int[][] frequencyParameterIndices = { { 0, 1, 2, 3 }, // NucleotideFrequencies
{ 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, //
14, 15, 16, 17, 18, 19, 20, 21, 22, 23, //
24, 25, 26, 27, 28, 29, 30, 31, 32, 33, //
34, 35, 36, 37, 38, 39, 40, 41, 42, 43, //
44, 45, 46, 47, 48, 49, 50, 51, 52, 53, //
54, 55, 56, 57, 58, 59, 60, 61, 62, 63, //
64 }, // CodonFrequencies
{ 65, 66, 67, 68, 69, //
70, 71, 72, 73, 74, //
75, 76, 77, 78, 79, //
80, 81, 82, 83, 84 //
} // AminoAcidFrequencies
};
public double[] frequencyParameterValues = new double[] { 0.25, // A frequency
0.25, // C frequency
0.25, // G frequency
0.25, // T frequency
0.0163936, // AAA frequency
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, //
0.01639344, // TTT frequency
0.05, // aminoacidfrequency1
0.05, // aminoacidfrequency2
0.05, // aminoacidfrequency3
0.05, // aminoacidfrequency4
0.05, // aminoacidfrequency5
0.05, // aminoacidfrequency6
0.05, // aminoacidfrequency7
0.05, // aminoacidfrequency8
0.05, // aminoacidfrequency9
0.05, // aminoacidfrequency10
0.05, // aminoacidfrequency11
0.05, // aminoacidfrequency12
0.05, // aminoacidfrequency13
0.05, // aminoacidfrequency14
0.05, // aminoacidfrequency15
0.05, // aminoacidfrequency16
0.05, // aminoacidfrequency17
0.05, // aminoacidfrequency18
0.05, // aminoacidfrequency19
0.05 // aminoacidfrequency20
};
public FrequencyModel createFrequencyModel() {
FrequencyModel frequencyModel = null;
if (this.frequencyModelIndex == 0) { // Nucleotidefrequencies
Parameter freqs = new Parameter.Default(new double[] {
frequencyParameterValues[0], frequencyParameterValues[1],
frequencyParameterValues[2], frequencyParameterValues[3] });
DataType dataType = this.createDataType();
frequencyModel = new FrequencyModel(dataType, freqs);
} else if (this.frequencyModelIndex == 1) {
Parameter freqs = new Parameter.Default(new double[] {
frequencyParameterValues[4], frequencyParameterValues[5],
frequencyParameterValues[6], frequencyParameterValues[7],
frequencyParameterValues[8], frequencyParameterValues[9],
frequencyParameterValues[10], frequencyParameterValues[11],
frequencyParameterValues[12], frequencyParameterValues[13],
frequencyParameterValues[14], frequencyParameterValues[15],
frequencyParameterValues[16], frequencyParameterValues[17],
frequencyParameterValues[18], frequencyParameterValues[19],
frequencyParameterValues[20], frequencyParameterValues[21],
frequencyParameterValues[22], frequencyParameterValues[23],
frequencyParameterValues[24], frequencyParameterValues[25],
frequencyParameterValues[26], frequencyParameterValues[27],
frequencyParameterValues[28], frequencyParameterValues[29],
frequencyParameterValues[30], frequencyParameterValues[31],
frequencyParameterValues[32], frequencyParameterValues[33],
frequencyParameterValues[34], frequencyParameterValues[35],
frequencyParameterValues[36], frequencyParameterValues[37],
frequencyParameterValues[38], frequencyParameterValues[39],
frequencyParameterValues[40], frequencyParameterValues[41],
frequencyParameterValues[42], frequencyParameterValues[43],
frequencyParameterValues[44], frequencyParameterValues[45],
frequencyParameterValues[46], frequencyParameterValues[47],
frequencyParameterValues[48], frequencyParameterValues[49],
frequencyParameterValues[50], frequencyParameterValues[51],
frequencyParameterValues[52], frequencyParameterValues[53],
frequencyParameterValues[54], frequencyParameterValues[55],
frequencyParameterValues[56], frequencyParameterValues[57],
frequencyParameterValues[58], frequencyParameterValues[59],
frequencyParameterValues[60], frequencyParameterValues[61],
frequencyParameterValues[62], frequencyParameterValues[63],
frequencyParameterValues[64] });
DataType dataType = this.createDataType();
frequencyModel = new FrequencyModel(dataType, freqs);
} else if (this.frequencyModelIndex == 2) {
Parameter freqs = new Parameter.Default(new double[] {
frequencyParameterValues[65], frequencyParameterValues[66], frequencyParameterValues[67], frequencyParameterValues[68],
frequencyParameterValues[69], frequencyParameterValues[70], frequencyParameterValues[71], frequencyParameterValues[72],
frequencyParameterValues[73], frequencyParameterValues[74], frequencyParameterValues[75], frequencyParameterValues[76],
frequencyParameterValues[77], frequencyParameterValues[78], frequencyParameterValues[79], frequencyParameterValues[80],
frequencyParameterValues[81], frequencyParameterValues[82], frequencyParameterValues[83], frequencyParameterValues[84]
});
DataType dataType = this.createDataType();
frequencyModel = new FrequencyModel(dataType, freqs);
} else {
System.out.println("Not yet implemented");
}
return frequencyModel;
}// END: createFrequencyModel
// ////////////////////
// ---CLOCK MODELS---//
// ////////////////////
public int clockModelIndex = 0;
public int LRC_INDEX = 1;
public String clockModelIdref = BranchRateModel.BRANCH_RATES;
public void resetClockModelIdref() {
this.clockModelIdref = BranchRateModel.BRANCH_RATES;
}
public static String[] clockModels = { "Strict Clock", // 0
"Lognormal relaxed clock (Uncorrelated)", // 1
"Exponential relaxed clock (Uncorrelated)", // 2
"Inverse Gaussian relaxed clock" // 3
};
public static String[] clockParameterNames = new String[] { "clock.rate", // StrictClock
"ucld.mean", // Lognormal relaxed clock
"ucld.stdev", // Lognormal relaxed clock
"ucld.offset", // Lognormal relaxed clock
"uced.mean", // Exponential relaxed clock
"uced.offset", // Exponential relaxed clock
"ig.mean", // Inverse Gaussian
"ig.stdev", // Inverse Gaussian
"ig.offset" // Inverse Gaussian
};
public static int[][] clockParameterIndices = { { 0 }, // StrictClock
{ 1, 2, 3 }, // Lognormal relaxed clock
{ 4, 5 }, // Exponential relaxed clock
{ 6, 7, 8 } // Inverse Gaussian
};
public double[] clockParameterValues = new double[] { 1.0, // clockrate
0.001, // ucld.mean
1.0, // ucld.stdev
0.0, // ucld.offset
1.0, // uced.mean
0.0, // uced.offset
0.0, // ig.mean
1.0, // ig.stdev
0.0 // ig.offset
};
public boolean lrcParametersInRealSpace = true;
public BranchRateModel createClockRateModel() {
BranchRateModel branchRateModel = null;
if (this.clockModelIndex == 0) { // Strict Clock
Parameter rateParameter = new Parameter.Default(1, clockParameterValues[0]);
branchRateModel = new StrictClockBranchRates(rateParameter);
} else if (this.clockModelIndex == LRC_INDEX) {// Lognormal relaxed clock
double numberOfBranches = 2 * (createTreeModel().getTaxonCount() - 1);
Parameter rateCategoryParameter = new Parameter.Default(numberOfBranches);
Parameter mean = new Parameter.Default(LogNormalDistributionModelParser.MEAN, 1, clockParameterValues[1]);
Parameter stdev = new Parameter.Default(LogNormalDistributionModelParser.STDEV, 1, clockParameterValues[2]);
//TODO: choose between log scale / real scale
ParametricDistributionModel distributionModel = new LogNormalDistributionModel(mean, stdev, clockParameterValues[3], lrcParametersInRealSpace);
branchRateModel = new DiscretizedBranchRates(createTreeModel(), //
rateCategoryParameter, //
distributionModel, //
1, //
false, //
Double.NaN, //
true, //randomizeRates
false, // keepRates
false // cacheRates
);
} else if(this.clockModelIndex == 2) { // Exponential relaxed clock
double numberOfBranches = 2 * (createTreeModel().getTaxonCount() - 1);
Parameter rateCategoryParameter = new Parameter.Default(numberOfBranches);
Parameter mean = new Parameter.Default(DistributionModelParser.MEAN, 1, clockParameterValues[4]);
ParametricDistributionModel distributionModel = new ExponentialDistributionModel(mean, clockParameterValues[5]);
// branchRateModel = new DiscretizedBranchRates(createTreeModel(), rateCategoryParameter,
// distributionModel, 1, false, Double.NaN);
branchRateModel = new DiscretizedBranchRates(createTreeModel(), //
rateCategoryParameter, //
distributionModel, //
1, //
false, //
Double.NaN, //
true, //randomizeRates
false, // keepRates
false // cacheRates
);
} else if(this.clockModelIndex == 3) { // Inverse Gaussian
double numberOfBranches = 2 * (createTreeModel().getTaxonCount() - 1);
Parameter rateCategoryParameter = new Parameter.Default(numberOfBranches);
Parameter mean = new Parameter.Default(InverseGaussianDistributionModelParser.MEAN, 1, clockParameterValues[6]);
Parameter stdev = new Parameter.Default(InverseGaussianDistributionModelParser.STDEV, 1, clockParameterValues[7]);
ParametricDistributionModel distributionModel = new InverseGaussianDistributionModel(
mean, stdev, clockParameterValues[8], false);
branchRateModel = new DiscretizedBranchRates(createTreeModel(), //
rateCategoryParameter, //
distributionModel, //
1, //
false, //
Double.NaN, //
true, //randomizeRates
false, // keepRates
false // cacheRates
);
} else {
System.out.println("Not yet implemented");
}
return branchRateModel;
}// END: createBranchRateModel
// ///////////////////////
// ---SITE RATE MODEL---//
// ///////////////////////
public int siteRateModelIndex = 0;
public String siteRateModelIdref = SiteModel.SITE_MODEL;
public void resetSiteRateModelIdref() {
this.siteRateModelIdref = SiteModel.SITE_MODEL;
}
public static String[] siteRateModels = { "No Model", //
"Gamma Site Rate Model" //
};
public static String[] siteRateModelParameterNames = new String[] {
"Gamma categories", // Gamma Site Rate Model
"Alpha", // Gamma Site Rate Model
"Invariant sites proportion" // Gamma Site Rate Model
};
public static int[][] siteRateModelParameterIndices = { {}, // NoModel
{ 0, 1, 2 }, // GammaSiteRateModel
};
public double[] siteRateModelParameterValues = new double[] { 4.0, // GammaCategories
0.5, // Alpha
0.0 // Invariant sites proportion
};
public GammaSiteRateModel createSiteRateModel() {
GammaSiteRateModel siteModel = null;
String name = "siteModel";
if (this.siteRateModelIndex == 0) { // no model
siteModel = new GammaSiteRateModel(name);
} else if (this.siteRateModelIndex == 1) { // GammaSiteRateModel
siteModel = new GammaSiteRateModel(name,
siteRateModelParameterValues[1],
(int) siteRateModelParameterValues[0], siteRateModelParameterValues[2]);
} else {
System.out.println("Not yet implemented");
}
return siteModel;
}// END: createGammaSiteRateModel
// //////////////////////////
// ---ANCESTRAL SEQUENCE---//
// //////////////////////////
public String ancestralSequenceString = null;
public Sequence createAncestralSequence() {
Sequence sequence = new Sequence(ancestralSequenceString);
// sequence.appendSequenceString(ancestralSequenceString);
return sequence;
}
}// END: class
| lgpl-2.1 |
lat-lon/deegree2-base | deegree2-core/src/main/java/org/deegree/ogcwebservices/wfs/capabilities/WFSOperationsMetadata.java | 9771 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.ogcwebservices.wfs.capabilities;
import java.util.ArrayList;
import java.util.List;
import org.deegree.ogcwebservices.getcapabilities.Operation;
import org.deegree.ogcwebservices.getcapabilities.OperationsMetadata;
import org.deegree.owscommon.OWSDomainType;
/**
* Represents the <code>OperationMetadata</code> part in the capabilities document of a WFS
* according to the <code>Web Feature Service Implementation Specification 1.1.0</code>.
* <p>
* In addition to the <code>GetCapabilities</code> operation that all <code>OWS 0.3</code>
* compliant services must implement, it may define some or all of the following operations: <table
* border="1">
* <tr>
* <th>Name</th>
* <th>Mandatory?</th>
* <th>Function</th>
* </tr>
* <tr>
* <td><code>DescribeFeatureType</code></td>
* <td align="center">X</td>
* <td>The function of the <code>DescribeFeatureType</code> operation is to generate a schema
* description of feature types serviced by a WFS implementation.</td>
* </tr>
* <tr>
* <td><code>GetFeature</code></td>
* <td align="center">X</td>
* <td>The <code>GetFeature</code> operation allows retrieval of features from a web feature
* service.</td>
* </tr>
* <tr>
* <td><code>GetFeatureWithLock</code></td>
* <td align="center">-</td>
* <td>The lock action of the <code>GetFeatureWithLock</code> request is to attempt to lock all
* identified feature instances. If all identified feature instances cannot be locked, then an
* exception report should be generated.</td>
* </tr>
* <tr>
* <td><code>GetGMLObject</code></td>
* <td align="center">-</td>
* <td>The <code>GetGMLObject</code> operation allows retrieval of features and elements by ID
* from a web feature service.</td>
* </tr>
* <tr>
* <td><code>LockFeature</code></td>
* <td align="center">-</td>
* <td>The purpose of the <code>LockFeature</code> operation is to expose a long term feature
* locking mechanism to ensure consistency. The lock is considered long term because network latency
* would make feature locks last relatively longer than native commercial database locks.</td>
* </tr>
* <tr>
* <td><code>Transaction</code></td>
* <td align="center">-</td>
* <td>The <code>Transaction</code> operation is used to describe data transformation operations
* that are to be applied to web accessible feature instances. When the transaction has been
* completed, a web feature service will generate an XML response document indicating the completion
* status of the transaction.</td>
* </tr>
* </table>
*
* @see org.deegree.ogcwebservices.getcapabilities.OperationsMetadata
* @author <a href="mailto:poth@lat-lon.de">Andreas Poth </a>
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*/
public class WFSOperationsMetadata extends OperationsMetadata {
private static final long serialVersionUID = -3953425919713834071L;
/**
*
*/
public static final String DESCRIBE_FEATURETYPE_NAME = "DescribeFeatureType";
/**
*
*/
public static final String GET_FEATURE_NAME = "GetFeature";
/**
*
*/
public static final String GET_FEATURE_WITH_LOCK_NAME = "GetFeatureWithLock";
/**
*
*/
public static final String GET_GML_OBJECT_NAME = "GetGmlObject";
/**
*
*/
public static final String LOCK_FEATURE_NAME = "LockFeature";
/**
*
*/
public static final String TRANSACTION_NAME = "Transaction";
private Operation describeFeatureType;
private Operation getFeature;
private Operation getFeatureWithLock;
private Operation getGMLObject;
private Operation lockFeature;
private Operation transaction;
/**
* Constructs a new <code>WFSOperationsMetadata</code> instance from the given parameters.
*
* @param getCapabilities
* @param describeFeatureType
* @param getFeature
* @param getFeatureWithLock
* optional operation (may be null)
* @param getGMLObject
* optional operation (may be null)
* @param lockFeature
* optional operation (may be null)
* @param transaction
* optional operation (may be null)
* @param parameters
* @param constraints
*/
public WFSOperationsMetadata( Operation getCapabilities, Operation describeFeatureType,
Operation getFeature, Operation getFeatureWithLock,
Operation getGMLObject, Operation lockFeature,
Operation transaction, OWSDomainType[] parameters,
OWSDomainType[] constraints ) {
super( getCapabilities, parameters, constraints );
this.describeFeatureType = describeFeatureType;
this.getFeature = getFeature;
this.getFeatureWithLock = getFeatureWithLock;
this.getGMLObject = getGMLObject;
this.lockFeature = lockFeature;
this.transaction = transaction;
}
/**
* Returns all <code>Operations</code> known to the WFS.
*
* @return all <code>Operations</code> known to the WFS.
*/
@Override
public Operation[] getOperations() {
List<Operation> list = new ArrayList<Operation>( 10 );
list.add( getFeature );
list.add( describeFeatureType );
list.add( getCapabilitiesOperation );
if ( getFeatureWithLock != null ) {
list.add( getFeatureWithLock );
}
if ( getGMLObject != null ) {
list.add( getGMLObject );
}
if ( lockFeature != null ) {
list.add( lockFeature );
}
if ( transaction != null ) {
list.add( transaction );
}
Operation[] ops = new Operation[list.size()];
return list.toArray( ops );
}
/**
* @return Returns the describeFeatureType <code>Operation</code>.
*/
public Operation getDescribeFeatureType() {
return describeFeatureType;
}
/**
* @param describeFeatureType
* The describeFeatureType <code>Operation</code> to set.
*/
public void setDescribeFeatureType( Operation describeFeatureType ) {
this.describeFeatureType = describeFeatureType;
}
/**
* @return Returns the getFeature <code>Operation</code>.
*/
public Operation getGetFeature() {
return getFeature;
}
/**
* @param getFeature
* The getFeature <code>Operation</code> to set.
*/
public void setGetFeature( Operation getFeature ) {
this.getFeature = getFeature;
}
/**
* @return Returns the getFeatureWithLock <code>Operation</code>.
*/
public Operation getGetFeatureWithLock() {
return getFeatureWithLock;
}
/**
* @param getFeatureWithLock
* The getFeatureWithLock <code>Operation</code> to set.
*/
public void setGetFeatureWithLock( Operation getFeatureWithLock ) {
this.getFeatureWithLock = getFeatureWithLock;
}
/**
* @return Returns the getGMLObject <code>Operation</code>.
*/
public Operation getGetGMLObject() {
return getGMLObject;
}
/**
* @param getGMLObject
* The getGMLObject <code>Operation</code> to set.
*/
public void setGetGMLObject( Operation getGMLObject ) {
this.getGMLObject = getGMLObject;
}
/**
* @return Returns the lockFeature <code>Operation</code>.
*/
public Operation getLockFeature() {
return lockFeature;
}
/**
* @param lockFeature
* The lockFeature <code>Operation</code> to set.
*/
public void setLockFeature( Operation lockFeature ) {
this.lockFeature = lockFeature;
}
/**
* @return Returns the transaction <code>Operation</code>.
*/
public Operation getTransaction() {
return transaction;
}
/**
* @param transaction
* The transaction <code>Operation</code> to set.
*/
public void setTransaction( Operation transaction ) {
this.transaction = transaction;
}
}
| lgpl-2.1 |
MenoData/Time4J | base/src/test/java/net/time4j/i18n/NameDisplayTest.java | 7273 | package net.time4j.i18n;
import net.time4j.Meridiem;
import net.time4j.Month;
import net.time4j.PlainDate;
import net.time4j.PlainTime;
import net.time4j.Quarter;
import net.time4j.Weekday;
import net.time4j.engine.ChronoElement;
import net.time4j.format.OutputContext;
import net.time4j.format.TextWidth;
import net.time4j.history.ChronoHistory;
import net.time4j.history.YearDefinition;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.junit.runners.JUnit4;
import java.text.ParseException;
import java.util.Locale;
import static org.hamcrest.CoreMatchers.is;
import static org.hamcrest.MatcherAssert.assertThat;
@RunWith(JUnit4.class)
public class NameDisplayTest {
@Test
public void getMonthDisplayName_1args() {
assertThat(Month.FEBRUARY.getDisplayName(Locale.GERMAN), is("Februar"));
}
@Test
public void getMonthDisplayName_3args() {
assertThat(
Month.FEBRUARY.getDisplayName(
Locale.GERMAN, TextWidth.WIDE, OutputContext.FORMAT),
is("Februar"));
assertThat(
Month.FEBRUARY.getDisplayName(
Locale.GERMAN, TextWidth.ABBREVIATED, OutputContext.FORMAT),
is("Feb."));
}
@Test
public void getQuarterDisplayName_1args() {
assertThat(
Quarter.Q1.getDisplayName(Locale.GERMAN),
is("1. Quartal"));
}
@Test
public void getQuarterDisplayName_3args() {
assertThat(
Quarter.Q1.getDisplayName(
Locale.GERMAN, TextWidth.WIDE, OutputContext.FORMAT),
is("1. Quartal"));
assertThat(
Quarter.Q1.getDisplayName(
Locale.GERMAN, TextWidth.ABBREVIATED, OutputContext.FORMAT),
is("Q1"));
}
@Test
public void getWeekdayDisplayName_1args() {
assertThat(Weekday.TUESDAY.getDisplayName(Locale.US), is("Tuesday"));
}
@Test
public void getWeekdayDisplayName_3args() {
assertThat(
Weekday.TUESDAY.getDisplayName(
Locale.GERMAN, TextWidth.ABBREVIATED, OutputContext.FORMAT),
is("Di."));
assertThat(
Weekday.TUESDAY.getDisplayName(
Locale.GERMAN, TextWidth.WIDE, OutputContext.FORMAT),
is("Dienstag"));
}
@Test
public void getMeridiemDisplayName() {
assertThat(Meridiem.AM.getDisplayName(Locale.US), is("am"));
assertThat(Meridiem.PM.getDisplayName(Locale.US), is("pm"));
}
@Test
public void getDisplayNameOfElement_ERA() {
ChronoElement<?> element = ChronoHistory.ofFirstGregorianReform().era();
assertThat(element.getDisplayName(Locale.ENGLISH), is("era"));
}
@Test
public void getDisplayNameOfElement_YEAR() {
assertThat(PlainDate.YEAR.getDisplayName(Locale.GERMAN), is("Jahr"));
}
@Test
public void getDisplayNameOfElement_YEAR_OF_WEEKDATE() {
assertThat(PlainDate.YEAR_OF_WEEKDATE.getDisplayName(Locale.GERMAN), is("Jahr"));
}
@Test
public void getDisplayNameOfElement_YEAR_OF_ERA() {
ChronoElement<?> element = ChronoHistory.ofFirstGregorianReform().yearOfEra(YearDefinition.DUAL_DATING);
assertThat(element.getDisplayName(Locale.ENGLISH), is("year"));
}
@Test
public void getDisplayNameOfElement_QUARTER_OF_YEAR() {
assertThat(PlainDate.QUARTER_OF_YEAR.getDisplayName(Locale.GERMAN), is("Quartal"));
}
@Test
public void getDisplayNameOfElement_MONTH() {
assertThat(PlainDate.MONTH_OF_YEAR.getDisplayName(Locale.GERMAN), is("Monat"));
assertThat(PlainDate.MONTH_AS_NUMBER.getDisplayName(Locale.GERMAN), is("Monat"));
}
@Test
public void getDisplayNameOfElement_DAY_OF_MONTH() {
assertThat(PlainDate.DAY_OF_MONTH.getDisplayName(Locale.GERMAN), is("Tag"));
}
@Test
public void getDisplayNameOfElement_DAY_OF_WEEK() {
assertThat(PlainDate.DAY_OF_WEEK.getDisplayName(Locale.GERMAN), is("Wochentag"));
}
@Test
public void getDisplayNameOfElement_AM_PM_OF_DAY() {
assertThat(PlainTime.AM_PM_OF_DAY.getDisplayName(Locale.ENGLISH), is("am/pm"));
}
@Test
public void getDisplayNameOfElement_HOUR() {
assertThat(PlainTime.CLOCK_HOUR_OF_DAY.getDisplayName(Locale.GERMAN), is("Stunde"));
assertThat(PlainTime.DIGITAL_HOUR_OF_DAY.getDisplayName(Locale.GERMAN), is("Stunde"));
assertThat(PlainTime.CLOCK_HOUR_OF_AMPM.getDisplayName(Locale.GERMAN), is("Stunde"));
assertThat(PlainTime.DIGITAL_HOUR_OF_AMPM.getDisplayName(Locale.GERMAN), is("Stunde"));
assertThat(PlainTime.HOUR_FROM_0_TO_24.getDisplayName(Locale.GERMAN), is("Stunde"));
}
@Test
public void getDisplayNameOfElement_MINUTE() {
assertThat(PlainTime.MINUTE_OF_HOUR.getDisplayName(Locale.ENGLISH), is("minute"));
}
@Test
public void getDisplayNameOfElement_SECOND() {
assertThat(PlainTime.SECOND_OF_MINUTE.getDisplayName(Locale.ENGLISH), is("second"));
}
@Test
public void parseQuarterName() throws ParseException {
assertThat(
Quarter.parse(
"1. Quartal", Locale.GERMAN, TextWidth.WIDE, OutputContext.FORMAT),
is(Quarter.Q1));
assertThat(
Quarter.parse(
"Q1", Locale.GERMAN, TextWidth.ABBREVIATED, OutputContext.FORMAT),
is(Quarter.Q1));
}
@Test
public void parseWeekdayName() throws ParseException {
assertThat(
Weekday.parse(
"Montag", Locale.GERMAN, TextWidth.WIDE, OutputContext.FORMAT),
is(Weekday.MONDAY));
assertThat(
Weekday.parse(
"Mo.", Locale.GERMAN, TextWidth.ABBREVIATED, OutputContext.FORMAT),
is(Weekday.MONDAY));
}
@Test
public void parseMonthName() throws ParseException {
assertThat(
Month.parse(
"Januar", Locale.GERMAN, TextWidth.WIDE, OutputContext.FORMAT),
is(Month.JANUARY));
assertThat(
Month.parse(
"Jan", Locale.GERMAN, TextWidth.ABBREVIATED, OutputContext.STANDALONE),
is(Month.JANUARY));
}
@Test
public void parseMeridiemName() throws ParseException {
assertThat(
Meridiem.parse(
"a. m.", new Locale("es"), TextWidth.WIDE, OutputContext.FORMAT),
is(Meridiem.AM));
assertThat(
Meridiem.parse(
"p. m.", new Locale("es"), TextWidth.WIDE, OutputContext.FORMAT),
is(Meridiem.PM));
assertThat(
Meridiem.parse(
"am", new Locale("es"), TextWidth.WIDE, OutputContext.FORMAT),
is(Meridiem.AM));
assertThat(
Meridiem.parse(
"AM", new Locale("es"), TextWidth.WIDE, OutputContext.FORMAT),
is(Meridiem.AM));
assertThat(
Meridiem.parse(
"pm", new Locale("es"), TextWidth.WIDE, OutputContext.FORMAT),
is(Meridiem.PM));
assertThat(
Meridiem.parse(
"PM", new Locale("es"), TextWidth.WIDE, OutputContext.FORMAT),
is(Meridiem.PM));
}
} | lgpl-2.1 |
terryrao/test | src/main/java/org/raowei/test/testnio/TestPath.java | 993 | package org.raowei.test.testnio;
import java.nio.file.Path;
import java.nio.file.Paths;
/**
* Created by terryrao on 5/25/2015.
*/
public class TestPath {
public static Path getPath(String path,String more) {
// if (StringUtils.isBlank(more)) {
// return FileSystems.getDefault().getPath(path);
// }
return Paths.get(path,more);
}
public static Path relativeToAbsolute(Path path) {
return path.toAbsolutePath();
}
public static void main(String args[]) {
/* Path path = getPath("./test.text",null);
path.toAbsolutePath(); // C:\Users\terryrao\Documents\GitHub\.\core\test.text
path.normalize().toAbsolutePath(); //C:\Users\terryrao\Documents\GitHub\core\test.text
try {
path = path.toRealPath(); // if test.text is not exist throws an exception
} catch (IOException e) {
e.printStackTrace();
}
System.out.println(path.toString());*/
}
}
| lgpl-2.1 |
deegree/deegree3 | deegree-core/deegree-core-3d/src/main/java/org/deegree/rendering/r3d/opengl/tesselation/TexturedVertex.java | 4573 | //$HeadURL$
/*----------------------------------------------------------------------------
This file is part of deegree, http://deegree.org/
Copyright (C) 2001-2009 by:
Department of Geography, University of Bonn
and
lat/lon GmbH
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
Contact information:
lat/lon GmbH
Aennchenstr. 19, 53177 Bonn
Germany
http://lat-lon.de/
Department of Geography, University of Bonn
Prof. Dr. Klaus Greve
Postfach 1147, 53001 Bonn
Germany
http://www.geographie.uni-bonn.de/deegree/
e-mail: info@deegree.org
----------------------------------------------------------------------------*/
package org.deegree.rendering.r3d.opengl.tesselation;
/**
* The <code>TexturedVertex</code> a textured vertex.
*
* @author <a href="mailto:bezema@lat-lon.de">Rutger Bezema</a>
*
* @author last edited by: $Author$
*
* @version $Revision$, $Date$
*
*/
public class TexturedVertex extends Vertex {
float tex_u;
float tex_v;
/**
* Construct a textured vertex and calculate it's values from the given vertices
*
* @param coordinates
* of the vertex may not be <code>null</code> and must have a length of 3
*/
TexturedVertex( double[] coordinates, TexturedVertex[] otherVertices, float[] weights ) {
super( coordinates, otherVertices, weights );
// checked in super class:
// otherVertices != null && weights != null && otherVertices.length == weights.length ) {
calcTexCoords( otherVertices, weights );
}
/**
* Use the weights to calculate the u/v coordinates of this vertex
*
* @param otherVertices
* used to create this vertex
* @param weights
* adding up to 1
*/
private void calcTexCoords( TexturedVertex[] otherVertices, float[] weights ) {
// add with weights
tex_u = 0;
tex_v = 0;
for ( int i = 0; i < otherVertices.length; ++i ) {
TexturedVertex v = otherVertices[i];
if ( v != null ) {
float w = weights[i];
tex_u += v.tex_u * w;
tex_v += v.tex_v * w;
}
}
}
/**
* Construct a textured vertex with a white color and a 1,0,0 normal.
*
* @param coordinates
* of the vertex may not be <code>null</code> and must have a length of 3
* @param textureCoordinates
* of the vertex may not be <code>null</code> and must have a length of 2
*/
TexturedVertex( float[] coordinates, float[] textureCoordinates ) {
this( coordinates, new float[] { 1, 0, 0 }, textureCoordinates );
}
/**
* Construct a textured vertex with given color and normal.
*
* @param coordinates
* of the vertex may not be <code>null</code> and must have a length of 3
* @param normal
* if <code>null</code> 1,0,0 will be used.
* @param textureCoordinates
* of the vertex may not be <code>null</code> and must have a length of 2
*/
public TexturedVertex( float[] coordinates, float[] normal, float[] textureCoordinates ) {
super( coordinates, normal );
if ( textureCoordinates == null || textureCoordinates.length != 2 ) {
throw new IllegalArgumentException( "Only 2d texture coordinates are supported." );
}
tex_u = textureCoordinates[0];
tex_v = textureCoordinates[1];
}
/**
*
* @return the u and v (x,y) texture coordinates of this vertex.
*/
public float[] getTextureCoords() {
return new float[] { tex_u, tex_v };
}
@Override
public String toString() {
StringBuilder sb = new StringBuilder( super.toString() );
sb.append( "\ntex_coords:\t" ).append( tex_u ).append( "," ).append( tex_v );
return sb.toString();
}
}
| lgpl-2.1 |
ambs/exist | exist-core/src/main/java/org/exist/validation/XmlLibraryChecker.java | 12850 | /*
* eXist-db Open Source Native XML Database
* Copyright (C) 2001 The eXist-db Authors
*
* info@exist-db.org
* http://www.exist-db.org
*
* 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 org.exist.validation;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ServiceLoader;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParserFactory;
import javax.xml.transform.Transformer;
import javax.xml.transform.TransformerConfigurationException;
import javax.xml.transform.TransformerFactory;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.exist.util.ExistSAXParserFactory;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
/**
* Class for checking dependencies with XML libraries.
*
* @author <a href="mailto:adam.retter@devon.gov.uk">Adam Retter</a>
*/
public class XmlLibraryChecker {
/**
* Possible XML Parsers, at least one must be valid
*/
private final static ClassVersion[] validParsers = {
new ClassVersion("Xerces", "Xerces-J 2.10.0", "org.apache.xerces.impl.Version.getVersion()")
};
/**
* Possible XML Transformers, at least one must be valid
*/
private final static ClassVersion[] validTransformers = {
new ClassVersion("Saxon", "8.9.0", "net.sf.saxon.Version.getProductVersion()"),
new ClassVersion("Xalan", "Xalan Java 2.7.1", "org.apache.xalan.Version.getVersion()"),
};
/**
* Possible XML resolvers, at least one must be valid
*/
private final static ClassVersion[] validResolvers = {
new ClassVersion("Resolver", "XmlResolver 1.2", "org.apache.xml.resolver.Version.getVersion()"),
};
private final static Logger logger = LogManager.getLogger( XmlLibraryChecker.class );
/**
* Remove "@" from string.
*/
private static String getClassName(String classid) {
String className;
final int lastChar = classid.lastIndexOf('@');
if (lastChar == -1) {
className = classid;
} else {
className = classid.substring(0, lastChar);
}
return className;
}
/**
* Determine the class that is actually used as XML parser.
*
* @return Full classname of parser.
*/
private static String determineActualParserClass() {
String parserClass = "Unable to determine parser class";
try {
final SAXParserFactory factory = ExistSAXParserFactory.getSAXParserFactory();
final XMLReader xmlReader = factory.newSAXParser().getXMLReader();
final String classId = xmlReader.toString();
parserClass = getClassName(classId);
} catch (final ParserConfigurationException | SAXException ex) {
logger.error(ex.getMessage());
}
return parserClass;
}
/**
* Determine the class that is actually used as XML transformer.
*
* @return Full classname of transformer.
*/
private static String determineActualTransformerClass(){
String transformerClass = "Unable to determine transformer class";
try {
final TransformerFactory factory = TransformerFactory.newInstance();
final Transformer transformer = factory.newTransformer();
final String classId = transformer.toString();
transformerClass = getClassName(classId);
} catch (final TransformerConfigurationException ex) {
logger.error(ex.getMessage());
}
return transformerClass;
}
/**
* Perform checks on parsers, transformers and resolvers.
*/
public static void check() {
StringBuilder message = new StringBuilder();
/*
* Parser
*/
final ServiceLoader<SAXParserFactory> allSax = ServiceLoader.load(SAXParserFactory.class);
for(final SAXParserFactory sax : allSax){
message.append(getClassName(sax.toString()));
message.append(" ");
}
logger.debug("Detected SAXParserFactory classes: " + message.toString());
message = new StringBuilder();
boolean invalidVersionFound = false;
if( hasValidClassVersion( "Parser", validParsers, message ) ) {
logger.info( message.toString() );
} else {
logger.warn(message.toString());
invalidVersionFound = true;
}
/*
* Transformer
*/
message = new StringBuilder();
final ServiceLoader<TransformerFactory> allXsl = ServiceLoader.load(TransformerFactory.class);
for(final TransformerFactory xsl : allXsl){
message.append(getClassName(xsl.toString()));
message.append(" ");
}
logger.debug("Detected TransformerFactory classes: " + message.toString());
message = new StringBuilder();
if( hasValidClassVersion( "Transformer", validTransformers, message ) ) {
logger.info( message.toString() );
} else {
logger.warn( message.toString() );
System.err.println( message.toString() );
invalidVersionFound = true;
}
/*
* Resolver
*/
message = new StringBuilder();
if( hasValidClassVersion( "Resolver", validResolvers, message ) ) {
logger.info(message.toString());
} else {
logger.warn(message.toString());
invalidVersionFound = true;
}
logger.info( "Using parser " + determineActualParserClass() );
logger.info( "Using transformer " + determineActualTransformerClass() );
if(invalidVersionFound) {
logger.warn("Using parser " + determineActualParserClass());
logger.warn( "Using transformer " + determineActualTransformerClass() );
}
}
/**
* Check if for the specified service object one of the required
* classes is available.
*
* @param type Parser, Transformer or Resolver, used for reporting only.
* @param validClasses Array of valid classes.
* @param message Output message of detecting classes.
* @return TRUE if valid class has been found, otherwise FALSE.
*/
public static boolean hasValidClassVersion(String type,
ClassVersion[] validClasses, StringBuilder message) {
final String sep = System.getProperty("line.separator");
message.append("Looking for a valid ").append(type).append("...").append(sep);
for (final ClassVersion validClass : validClasses) {
final String actualVersion = validClass.getActualVersion();
message.append("Checking for ").append(validClass.getSimpleName());
if (actualVersion != null) {
message.append(", found version ").append(actualVersion);
if (actualVersion.compareToIgnoreCase(
validClass.getRequiredVersion()) >= 0) {
message.append(sep).append("OK!").append(sep);
return true;
} else {
message.append(" needed version ").append(validClass.getRequiredVersion()).append(sep);
}
} else {
message.append(", not found!").append(sep);
}
}
message.append("Warning: Failed find a valid ").append(type).append("!").append(sep);
message.append(sep).append("Please add an appropriate ").append(type)
.append(" to the " + "class-path, e.g. in the 'endorsed' folder of "
+ "the servlet container or in the 'endorsed' folder of the JRE.")
.append(sep);
return false;
}
/**
* Checks to see if a valid XML Parser exists
*
* @return boolean true indicates a valid Parser was found, false otherwise
*/
public static boolean hasValidParser() {
return hasValidParser(new StringBuilder());
}
/**
* Checks to see if a valid XML Parser exists
*
* @param message Messages about the status of available Parser's will
* be appended to this buffer
*
* @return boolean true indicates a valid Parser was found, false otherwise
*/
public static boolean hasValidParser(StringBuilder message) {
return hasValidClassVersion("Parser", validParsers, message);
}
/**
* Checks to see if a valid XML Transformer exists
*
* @return boolean true indicates a valid Transformer was found,
* false otherwise
*/
public static boolean hasValidTransformer() {
return hasValidTransformer(new StringBuilder());
}
/**
* Checks to see if a valid XML Transformer exists
*
* @param message Messages about the status of available Transformer's
* will be appended to this buffer
*
* @return boolean true indicates a valid Transformer was found,
* false otherwise
*/
public static boolean hasValidTransformer(StringBuilder message) {
return hasValidClassVersion("Transformer", validTransformers, message);
}
/**
* Simple class to describe a class, its required version and how to
* obtain the actual version
*/
public static class ClassVersion {
private final String simpleName;
private final String requiredVersion;
private final String versionFunction;
/**
* Default Constructor
*
* @param simpleName The simple name for the class (just a
* descriptor really)
* @param requiredVersion The required version of the class
* @param versionFunction The function to be invoked to obtain the
* actual version of the class, must be fully
* qualified (i.e. includes the package name)
*/
ClassVersion(String simpleName, String requiredVersion, String versionFunction) {
this.simpleName = simpleName;
this.requiredVersion = requiredVersion;
this.versionFunction = versionFunction;
}
/**
* @return the simple name of the class
*/
public String getSimpleName() {
return simpleName;
}
/**
* @return the required version of the class
*/
public String getRequiredVersion() {
return requiredVersion;
}
/**
* Invokes the specified versionFunction using reflection to get the
* actual version of the class
*
* @return the actual version of the class
*/
public String getActualVersion() {
String actualVersion = null;
//get the class name from the specifiec version function string
final String versionClassName = versionFunction
.substring(0, versionFunction.lastIndexOf('.'));
//get the function name from the specifiec version function string
final String versionFunctionName = versionFunction.substring(
versionFunction.lastIndexOf('.') + 1, versionFunction.lastIndexOf('('));
try {
//get the class
final Class<?> versionClass = Class.forName(versionClassName);
//get the method
final Method getVersionMethod = versionClass.getMethod(versionFunctionName, (Class[]) null);
//invoke the method on the class
actualVersion = (String) getVersionMethod.invoke(versionClass, (Object[]) null);
} catch (final ClassNotFoundException | NoSuchMethodException | SecurityException | IllegalAccessException | IllegalArgumentException | InvocationTargetException ex) {
logger.debug(ex.getMessage());
}
//return the actual version
return actualVersion;
}
}
}
| lgpl-2.1 |
pbondoer/xwiki-platform | xwiki-platform-core/xwiki-platform-rendering/xwiki-platform-rendering-wikimacro/xwiki-platform-rendering-wikimacro-api/src/test/java/org/xwiki/rendering/internal/macro/wikibridge/DefaultWikiMacroManagerTest.java | 10623 | /*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* 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.xwiki.rendering.internal.macro.wikibridge;
import java.util.Arrays;
import java.util.Collections;
import org.junit.Rule;
import org.junit.Test;
import org.xwiki.bridge.DocumentAccessBridge;
import org.xwiki.component.descriptor.DefaultComponentDescriptor;
import org.xwiki.component.manager.ComponentManager;
import org.xwiki.model.ModelContext;
import org.xwiki.model.reference.DocumentReference;
import org.xwiki.model.reference.EntityReferenceSerializer;
import org.xwiki.rendering.block.Block;
import org.xwiki.rendering.block.ParagraphBlock;
import org.xwiki.rendering.block.WordBlock;
import org.xwiki.rendering.block.XDOM;
import org.xwiki.rendering.macro.Macro;
import org.xwiki.rendering.macro.MacroId;
import org.xwiki.rendering.macro.descriptor.DefaultContentDescriptor;
import org.xwiki.rendering.macro.wikibridge.InsufficientPrivilegesException;
import org.xwiki.rendering.macro.wikibridge.WikiMacroDescriptor;
import org.xwiki.rendering.macro.wikibridge.WikiMacroFactory;
import org.xwiki.rendering.macro.wikibridge.WikiMacroManager;
import org.xwiki.rendering.macro.wikibridge.WikiMacroParameterDescriptor;
import org.xwiki.rendering.macro.wikibridge.WikiMacroVisibility;
import org.xwiki.rendering.syntax.Syntax;
import org.xwiki.test.mockito.MockitoComponentMockingRule;
import static org.junit.Assert.assertFalse;
import static org.junit.Assert.assertTrue;
import static org.mockito.ArgumentMatchers.any;
import static org.mockito.ArgumentMatchers.eq;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
/**
* Unit tests for {@link org.xwiki.rendering.internal.macro.wikibridge.DefaultWikiMacroManager}.
*
* @version $Id$
* @since 2.0M2
*/
public class DefaultWikiMacroManagerTest
{
@Rule
public MockitoComponentMockingRule<DefaultWikiMacroManager> mocker =
new MockitoComponentMockingRule<>(DefaultWikiMacroManager.class);
private DocumentReference authorReference = new DocumentReference("authorwiki", Arrays.asList("authorspace"),
"authorpage");
@Test
public void registerAndUnregisterWikiMacroWhenGlobalVisibilityAndAllowed() throws Exception
{
DefaultWikiMacro wikiMacro = generateWikiMacro(WikiMacroVisibility.GLOBAL);
// Simulate a user who's allowed for the GLOBAL visibility
WikiMacroFactory wikiMacroFactory = this.mocker.getInstance(WikiMacroFactory.class);
when(wikiMacroFactory.isAllowed(wikiMacro.getDocumentReference(), WikiMacroVisibility.GLOBAL)).thenReturn(true);
WikiMacroManager wikiMacroManager = this.mocker.getComponentUnderTest();
assertFalse(wikiMacroManager.hasWikiMacro(wikiMacro.getDocumentReference()));
EntityReferenceSerializer<String> serializer = this.mocker.getInstance(EntityReferenceSerializer.TYPE_STRING);
when(serializer.serialize(this.authorReference)).thenReturn("authorwiki:authorspace.authorpage");
// Test registration
wikiMacroManager.registerWikiMacro(wikiMacro.getDocumentReference(), wikiMacro);
assertTrue(wikiMacroManager.hasWikiMacro(wikiMacro.getDocumentReference()));
// Verify that the WikiMacroManager has registered the macro against the root CM
assertTrue(this.mocker.hasComponent(Macro.class, "testwikimacro"));
// Verify that the user and wiki where the macro is located have been set in the context
DocumentAccessBridge bridge = this.mocker.getInstance(DocumentAccessBridge.class);
verify(bridge).setCurrentUser("authorwiki:authorspace.authorpage");
ModelContext modelContext = this.mocker.getInstance(ModelContext.class);
verify(modelContext).setCurrentEntityReference(wikiMacro.getDocumentReference());
// Test unregistration
wikiMacroManager.unregisterWikiMacro(wikiMacro.getDocumentReference());
assertFalse(wikiMacroManager.hasWikiMacro(wikiMacro.getDocumentReference()));
// Verify that the WikiMacroManager has unregistered the macro from the root CM
assertFalse(this.mocker.hasComponent(Macro.class, "testwikimacro"));
}
@Test
public void registerWikiMacroWhenWikiVisibilityAndAllowed() throws Exception
{
DefaultWikiMacro wikiMacro = generateWikiMacro(WikiMacroVisibility.WIKI);
// Simulate a user who's allowed for the WIKI visibility
WikiMacroFactory wikiMacroFactory = this.mocker.getInstance(WikiMacroFactory.class);
when(wikiMacroFactory.isAllowed(wikiMacro.getDocumentReference(), WikiMacroVisibility.WIKI)).thenReturn(true);
ComponentManager wikiComponentManager = this.mocker.registerMockComponent(ComponentManager.class, "wiki");
// Test registration
WikiMacroManager wikiMacroManager = this.mocker.getComponentUnderTest();
wikiMacroManager.registerWikiMacro(wikiMacro.getDocumentReference(), wikiMacro);
assertTrue(wikiMacroManager.hasWikiMacro(wikiMacro.getDocumentReference()));
// Verify that the WikiMacroManager has registered the macro against the wiki CM
verify(wikiComponentManager).registerComponent(any(DefaultComponentDescriptor.class), eq(wikiMacro));
// Test unregistration
wikiMacroManager.unregisterWikiMacro(wikiMacro.getDocumentReference());
assertFalse(wikiMacroManager.hasWikiMacro(wikiMacro.getDocumentReference()));
// Verify that the WikiMacroManager has unregistered the macro against the wiki CM
verify(wikiComponentManager).unregisterComponent(Macro.class, "testwikimacro");
}
@Test
public void registerWikiMacroWhenUserVisibilityAndAllowed() throws Exception
{
DefaultWikiMacro wikiMacro = generateWikiMacro(WikiMacroVisibility.USER);
// Simulate a user who's allowed for the USER visibility
WikiMacroFactory wikiMacroFactory = this.mocker.getInstance(WikiMacroFactory.class);
when(wikiMacroFactory.isAllowed(wikiMacro.getDocumentReference(), WikiMacroVisibility.USER)).thenReturn(true);
ComponentManager userComponentManager = this.mocker.registerMockComponent(ComponentManager.class, "user");
// Test registration
WikiMacroManager wikiMacroManager = this.mocker.getComponentUnderTest();
wikiMacroManager.registerWikiMacro(wikiMacro.getDocumentReference(), wikiMacro);
assertTrue(wikiMacroManager.hasWikiMacro(wikiMacro.getDocumentReference()));
// Verify that the WikiMacroManager has registered the macro against the user CM
verify(userComponentManager).registerComponent(any(DefaultComponentDescriptor.class), eq(wikiMacro));
// Test unregistration
wikiMacroManager.unregisterWikiMacro(wikiMacro.getDocumentReference());
assertFalse(wikiMacroManager.hasWikiMacro(wikiMacro.getDocumentReference()));
// Verify that the WikiMacroManager has unregistered the macro against the user CM
verify(userComponentManager).unregisterComponent(Macro.class, "testwikimacro");
}
@Test(expected = InsufficientPrivilegesException.class)
public void registerWikiMacroWhenGlobalVisibilityAndNotAllowed() throws Exception
{
DefaultWikiMacro wikiMacro = generateWikiMacro(WikiMacroVisibility.GLOBAL);
// Simulate a user who's not allowed for the GLOBAL visibility
WikiMacroFactory wikiMacroFactory = this.mocker.getInstance(WikiMacroFactory.class);
when(wikiMacroFactory.isAllowed(wikiMacro.getDocumentReference(), WikiMacroVisibility.GLOBAL)).thenReturn(
false);
this.mocker.getComponentUnderTest().registerWikiMacro(wikiMacro.getDocumentReference(), wikiMacro);
}
@Test(expected = InsufficientPrivilegesException.class)
public void registerWikiMacroWhenWikiVisibilityAndNotAllowed() throws Exception
{
DefaultWikiMacro wikiMacro = generateWikiMacro(WikiMacroVisibility.WIKI);
// Simulate a user who's not allowed for the WIKI visibility
WikiMacroFactory wikiMacroFactory = this.mocker.getInstance(WikiMacroFactory.class);
when(wikiMacroFactory.isAllowed(wikiMacro.getDocumentReference(), WikiMacroVisibility.WIKI)).thenReturn(
false);
this.mocker.getComponentUnderTest().registerWikiMacro(wikiMacro.getDocumentReference(), wikiMacro);
}
@Test(expected = InsufficientPrivilegesException.class)
public void registerWikiMacroWhenUserVisibilityAndNotAllowed() throws Exception
{
DefaultWikiMacro wikiMacro = generateWikiMacro(WikiMacroVisibility.USER);
// Simulate a user who's not allowed for the USER visibility
WikiMacroFactory wikiMacroFactory = this.mocker.getInstance(WikiMacroFactory.class);
when(wikiMacroFactory.isAllowed(wikiMacro.getDocumentReference(), WikiMacroVisibility.USER)).thenReturn(
false);
this.mocker.getComponentUnderTest().registerWikiMacro(wikiMacro.getDocumentReference(), wikiMacro);
}
private DefaultWikiMacro generateWikiMacro(WikiMacroVisibility visibility) throws Exception
{
DocumentReference wikiMacroDocReference = new DocumentReference("wiki", Arrays.asList("space"),
"space");
WikiMacroDescriptor descriptor =
new WikiMacroDescriptor(new MacroId("testwikimacro"), "Test Wiki Macro", "Description", "Test", visibility,
new DefaultContentDescriptor(), Collections.<WikiMacroParameterDescriptor>emptyList());
XDOM xdom = new XDOM(Arrays.asList(new ParagraphBlock(Arrays.<Block>asList(new WordBlock("test")))));
DefaultWikiMacro wikiMacro = new DefaultWikiMacro(wikiMacroDocReference, authorReference, true, descriptor,
xdom, Syntax.XWIKI_2_0, this.mocker);
return wikiMacro;
}
}
| lgpl-2.1 |
exodev/social | component/core/src/test/java/org/exoplatform/social/core/test/MaxQueryNumber.java | 1154 | /*
* Copyright (C) 2003-2011 eXo Platform SAS.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.exoplatform.social.core.test;
import java.lang.annotation.ElementType;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
/**
* @author <a href="mailto:alain.defrance@exoplatform.com">Alain Defrance</a>
* @version $Revision$
*/
@Retention(RetentionPolicy.RUNTIME)
@Target({ElementType.METHOD})
public @interface MaxQueryNumber {
int value();
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | benchmark_typechecker/subjectSystems/GUIDSL/cnfFormat_stubfix/cnfModel.java | 186 | import de.uni_passau.spl.bytecodecomposer.stubs.Stub;
import java.lang.String;
import java.lang.Throwable;
import java.lang.System;
import java.io.PrintStream;
public class cnfModel {
}
| lgpl-3.0 |
Sleaker/SpoutPluginAPI | src/org/getspout/spoutapi/util/ChunkHash.java | 905 | /*
* This file is part of Spout (http://wiki.getspout.org/).
*
* Spout 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.
*
* Spout 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.spoutapi.util;
public class ChunkHash {
public static long hash(byte[] a) {
long h = 1;
for(byte b : a) {
h += (h<<5) + (long)b;
}
return h;
}
} | lgpl-3.0 |
liyang-bsy/LYLab | src/main/java/net/vicp/lylab/core/exceptions/LYError.java | 374 | package net.vicp.lylab.core.exceptions;
public class LYError extends Error {
private static final long serialVersionUID = -8672577910978450074L;
int code;
public LYError(String message) {
this(-1, message);
}
public LYError(int code, String message) {
super(message);
this.code = code;
}
public int getCode() {
return code;
}
}
| lgpl-3.0 |
pravinkmrr/PanoramaGL-Android | src/com/android/panoramagl/PLScene.java | 3499 | /*
* This file is part of the PanoramaGL library for Android.
*
* Authors: Javier Baez <javbaezga@gmail.com> and Miguel auay <mg_naunay@hotmail.com>
*
* $Id$
*
* 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; version 3 of
* the License
*
* 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 com.android.panoramagl;
import java.util.ArrayList;
import java.util.List;
public class PLScene extends Object
{
private List<PLCamera> cameras;
private PLCamera currentCamera;
private Integer cameraIndex;
private List<PLSceneElement> elements;
/**property methods*/
public List<PLCamera> getCameras()
{
return cameras;
}
public PLCamera getCurrentCamera()
{
return currentCamera;
}
public Integer getCameraIndex()
{
return cameraIndex;
}
public List<PLSceneElement> getElements()
{
return elements;
}
/**init methods*/
public PLScene()
{
super();
this.initializeValues();
this.addCamera(PLCamera.camera());
}
public PLScene(PLCamera camera)
{
super();
this.initializeValues();
this.addCamera(camera);
}
public PLScene(PLSceneElement element)
{
this(element, new PLCamera());
}
public PLScene(PLSceneElement element, PLCamera camera)
{
super();
this.initializeValues();
this.addElement(element);
this.addCamera(camera);
}
public static PLScene scene()
{
return new PLScene();
}
public static PLScene sceneWithCamera(PLCamera camera)
{
return new PLScene(camera);
}
public static PLScene sceneWithElement(PLSceneElement element)
{
return new PLScene(element);
}
public static PLScene sceneWithElement(PLSceneElement element, PLCamera camera)
{
return new PLScene(element, camera);
}
protected void initializeValues()
{
elements = new ArrayList<PLSceneElement>();
cameras = new ArrayList<PLCamera>();
}
/**camera methods*/
public void setCameraIndex(Integer index)
{
if(index < cameras.size())
{
cameraIndex = index;
currentCamera = cameras.get(index);
}
}
public void addCamera(PLCamera camera)
{
if(cameras.size() == 0)
{
cameraIndex = 0;
currentCamera = camera;
}
cameras.add(camera);
}
public void removeCameraAtIndex(Integer index)
{
cameras.remove(index);
if(cameras.size() == 0)
{
currentCamera = null;
cameraIndex = -1;
}
}
/**element methods*/
public void addElement(PLSceneElement element)
{
elements.add(element);
}
public void removeElementAtIndex(Integer index)
{
elements.remove(index);
}
public void removeAllElements()
{
elements.clear();
}
/**dealloc methods*/
@Override
protected void finalize() throws Throwable
{
elements = null;
cameras = null;
currentCamera = null;
super.finalize();
}
}
| lgpl-3.0 |
fuinorg/utils4j | src/test/java/org/fuin/utils4j/Utils4JTest.java | 33123 | /**
* Copyright (C) 2015 Michael Schnell. All rights reserved.
* http://www.fuin.org/
*
* 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; 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/.
*/
package org.fuin.utils4j;
import static org.assertj.core.api.Assertions.assertThat;
import static org.junit.Assert.fail;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.net.MalformedURLException;
import java.net.URL;
import java.nio.channels.FileLock;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Calendar;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.TimeZone;
import org.apache.commons.io.FileUtils;
import org.fuin.utils4j.test.ClassWithPrivateConstructor;
import org.junit.BeforeClass;
import org.junit.Test;
/**
* Tests for Utils4J.
*/
// CHECKSTYLE:OFF
public class Utils4JTest {
private static final File TEST_PROPERTIES_FILE = new File("src/test/resources/org/fuin/utils4j/test.properties");
private static final File ZIP_FILE = new File("src/test/resources/test.zip");
private static final Map<String, String> vars = new HashMap<>();
@BeforeClass
public static void beforeClass() {
vars.put("one", "1");
vars.put("two", "2");
vars.put("3", "three");
}
@Test
public final void testReplaceVarsNull() {
assertThat(Utils4J.replaceVars(null, vars)).isNull();
}
@Test
public final void testReplaceVarsEmpty() {
assertThat(Utils4J.replaceVars("", vars)).isEqualTo("");
}
@Test
public final void testReplaceVarsNoVars() {
assertThat(Utils4J.replaceVars("one two three", vars)).isEqualTo("one two three");
}
@Test
public final void testReplaceVarsSingleVar1() {
assertThat(Utils4J.replaceVars("${one}", vars)).isEqualTo("1");
}
@Test
public final void testReplaceVarsSingleVar2() {
assertThat(Utils4J.replaceVars(" ${one}", vars)).isEqualTo(" 1");
}
@Test
public final void testReplaceVarsSingleVar3() {
assertThat(Utils4J.replaceVars("${one} ", vars)).isEqualTo("1 ");
}
@Test
public final void testReplaceVarsSingleVar4() {
assertThat(Utils4J.replaceVars(" ${one} ", vars)).isEqualTo(" 1 ");
}
@Test
public final void testReplaceVarsMultipleVars1() {
assertThat(Utils4J.replaceVars(" ${one} ${two} ${3} ", vars)).isEqualTo(" 1 2 three ");
}
@Test
public final void testReplaceVarsMultipleVars2() {
assertThat(Utils4J.replaceVars("${one} ${two} ${3} ", vars)).isEqualTo("1 2 three ");
}
@Test
public final void testReplaceVarsMultipleVars3() {
assertThat(Utils4J.replaceVars("${one}${two}${3}", vars)).isEqualTo("12three");
}
@Test
public final void testReplaceVarsMultipleVars4() {
assertThat(Utils4J.replaceVars(" ${one} ${two} ${3}", vars)).isEqualTo(" 1 2 three");
}
@Test
public final void testReplaceVarsUnknown1() {
assertThat(Utils4J.replaceVars("${xyz}", vars)).isEqualTo("${xyz}");
}
@Test
public final void testReplaceVarsUnknown2() {
assertThat(Utils4J.replaceVars("${one}${xyz}", vars)).isEqualTo("1${xyz}");
}
@Test
public final void testReplaceVarsUnknown3() {
assertThat(Utils4J.replaceVars("${xyz}${two}", vars)).isEqualTo("${xyz}2");
}
@Test
public final void testReplaceVarsUnknown4() {
assertThat(Utils4J.replaceVars("${one}${xyz}${two}", vars)).isEqualTo("1${xyz}2");
}
@Test
public final void testReplaceVarsNoClosingBracket() {
assertThat(Utils4J.replaceVars("${one}${two", vars)).isEqualTo("1${two");
}
@Test
public final void testGetPackagePath() {
assertThat(Utils4J.getPackagePath(Utils4J.class)).isEqualTo("org/fuin/utils4j");
}
@Test
public final void testGetResource() throws IOException {
final URL url = new File(new File(".").getCanonicalPath(), "target/test-classes/org/fuin/utils4j/test.properties").toURI().toURL();
assertThat(Utils4J.getResource(Utils4JTest.class, "test.properties")).isEqualTo(url);
}
@Test
public final void testCheckValidFileOK() {
Utils4J.checkValidFile(TEST_PROPERTIES_FILE);
}
@Test
public final void testCheckValidFileNotExisting() {
try {
Utils4J.checkValidFile(new File(TEST_PROPERTIES_FILE.getParentFile(), "foobar.txt"));
fail();
} catch (final IllegalArgumentException ex) {
// OK
}
}
@Test
public final void testCheckValidFileDirectory() {
try {
Utils4J.checkValidFile(TEST_PROPERTIES_FILE.getParentFile());
fail();
} catch (final IllegalArgumentException ex) {
// OK
}
}
@Test
public final void testCheckValidDirOK() {
Utils4J.checkValidDir(TEST_PROPERTIES_FILE.getParentFile());
}
@Test
public final void testCheckValidDirNotExisting() {
try {
Utils4J.checkValidDir(new File(TEST_PROPERTIES_FILE.getParentFile(), "foobar"));
fail();
} catch (final IllegalArgumentException ex) {
// OK
}
}
@Test
public final void testCheckValidDirFile() {
try {
Utils4J.checkValidDir(TEST_PROPERTIES_FILE);
fail();
} catch (final IllegalArgumentException ex) {
// OK
}
}
@Test
public final void testCreateInstanceOK() {
final Object obj = Utils4J.createInstance(Utils4JTest.class.getName());
assertThat(obj).isInstanceOf(Utils4JTest.class);
}
@Test
public final void testCreateInstanceClassNotFound() {
try {
Utils4J.createInstance("x.y.Z");
fail();
} catch (final RuntimeException ex) {
assertThat(ex.getCause()).isInstanceOf(ClassNotFoundException.class);
}
}
@Test
public final void testCreateInstanceInstantiationProblem() {
try {
Utils4J.createInstance(Cancelable.class.getName());
fail();
} catch (final RuntimeException ex) {
assertThat(ex.getCause()).isInstanceOf(NoSuchMethodException.class);
}
}
@Test
public final void testCreateInstanceIllegalAccess() {
try {
Utils4J.createInstance(ClassWithPrivateConstructor.class.getName());
fail();
} catch (final RuntimeException ex) {
assertThat(ex.getCause()).isInstanceOf(IllegalAccessException.class);
}
}
@Test
public final void testContainsURL() throws IOException {
final URL[] urls = new URL[] { new URL("http://www.google.com"), new URL("http://www.yahoo.com"), new URL("file:/foobar.txt") };
assertThat(Utils4J.containsURL(urls, new URL("http://www.google.com"))).isTrue();
assertThat(Utils4J.containsURL(urls, new URL("http://www.google.com/"))).isFalse();
assertThat(Utils4J.containsURL(urls, new URL("http://www.abc.com"))).isFalse();
}
@Test
public final void testCreateHash() {
assertThat(Utils4J.createHashMD5(TEST_PROPERTIES_FILE)).isEqualTo("e13c4b796b94a61b9d0050941676d129");
}
@Test
public final void testCreateUrlDirFile() throws IOException {
assertThat(Utils4J.createUrl(new URL("http://www.fuin.org"), "test", "index.html"))
.isEqualTo(new URL("http://www.fuin.org/test/index.html"));
assertThat(Utils4J.createUrl(new URL("http://www.fuin.org/"), "test", "index.html"))
.isEqualTo(new URL("http://www.fuin.org/test/index.html"));
}
@Test
public final void testCreateUrlNullDirFile() throws IOException {
assertThat(Utils4J.createUrl(new URL("http://www.fuin.org"), null, "index.html"))
.isEqualTo(new URL("http://www.fuin.org/index.html"));
assertThat(Utils4J.createUrl(new URL("http://www.fuin.org/"), null, "index.html"))
.isEqualTo(new URL("http://www.fuin.org/index.html"));
}
@Test
public final void testCreateUrlEmptyDirFile() throws IOException {
assertThat(Utils4J.createUrl(new URL("http://www.fuin.org"), "", "index.html"))
.isEqualTo(new URL("http://www.fuin.org/index.html"));
assertThat(Utils4J.createUrl(new URL("http://www.fuin.org/"), "", "index.html"))
.isEqualTo(new URL("http://www.fuin.org/index.html"));
}
@Test
public final void testGetRelativePathOK() {
assertThat(Utils4J.getRelativePath(TEST_PROPERTIES_FILE.getParentFile().getParentFile().getParentFile().getParentFile(),
TEST_PROPERTIES_FILE.getParentFile())).isEqualTo("org" + File.separator + "fuin" + File.separator + "utils4j");
}
@Test
public final void testGetBackToRootPath() {
assertThat(Utils4J.getBackToRootPath("a/b/c", '/')).isEqualTo("../../..");
assertThat(Utils4J.getBackToRootPath("a/b/", '/')).isEqualTo("../../");
assertThat(Utils4J.getBackToRootPath("a", '/')).isEqualTo("..");
assertThat(Utils4J.getBackToRootPath("", '/')).isEqualTo("");
}
@Test
public final void testGetRelativePathSame() {
assertThat(Utils4J.getRelativePath(TEST_PROPERTIES_FILE.getParentFile(), TEST_PROPERTIES_FILE.getParentFile())).isEqualTo("");
}
@Test
public final void testGetRelativePathNotInsideBaseDir() {
try {
Utils4J.getRelativePath(TEST_PROPERTIES_FILE.getParentFile(), TEST_PROPERTIES_FILE.getParentFile().getParentFile());
fail();
} catch (final IllegalArgumentException ex) {
// OK
}
}
@Test
public final void testCheckNotNullOK() {
Utils4J.checkNotNull("name", "123");
}
@Test
public final void testCheckNotNullFail() {
try {
Utils4J.checkNotNull("name", null);
fail();
} catch (final IllegalArgumentException ex) {
// OK
}
}
@Test
public final void testCheckNotEmptyOK() {
Utils4J.checkNotEmpty("name", "abc");
}
@Test
public final void testCheckNotEmptyFail() {
try {
Utils4J.checkNotEmpty("name", "");
fail();
} catch (final IllegalArgumentException ex) {
// OK
}
}
@Test
public final void testInvokeOK() throws InvokeMethodFailedException {
assertThat(Utils4J.invoke(new IllegalNullArgumentException("abc"), "getArgument", new Class[] {}, new Object[] {}))
.isEqualTo("abc");
}
@Test
public final void testInvokeFail() throws InvokeMethodFailedException {
try {
Utils4J.invoke(new IllegalNullArgumentException("abc"), "getArgument", new Class[] { String.class }, new Object[] { "" });
fail();
} catch (final InvokeMethodFailedException ex) {
// OK
}
}
@Test
public final void testUnzip() throws IOException {
final File tmpDir = Utils4J.getTempDir();
final File readMeTxt = new File(tmpDir, "readme.txt");
final File dirOne = new File(tmpDir, "one");
final File dirTwo = new File(tmpDir, "two");
final File dirThree = new File(tmpDir, "three");
final File fileOne = new File(dirOne, "1.txt");
final File fileTwo = new File(dirTwo, "2.txt");
final File fileThree = new File(dirThree, "3.txt");
// Preconditions
assertThat(readMeTxt.exists()).isFalse();
assertThat(dirOne.exists()).isFalse();
assertThat(dirTwo.exists()).isFalse();
assertThat(dirThree.exists()).isFalse();
assertThat(fileOne.exists()).isFalse();
assertThat(fileTwo.exists()).isFalse();
assertThat(fileThree.exists()).isFalse();
// Execute method
Utils4J.unzip(ZIP_FILE, tmpDir);
try {
// Postconditions
assertThat(readMeTxt.exists()).isTrue();
assertThat(dirOne.exists()).isTrue();
assertThat(dirOne.isDirectory()).isTrue();
assertThat(dirTwo.exists()).isTrue();
assertThat(dirTwo.isDirectory()).isTrue();
assertThat(dirThree.exists()).isTrue();
assertThat(dirThree.isDirectory()).isTrue();
assertThat(fileOne.exists()).isTrue();
assertThat(fileTwo.exists()).isTrue();
assertThat(fileThree.exists()).isTrue();
} finally {
// Cleanup
fileOne.delete();
fileTwo.delete();
fileThree.delete();
dirOne.delete();
dirTwo.delete();
dirThree.delete();
readMeTxt.delete();
}
}
@Test
public final void testZip() throws IOException {
final File tmpDir = Utils4J.getTempDir();
final File tmpSubDir = new File(tmpDir, "test");
if (tmpSubDir.exists()) {
FileUtils.deleteDirectory(tmpSubDir);
}
assertThat(tmpSubDir.mkdir()).isTrue();
final File destFile = new File(tmpDir, "test2.zip");
final File readMeTxt = new File(tmpSubDir, "readme.txt");
final File dirOne = new File(tmpSubDir, "one");
final File dirTwo = new File(tmpSubDir, "two");
final File dirThree = new File(tmpSubDir, "three");
final File fileOne = new File(dirOne, "1.txt");
final File fileTwo = new File(dirTwo, "2.txt");
final File fileThree = new File(dirThree, "3.txt");
final String destPath = "abc" + File.separator + "def";
final File destSubDir = new File(tmpDir, destPath);
if (destSubDir.exists()) {
FileUtils.deleteDirectory(destSubDir);
}
Utils4J.unzip(ZIP_FILE, tmpSubDir);
try {
// Preconditions
assertThat(readMeTxt.exists()).isTrue();
assertThat(dirOne.exists()).isTrue();
assertThat(dirOne.isDirectory()).isTrue();
assertThat(dirTwo.exists()).isTrue();
assertThat(dirTwo.isDirectory()).isTrue();
assertThat(dirThree.exists()).isTrue();
assertThat(dirThree.isDirectory()).isTrue();
assertThat(fileOne.exists()).isTrue();
assertThat(fileTwo.exists()).isTrue();
assertThat(fileThree.exists()).isTrue();
// Run function under test
Utils4J.zipDir(tmpSubDir, destPath, destFile);
// Unzip the result file
Utils4J.unzip(destFile, tmpDir);
// Postconditions
assertThat(new File(destSubDir, "readme.txt").exists()).isTrue();
assertThat(new File(destSubDir, "one").exists()).isTrue();
assertThat(new File(destSubDir, "one").isDirectory()).isTrue();
assertThat(new File(destSubDir, "two").exists()).isTrue();
assertThat(new File(destSubDir, "two").isDirectory()).isTrue();
assertThat(new File(destSubDir, "three").exists()).isTrue();
assertThat(new File(destSubDir, "three").isDirectory()).isTrue();
assertThat(new File(dirOne, "1.txt").exists()).isTrue();
assertThat(new File(dirTwo, "2.txt").exists()).isTrue();
assertThat(new File(dirThree, "3.txt").exists()).isTrue();
} finally {
// Cleanup
FileUtils.deleteDirectory(tmpSubDir);
FileUtils.deleteDirectory(destSubDir);
destFile.delete();
}
}
@Test
public final void testGetUserHomeDir() {
assertThat(Utils4J.getUserHomeDir()).isEqualTo(new File(System.getProperty("user.home")));
}
@Test
public final void testGetTempDir() {
assertThat(Utils4J.getTempDir()).isEqualTo(new File(System.getProperty("java.io.tmpdir")));
}
@Test
public final void testConcatPathAndFilename() {
assertThat(Utils4J.concatPathAndFilename(null, "xyz.jar", File.separator)).isEqualTo("xyz.jar");
assertThat(Utils4J.concatPathAndFilename("", "xyz.jar", File.separator)).isEqualTo("xyz.jar");
assertThat(Utils4J.concatPathAndFilename("one", "xyz.jar", File.separator)).isEqualTo("one" + File.separator + "xyz.jar");
assertThat(Utils4J.concatPathAndFilename("one", "xyz.jar", File.separator)).isEqualTo("one" + File.separator + "xyz.jar");
}
@Test
public final void testLockRandomAccessFile() throws IOException {
final File file = File.createTempFile("testLockRandomAccessFile", ".bin");
try {
final ExceptionContainer ec1 = new ExceptionContainer();
// First holds a lock for one second
final Thread thread1 = new Thread(createLockRunnable(file, ec1, 3, 100, 1000));
final ExceptionContainer ec2 = new ExceptionContainer();
// Second makes three tries to get the lock and retries after a
// second
final Thread thread2 = new Thread(createLockRunnable(file, ec2, 3, 1000, 0));
// Start both threads to simulate a concurrent lock
startAndWaitUntilFinished(thread1, thread2);
// Check results
assertThat(ec1.exception).isNull();
assertThat(ec2.exception).isNull();
} finally {
file.delete();
}
}
@Test(expected = LockingFailedException.class)
public final void testLockRandomAccessFileFailed() throws Exception {
final File file = File.createTempFile("testLockRandomAccessFile", ".bin");
try {
final ExceptionContainer ec1 = new ExceptionContainer();
// First holds a lock for one second
final Thread thread1 = new Thread(createLockRunnable(file, ec1, 3, 100, 1000));
final ExceptionContainer ec2 = new ExceptionContainer();
// Second makes only one try to get the lock
final Thread thread2 = new Thread(createLockRunnable(file, ec2, 1, 0, 0));
// Start both threads to simulate a concurrent lock
startAndWaitUntilFinished(thread1, thread2);
// Check results
assertThat(ec1.exception).isNull();
if (ec2.exception != null) {
throw ec2.exception;
}
fail("Expected " + LockingFailedException.class.getName());
} finally {
file.delete();
}
}
@Test
public final void testEncodeDecodeHex() {
final String str1 = "This is an example! 123456789-!\"?()[]&";
final byte[] data1 = str1.getBytes();
final String hex1 = Utils4J.encodeHex(data1);
assertThat(hex1).isEqualTo("5468697320697320616e206578616d706c6521203132333435363738392d21223f28295b5d26");
final byte[] data2 = Utils4J.decodeHex(hex1);
final String str2 = new String(data2);
assertThat(str2).isEqualTo(str1);
}
@Test
public final void testEncryptDecryptPasswordBased() {
final String algorithm = "PBEWithMD5AndDES";
final String str1 = "This is a secret text 1234567890-ÄÖÜäöüß";
final byte[] data1 = str1.getBytes();
final char[] password = "MyVerySecretPw!".toCharArray();
final byte[] salt = new byte[] { (byte) 0xc7, (byte) 0x73, (byte) 0x21, (byte) 0x8c, (byte) 0x7e, (byte) 0xc8, (byte) 0xee,
(byte) 0x99 };
final int count = 100;
final byte[] encrypted = Utils4J.encryptPasswordBased(algorithm, data1, password, salt, count);
final byte[] decrypted = Utils4J.decryptPasswordBased(algorithm, encrypted, password, salt, count);
final String str2 = new String(decrypted);
assertThat(str2).isEqualTo(str1);
}
@Test
public void testFileInsideDirectory() {
assertThat(Utils4J.fileInsideDirectory(new File("/"), new File("/a/b/c/fileX.txt"))).isTrue();
assertThat(Utils4J.fileInsideDirectory(new File("/"), new File("/fileX.txt"))).isTrue();
assertThat(Utils4J.fileInsideDirectory(new File("/a"), new File("/a/b/c/fileX.txt"))).isTrue();
assertThat(Utils4J.fileInsideDirectory(new File("/a/b"), new File("/a/b/c/fileX.txt"))).isTrue();
assertThat(Utils4J.fileInsideDirectory(new File("/a/b/c"), new File("/a/b/c/fileX.txt"))).isTrue();
assertThat(Utils4J.fileInsideDirectory(new File("/a/b/c"), new File("/a/b/c/d/fileX.txt"))).isTrue();
assertThat(Utils4J.fileInsideDirectory(new File("/a"), new File("/fileX.txt"))).isFalse();
assertThat(Utils4J.fileInsideDirectory(new File("/a"), new File("/b/fileX.txt"))).isFalse();
}
@Test
public void testGetCanonicalPath() {
assertThat(Utils4J.getCanonicalPath(null)).isNull();
assertThat(Utils4J.getCanonicalPath(new File("/a/b/c/fileX.txt")))
.isEqualTo(getRoot() + "a/b/c/fileX.txt".replace('/', File.separatorChar));
}
@Test
public void testGetCanonicalFile() {
assertThat(Utils4J.getCanonicalFile(null)).isNull();
assertThat(Utils4J.getCanonicalFile(new File("/a/b/c/fileX.txt")))
.isEqualTo(new File(getRoot() + "a/b/c/fileX.txt".replace('/', File.separatorChar)));
}
@Test
public void testReadAsString() throws MalformedURLException {
// TEST
final String text = Utils4J.readAsString(TEST_PROPERTIES_FILE.toURI().toURL(), "utf-8", 1024);
// VERIFY
assertThat(text).isEqualTo("one=1\r\ntwo=2\r\nthree=3\r\n");
}
@Test
public void testUrl() throws MalformedURLException {
// TEST
final URL url = Utils4J.url("http://www.fuin.org/");
// VERIFY
assertThat(url).isEqualTo(new URL("http://www.fuin.org/"));
}
@Test
public void testReplaceCrLfTab() {
assertThat(Utils4J.replaceCrLfTab(null)).isNull();
assertThat(Utils4J.replaceCrLfTab("")).isEqualTo("");
assertThat(Utils4J.replaceCrLfTab("\r")).isEqualTo("\r");
assertThat(Utils4J.replaceCrLfTab("\\r")).isEqualTo("\r");
assertThat(Utils4J.replaceCrLfTab("\n")).isEqualTo("\n");
assertThat(Utils4J.replaceCrLfTab("\\n")).isEqualTo("\n");
assertThat(Utils4J.replaceCrLfTab("\t")).isEqualTo("\t");
assertThat(Utils4J.replaceCrLfTab("\\t")).isEqualTo("\t");
assertThat(Utils4J.replaceCrLfTab("a\\nb\\nc\\n")).isEqualTo("a\nb\nc\n");
}
@Test
public void testDateToFileTime() {
// PREPARE
final Calendar cal = Calendar.getInstance();
cal.set(Calendar.YEAR, 1601);
cal.set(Calendar.MONTH, 0);
cal.set(Calendar.DAY_OF_MONTH, 1);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
cal.setTimeZone(TimeZone.getTimeZone("GMT"));
// TEST & VERIFY
assertThat(Utils4J.dateToFileTime(cal.getTime())).isEqualTo(0);
}
@Test
public void testExpectedException() {
assertThat(Utils4J.expectedException(new IOException(), null)).isTrue();
assertThat(Utils4J.expectedException(new IOException(), new ArrayList<>())).isTrue();
assertThat(Utils4J.expectedException(new IOException(), list(IOException.class))).isTrue();
assertThat(Utils4J.expectedException(new FileNotFoundException(), list(IOException.class))).isTrue();
assertThat(Utils4J.expectedException(new IOException(), list(FileNotFoundException.class))).isFalse();
}
@Test
public void testExpectedCause() {
assertThat(Utils4J.expectedCause(new RuntimeException(), list(IOException.class))).isFalse();
assertThat(Utils4J.expectedCause(new RuntimeException(new IOException()), null)).isTrue();
assertThat(Utils4J.expectedCause(new RuntimeException(new IOException()), new ArrayList<>())).isTrue();
assertThat(Utils4J.expectedCause(new RuntimeException(new IOException()), list(IOException.class))).isTrue();
assertThat(Utils4J.expectedCause(new RuntimeException(new FileNotFoundException()), list(IOException.class))).isTrue();
assertThat(Utils4J.expectedCause(new RuntimeException(new IOException()), list(FileNotFoundException.class))).isFalse();
}
@SafeVarargs
private static List<Class<? extends Exception>> list(Class<? extends Exception>... classes) {
return Arrays.asList(classes);
}
private static String getRoot() {
try {
return new File("/").getCanonicalPath();
} catch (final IOException ex) {
throw new RuntimeException(ex);
}
}
private static class ExceptionContainer {
// Synchronizing is not necessary because only one thread is accessing
// the variable
public Exception exception = null;
}
/**
* Create a runnable that locks the file.
*
* @param file
* File to lock.
* @param ec
* If an exception occurs it will stored in this object.
* @param tryLockMax
* Number of tries to lock before throwing an exception.
* @param tryWaitMillis
* Milliseconds to sleep between retries.
* @param sleepMillis
* Number of milliseconds to hold the lock.
*
* @return New runnable instance.
*/
private Runnable createLockRunnable(final File file, final ExceptionContainer ec, final int tryLockMax, final long tryWaitMillis,
final long sleepMillis) {
return new Runnable() {
@Override
public void run() {
try {
final RandomAccessFile raf = new RandomAccessFile(file, "rw");
try {
final FileLock lock = Utils4J.lockRandomAccessFile(raf, tryLockMax, tryWaitMillis);
try {
// Hold the lock for one second
Thread.sleep(sleepMillis);
} finally {
lock.release();
}
} finally {
raf.close();
}
} catch (final Exception ex) {
ec.exception = ex;
}
}
};
}
/**
* Start the two threads and wait until both finished.
*
* @param thread1
* First thread.
* @param thread2
* Second thread.
*/
private static void startAndWaitUntilFinished(final Thread thread1, final Thread thread2) {
try {
// Start the threads
thread1.start();
Thread.sleep(200);
thread2.start();
// Wait for both to terminate
thread1.join();
thread2.join();
} catch (final InterruptedException ex) {
throw new RuntimeException(ex);
}
}
@Test
public void testJreFile() throws IOException {
final File javaHomeDir = new File(System.getProperty("java.home"));
final File libDir = new File(javaHomeDir, "lib");
final File[] jars = libDir.listFiles(file -> {
return file.getName().endsWith(".jar");
});
final File securityDir = new File(libDir, "security");
// Existing JRE files
assertThat(Utils4J.jreFile(jars[0])).isTrue();
assertThat(Utils4J.jreFile(new File(securityDir, "cacerts"))).isTrue();
// Non existing and not in JRE
assertThat(Utils4J.jreFile(new File(Utils4J.getTempDir(), "whatever.jar"))).isFalse();
// Non existing in JRE
assertThat(Utils4J.jreFile(new File(javaHomeDir, "whatever.jar"))).isFalse();
// Existing JAR, but not in JRE
final File aJar = new File(Utils4J.getTempDir(), "a.jar");
aJar.createNewFile();
try {
assertThat(Utils4J.jreJarFile(aJar)).isFalse();
} finally {
aJar.delete();
}
}
@Test
public void testClassFile() throws IOException {
final File aClass = new File(Utils4J.getTempDir(), "a.class");
aClass.createNewFile();
final File aJar = new File(Utils4J.getTempDir(), "a.jar");
aJar.createNewFile();
try {
assertThat(Utils4J.classFile(aClass)).isTrue();
assertThat(Utils4J.classFile(aJar)).isFalse();
assertThat(Utils4J.classFile(new File(Utils4J.getTempDir(), "b.jar"))).isFalse();
} finally {
aClass.delete();
aJar.delete();
}
}
@Test
public void testJarFile() throws IOException {
final File aClass = new File(Utils4J.getTempDir(), "a.class");
aClass.createNewFile();
final File aJar = new File(Utils4J.getTempDir(), "a.jar");
aJar.createNewFile();
try {
assertThat(Utils4J.jarFile(aJar)).isTrue();
assertThat(Utils4J.jarFile(aClass)).isFalse();
} finally {
aClass.delete();
aJar.delete();
}
}
@Test
public void testNonJreJarFile() throws IOException {
final File aClass = new File(Utils4J.getTempDir(), "a.class");
aClass.createNewFile();
final File aJar = new File(Utils4J.getTempDir(), "a.jar");
aJar.createNewFile();
try {
assertThat(Utils4J.nonJreJarFile(aJar)).isTrue();
assertThat(Utils4J.nonJreJarFile(aClass)).isFalse();
} finally {
aClass.delete();
aJar.delete();
}
}
@Test
public void testJreJarFile() throws IOException {
final File javaHomeDir = new File(System.getProperty("java.home"));
final File libDir = new File(javaHomeDir, "lib");
final File[] jars = libDir.listFiles(file -> {
return file.getName().endsWith(".jar");
});
// Valid JRE JARs
assertThat(Utils4J.jreJarFile(jars[0])).isTrue();
// No jar
assertThat(Utils4J.jreJarFile(new File(javaHomeDir, "README"))).isFalse();
// Not existing
assertThat(Utils4J.jreJarFile(new File(Utils4J.getTempDir(), "whatever.jar"))).isFalse();
// Existing JAR, but not in JRE
final File aJar = new File(Utils4J.getTempDir(), "a.jar");
aJar.createNewFile();
try {
assertThat(Utils4J.jreJarFile(aJar)).isFalse();
} finally {
aJar.delete();
}
}
@Test
public void testClasspathFilesPredicate() throws IOException {
final List<File> nonJreClassFiles = Utils4J.classpathFiles(Utils4J::classFile);
final File thisClass = new File("./target/test-classes/org/fuin/utils4j/Utils4JTest.class").getCanonicalFile();
assertThat(nonJreClassFiles).contains(thisClass);
}
@Test
public void testPathsFiles() {
final File javaHomeDir = new File(System.getProperty("java.home"));
final List<File> bootJarFiles = Utils4J.pathsFiles(System.getProperty("sun.boot.library.path"), Utils4J::jreJarFile);
final File rtJar = new File(javaHomeDir, "lib/jrt-fs.jar");
assertThat(bootJarFiles).contains(rtJar);
}
@Test
public void testClasspathFiles() throws IOException {
final File currentDir = new File(".").getCanonicalFile();
final List<File> files = Utils4J.classpathFiles();
assertThat(files).contains(new File(currentDir, "target/classes"));
}
}
// CHECKSTYLE:ON
| lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-batch/src/test/java/org/sonar/batch/index/CachesTest.java | 3137 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 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.batch.index;
import java.util.Collections;
import org.junit.After;
import org.junit.Before;
import org.junit.ClassRule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.api.CoreProperties;
import org.sonar.batch.bootstrap.BootstrapProperties;
import org.sonar.batch.bootstrap.BootstrapSettings;
import org.sonar.batch.bootstrap.TempFolderProvider;
import java.io.File;
import java.io.IOException;
import java.io.Serializable;
import static org.fest.assertions.Assertions.assertThat;
import static org.fest.assertions.Fail.fail;
public class CachesTest {
@ClassRule
public static TemporaryFolder temp = new TemporaryFolder();
public static Caches createCacheOnTemp(TemporaryFolder temp) {
BootstrapSettings bootstrapSettings = new BootstrapSettings(
new BootstrapProperties(Collections.<String,String>emptyMap())
);
try {
bootstrapSettings.properties().put(CoreProperties.WORKING_DIRECTORY, temp.newFolder().getAbsolutePath());
} catch (IOException e) {
throw new RuntimeException(e);
}
return new Caches(new TempFolderProvider().provide(bootstrapSettings));
}
Caches caches;
@Before
public void prepare() throws Exception {
caches = createCacheOnTemp(temp);
}
@After
public void stop() {
caches.stop();
}
@Test
public void should_stop_and_clean_temp_dir() throws Exception {
File tempDir = caches.tempDir();
assertThat(tempDir).isDirectory().exists();
assertThat(caches.persistit()).isNotNull();
assertThat(caches.persistit().isInitialized()).isTrue();
caches.stop();
assertThat(tempDir).doesNotExist();
assertThat(caches.tempDir()).isNull();
assertThat(caches.persistit()).isNull();
}
@Test
public void should_create_cache() throws Exception {
caches.start();
Cache<Element> cache = caches.createCache("foo");
assertThat(cache).isNotNull();
}
@Test
public void should_not_create_cache_twice() throws Exception {
caches.start();
caches.<Element>createCache("foo");
try {
caches.<Element>createCache("foo");
fail();
} catch (IllegalStateException e) {
// ok
}
}
static class Element implements Serializable {
}
}
| lgpl-3.0 |
ArticulatedSocialAgentsPlatform/HmiCore | HmiGraphics/src/hmi/graphics/collada/Scale.java | 2666 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer 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 Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package hmi.graphics.collada;
import hmi.math.Mat4f;
import hmi.math.Vec3f;
import hmi.xml.XMLFormatting;
import hmi.xml.XMLTokenizer;
import java.io.IOException;
/**
* @author Job Zwiers
*/
public class Scale extends TransformNode {
private float[] scaleVec = Vec3f.getVec3f(1.0f, 1.0f, 1.0f);
public Scale() {
super();
}
public Scale(Collada collada, XMLTokenizer tokenizer) throws IOException {
super(collada);
readXML(tokenizer);
}
/**
* Returns the 4X4 scaling matrix, in row-major order.
*/
@Override
public float[] getMat4f() {
if (super.getMat4f()==null) setMat4f(Mat4f.getScalingMatrix(scaleVec));
return super.getMat4f();
}
/**
* Returns the scaling vector in a Vec3f array.
*/
public float[] getScaleVec3f() {
return scaleVec;
}
@Override
public StringBuilder appendContent(StringBuilder buf, XMLFormatting fmt) {
appendNewLine(buf, fmt);
appendFloats(buf, scaleVec, ' ', fmt, Vec3f.VEC3F_SIZE);
return buf;
}
@Override
public void decodeContent(XMLTokenizer tokenizer) throws IOException {
decodeFloatArray(tokenizer.takeCharData(), scaleVec);
}
/*
* The XML Stag for XML encoding
*/
private static final String XMLTAG = "scale";
/**
* The XML Stag for XML encoding
*/
public static String xmlTag() { return XMLTAG; }
/**
* returns the XML Stag for XML encoding
*/
@Override
public String getXMLTag() {
return XMLTAG;
}
}
| lgpl-3.0 |
pgrabowski/jsleeannotations | jsleeannotations-processor/src/main/java/jsleeannotations/xml/profile/ProfileManagementInterfaceName.java | 2798 | /*
* JSLEE Annotations
* Copyright (c) 2015 Piotr Grabowski, 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.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 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.
*/
//
// This file was generated by the JavaTM Architecture for XML Binding(JAXB) Reference Implementation, v2.2.8-b130911.1802
// See <a href="http://java.sun.com/xml/jaxb">http://java.sun.com/xml/jaxb</a>
// Any modifications to this file will be lost upon recompilation of the source schema.
// Generated on: 2015.01.26 at 10:32:37 PM CET
//
package jsleeannotations.xml.profile;
import javax.xml.bind.annotation.XmlAccessType;
import javax.xml.bind.annotation.XmlAccessorType;
import javax.xml.bind.annotation.XmlAttribute;
import javax.xml.bind.annotation.XmlID;
import javax.xml.bind.annotation.XmlRootElement;
import javax.xml.bind.annotation.XmlType;
import javax.xml.bind.annotation.XmlValue;
import javax.xml.bind.annotation.adapters.CollapsedStringAdapter;
import javax.xml.bind.annotation.adapters.XmlJavaTypeAdapter;
/**
*
*/
@XmlAccessorType(XmlAccessType.FIELD)
@XmlType(name = "", propOrder = {
"value"
})
@XmlRootElement(name = "profile-management-interface-name")
public class ProfileManagementInterfaceName {
@XmlAttribute(name = "id")
@XmlJavaTypeAdapter(CollapsedStringAdapter.class)
@XmlID
protected String id;
@XmlValue
protected String value;
/**
* Gets the value of the id property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getId() {
return id;
}
/**
* Sets the value of the id property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setId(String value) {
this.id = value;
}
/**
* Gets the value of the value property.
*
* @return
* possible object is
* {@link String }
*
*/
public String getvalue() {
return value;
}
/**
* Sets the value of the value property.
*
* @param value
* allowed object is
* {@link String }
*
*/
public void setvalue(String value) {
this.value = value;
}
}
| lgpl-3.0 |
haisamido/SFDaaS | src/org/orekit/tle/DeepSDP4.java | 29987 | /* Copyright 2002-2010 CS Communication & Systèmes
* Licensed to CS Communication & Systèmes (CS) under one or more
* contributor license agreements. See the NOTICE file distributed with
* this work for additional information regarding copyright ownership.
* CS licenses this file to You under the Apache License, Version 2.0
* (the "License"); you may not use this file except in compliance with
* the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.orekit.tle;
import org.apache.commons.math.util.MathUtils;
import org.orekit.errors.OrekitException;
import org.orekit.time.AbsoluteDate;
import org.orekit.time.TimeScalesFactory;
import org.orekit.utils.Constants;
/** This class contains the methods that compute deep space perturbation terms.
* <p>
* The user should not bother in this class since it is handled internaly by the
* {@link TLEPropagator}.
* </p>
* <p>This implementation is largely inspired from the paper and source code <a
* href="http://www.celestrak.com/publications/AIAA/2006-6753/">Revisiting Spacetrack
* Report #3</a> and is fully compliant with its results and tests cases.</p>
* @author Felix R. Hoots, Ronald L. Roehrich, December 1980 (original fortran)
* @author David A. Vallado, Paul Crawford, Richard Hujsak, T.S. Kelso (C++ translation and improvements)
* @author Fabien Maussion (java translation)
* @version $Revision:1665 $ $Date:2008-06-11 12:12:59 +0200 (mer., 11 juin 2008) $
*/
class DeepSDP4 extends SDP4 {
/** Serializable UID. */
private static final long serialVersionUID = 7155645502511295218L;
// CHECKSTYLE: stop JavadocVariable check
// Internal constants
private static final double ZNS = 1.19459E-5;
private static final double ZES = 0.01675;
private static final double ZNL = 1.5835218E-4;
private static final double ZEL = 0.05490;
private static final double THDT = 4.3752691E-3;
private static final double C1SS = 2.9864797E-6;
private static final double C1L = 4.7968065E-7;
private static final double ROOT22 = 1.7891679E-6;
private static final double ROOT32 = 3.7393792E-7;
private static final double ROOT44 = 7.3636953E-9;
private static final double ROOT52 = 1.1428639E-7;
private static final double ROOT54 = 2.1765803E-9;
private static final double Q22 = 1.7891679E-6;
private static final double Q31 = 2.1460748E-6;
private static final double Q33 = 2.2123015E-7;
private static final double C_FASX2 = 0.99139134268488593;
private static final double S_FASX2 = 0.13093206501640101;
private static final double C_2FASX4 = 0.87051638752972937;
private static final double S_2FASX4 = -0.49213943048915526;
private static final double C_3FASX6 = 0.43258117585763334;
private static final double S_3FASX6 = 0.90159499016666422;
private static final double C_G22 = 0.87051638752972937;
private static final double S_G22 = -0.49213943048915526;
private static final double C_G32 = 0.57972190187001149;
private static final double S_G32 = 0.81481440616389245;
private static final double C_G44 = -0.22866241528815548;
private static final double S_G44 = 0.97350577801807991;
private static final double C_G52 = 0.49684831179884198;
private static final double S_G52 = 0.86783740128127729;
private static final double C_G54 = -0.29695209575316894;
private static final double S_G54 = -0.95489237761529999;
/** Integration step (seconds). */
private static final double SECULAR_INTEGRATION_STEP = 720.0;
/** Integration order. */
private static final int SECULAR_INTEGRATION_ORDER = 2;
/** Intermediate values. */
private double thgr;
private double xnq;
private double omegaq;
private double zcosil;
private double zsinil;
private double zsinhl;
private double zcoshl;
private double zmol;
private double zcosgl;
private double zsingl;
private double zmos;
private double savtsn;
private double ee2;
private double e3;
private double xi2;
private double xi3;
private double xl2;
private double xl3;
private double xl4;
private double xgh2;
private double xgh3;
private double xgh4;
private double xh2;
private double xh3;
private double d2201;
private double d2211;
private double d3210;
private double d3222;
private double d4410;
private double d4422;
private double d5220;
private double d5232;
private double d5421;
private double d5433;
private double xlamo;
private double sse;
private double ssi;
private double ssl;
private double ssh;
private double ssg;
private double se2;
private double si2;
private double sl2;
private double sgh2;
private double sh2;
private double se3;
private double si3;
private double sl3;
private double sgh3;
private double sh3;
private double sl4;
private double sgh4;
private double del1;
private double del2;
private double del3;
private double xfact;
private double xli;
private double xni;
private double atime;
private double pe;
private double pinc;
private double pl;
private double pgh;
private double ph;
private double[] derivs;
// CHECKSTYLE: resume JavadocVariable check
/** Flag for resonant orbits. */
private boolean resonant;
/** Flag for synchronous orbits. */
private boolean synchronous;
/** Flag for compliance with Dundee modifications. */
private boolean isDundeeCompliant = true;
/** Constructor for a unique initial TLE.
* @param initialTLE the TLE to propagate.
* @exception OrekitException if some specific error occurs
*/
protected DeepSDP4(final TLE initialTLE) throws OrekitException {
super(initialTLE);
}
/** Computes luni - solar terms from initial coordinates and epoch.
* @exception OrekitException when UTC time steps can't be read
*/
protected void luniSolarTermsComputation() throws OrekitException {
final double sing = Math.sin(tle.getPerigeeArgument());
final double cosg = Math.cos(tle.getPerigeeArgument());
final double sinq = Math.sin(tle.getRaan());
final double cosq = Math.cos(tle.getRaan());
final double aqnv = 1.0 / a0dp;
// Compute julian days since 1900
final double daysSince1900 =
(tle.getDate().durationFrom(AbsoluteDate.JULIAN_EPOCH) +
tle.getDate().timeScalesOffset(TimeScalesFactory.getUTC(), TimeScalesFactory.getTT())) / Constants.JULIAN_DAY - 2415020;
double cc = C1SS;
double ze = ZES;
double zn = ZNS;
double zsinh = sinq;
double zcosh = cosq;
thgr = thetaG(tle.getDate());
xnq = xn0dp;
omegaq = tle.getPerigeeArgument();
final double xnodce = 4.5236020 - 9.2422029e-4 * daysSince1900;
final double stem = Math.sin(xnodce);
final double ctem = Math.cos(xnodce);
final double c_minus_gam = 0.228027132 * daysSince1900 - 1.1151842;
final double gam = 5.8351514 + 0.0019443680 * daysSince1900;
zcosil = 0.91375164 - 0.03568096 * ctem;
zsinil = Math.sqrt(1.0 - zcosil * zcosil);
zsinhl = 0.089683511 * stem / zsinil;
zcoshl = Math.sqrt(1.0 - zsinhl * zsinhl);
zmol = MathUtils.normalizeAngle(c_minus_gam, Math.PI);
double zx = 0.39785416 * stem / zsinil;
final double zy = zcoshl * ctem + 0.91744867 * zsinhl * stem;
zx = Math.atan2( zx, zy) + gam - xnodce;
zcosgl = Math.cos( zx);
zsingl = Math.sin( zx);
zmos = MathUtils.normalizeAngle(6.2565837 + 0.017201977 * daysSince1900, Math.PI);
// Do solar terms
savtsn = 1e20;
double zcosi = 0.91744867;
double zsini = 0.39785416;
double zsing = -0.98088458;
double zcosg = 0.1945905;
double se = 0;
double sgh = 0;
double sh = 0;
double si = 0;
double sl = 0;
// There was previously some convoluted logic here, but it boils
// down to this: we compute the solar terms, then the lunar terms.
// On a second pass, we recompute the solar terms, taking advantage
// of the improved data that resulted from computing lunar terms.
for (int iteration = 0; iteration < 2; ++iteration) {
final double a1 = zcosg * zcosh + zsing * zcosi * zsinh;
final double a3 = -zsing * zcosh + zcosg * zcosi * zsinh;
final double a7 = -zcosg * zsinh + zsing * zcosi * zcosh;
final double a8 = zsing * zsini;
final double a9 = zsing * zsinh + zcosg * zcosi * zcosh;
final double a10 = zcosg * zsini;
final double a2 = cosi0 * a7 + sini0 * a8;
final double a4 = cosi0 * a9 + sini0 * a10;
final double a5 = -sini0 * a7 + cosi0 * a8;
final double a6 = -sini0 * a9 + cosi0 * a10;
final double x1 = a1 * cosg + a2 * sing;
final double x2 = a3 * cosg + a4 * sing;
final double x3 = -a1 * sing + a2 * cosg;
final double x4 = -a3 * sing + a4 * cosg;
final double x5 = a5 * sing;
final double x6 = a6 * sing;
final double x7 = a5 * cosg;
final double x8 = a6 * cosg;
final double z31 = 12 * x1 * x1 - 3 * x3 * x3;
final double z32 = 24 * x1 * x2 - 6 * x3 * x4;
final double z33 = 12 * x2 * x2 - 3 * x4 * x4;
final double z11 = -6 * a1 * a5 + e0sq * (-24 * x1 * x7 - 6 * x3 * x5);
final double z12 = -6 * (a1 * a6 + a3 * a5) +
e0sq * (-24 * (x2 * x7 + x1 * x8) - 6 * (x3 * x6 + x4 * x5));
final double z13 = -6 * a3 * a6 + e0sq * (-24 * x2 * x8 - 6 * x4 * x6);
final double z21 = 6 * a2 * a5 + e0sq * (24 * x1 * x5 - 6 * x3 * x7);
final double z22 = 6 * (a4 * a5 + a2 * a6) +
e0sq * (24 * (x2 * x5 + x1 * x6) - 6 * (x4 * x7 + x3 * x8));
final double z23 = 6 * a4 * a6 + e0sq * (24 * x2 * x6 - 6 * x4 * x8);
final double s3 = cc / xnq;
final double s2 = -0.5 * s3 / beta0;
final double s4 = s3 * beta0;
final double s1 = -15 * tle.getE() * s4;
final double s5 = x1 * x3 + x2 * x4;
final double s6 = x2 * x3 + x1 * x4;
final double s7 = x2 * x4 - x1 * x3;
double z1 = 3 * (a1 * a1 + a2 * a2) + z31 * e0sq;
double z2 = 6 * (a1 * a3 + a2 * a4) + z32 * e0sq;
double z3 = 3 * (a3 * a3 + a4 * a4) + z33 * e0sq;
z1 = z1 + z1 + beta02 * z31;
z2 = z2 + z2 + beta02 * z32;
z3 = z3 + z3 + beta02 * z33;
se = s1 * zn * s5;
si = s2 * zn * (z11 + z13);
sl = -zn * s3 * (z1 + z3 - 14 - 6 * e0sq);
sgh = s4 * zn * (z31 + z33 - 6);
if (tle.getI() < (Math.PI / 60.0)) {
// inclination smaller than 3 degrees
sh = 0;
} else {
sh = -zn * s2 * (z21 + z23);
}
ee2 = 2 * s1 * s6;
e3 = 2 * s1 * s7;
xi2 = 2 * s2 * z12;
xi3 = 2 * s2 * (z13 - z11);
xl2 = -2 * s3 * z2;
xl3 = -2 * s3 * (z3 - z1);
xl4 = -2 * s3 * (-21 - 9 * e0sq) * ze;
xgh2 = 2 * s4 * z32;
xgh3 = 2 * s4 * (z33 - z31);
xgh4 = -18 * s4 * ze;
xh2 = -2 * s2 * z22;
xh3 = -2 * s2 * (z23 - z21);
if (iteration == 0) { // we compute lunar terms only on the first pass:
sse = se;
ssi = si;
ssl = sl;
ssh = sh / sini0;
ssg = sgh - cosi0 * ssh;
se2 = ee2;
si2 = xi2;
sl2 = xl2;
sgh2 = xgh2;
sh2 = xh2;
se3 = e3;
si3 = xi3;
sl3 = xl3;
sgh3 = xgh3;
sh3 = xh3;
sl4 = xl4;
sgh4 = xgh4;
zcosg = zcosgl;
zsing = zsingl;
zcosi = zcosil;
zsini = zsinil;
zcosh = zcoshl * cosq + zsinhl * sinq;
zsinh = sinq * zcoshl - cosq * zsinhl;
zn = ZNL;
cc = C1L;
ze = ZEL;
}
} // end of solar - lunar - solar terms computation
sse += se;
ssi += si;
ssl += sl;
ssg += sgh - cosi0 / sini0 * sh;
ssh += sh / sini0;
// Start the resonant-synchronous tests and initialization
double bfact = 0;
// if mean motion is 1.893053 to 2.117652 revs/day, and eccentricity >= 0.5,
// start of the 12-hour orbit, e > 0.5 section
if ((xnq >= 0.00826) && (xnq <= 0.00924) && (tle.getE() >= 0.5)) {
final double g201 = -0.306 - (tle.getE() - 0.64) * 0.440;
final double eoc = tle.getE() * e0sq;
final double sini2 = sini0 * sini0;
final double f220 = 0.75 * (1 + 2 * cosi0 + theta2);
final double f221 = 1.5 * sini2;
final double f321 = 1.875 * sini0 * (1 - 2 * cosi0 - 3 * theta2);
final double f322 = -1.875 * sini0 * (1 + 2 * cosi0 - 3 * theta2);
final double f441 = 35 * sini2 * f220;
final double f442 = 39.3750 * sini2 * sini2;
final double f522 = 9.84375 * sini0 * (sini2 * (1 - 2 * cosi0 - 5 * theta2) +
0.33333333 * (-2 + 4 * cosi0 + 6 * theta2));
final double f523 = sini0 * (4.92187512 * sini2 * (-2 - 4 * cosi0 + 10 * theta2) +
6.56250012 * (1 + 2 * cosi0 - 3 * theta2));
final double f542 = 29.53125 * sini0 * (2 - 8 * cosi0 + theta2 * (-12 + 8 * cosi0 + 10 * theta2));
final double f543 = 29.53125 * sini0 * (-2 - 8 * cosi0 + theta2 * (12 + 8 * cosi0 - 10 * theta2));
double g211;
double g310;
double g322;
double g410;
double g422;
double g520;
resonant = true; // it is resonant...
synchronous = false; // but it's not synchronous
// Geopotential resonance initialization for 12 hour orbits :
if (tle.getE() <= 0.65) {
g211 = 3.616 - 13.247 * tle.getE() + 16.290 * e0sq;
g310 = -19.302 + 117.390 * tle.getE() - 228.419 * e0sq + 156.591 * eoc;
g322 = -18.9068 + 109.7927 * tle.getE() - 214.6334 * e0sq + 146.5816 * eoc;
g410 = -41.122 + 242.694 * tle.getE() - 471.094 * e0sq + 313.953 * eoc;
g422 = -146.407 + 841.880 * tle.getE() - 1629.014 * e0sq + 1083.435 * eoc;
g520 = -532.114 + 3017.977 * tle.getE() - 5740.032 * e0sq + 3708.276 * eoc;
} else {
g211 = -72.099 + 331.819 * tle.getE() - 508.738 * e0sq + 266.724 * eoc;
g310 = -346.844 + 1582.851 * tle.getE() - 2415.925 * e0sq + 1246.113 * eoc;
g322 = -342.585 + 1554.908 * tle.getE() - 2366.899 * e0sq + 1215.972 * eoc;
g410 = -1052.797 + 4758.686 * tle.getE() - 7193.992 * e0sq + 3651.957 * eoc;
g422 = -3581.69 + 16178.11 * tle.getE() - 24462.77 * e0sq + 12422.52 * eoc;
if (tle.getE() <= 0.715) {
g520 = 1464.74 - 4664.75 * tle.getE() + 3763.64 * e0sq;
} else {
g520 = -5149.66 + 29936.92 * tle.getE() - 54087.36 * e0sq + 31324.56 * eoc;
}
}
double g533;
double g521;
double g532;
if (tle.getE() < 0.7) {
g533 = -919.2277 + 4988.61 * tle.getE() - 9064.77 * e0sq + 5542.21 * eoc;
g521 = -822.71072 + 4568.6173 * tle.getE() - 8491.4146 * e0sq + 5337.524 * eoc;
g532 = -853.666 + 4690.25 * tle.getE() - 8624.77 * e0sq + 5341.4 * eoc;
} else {
g533 = -37995.78 + 161616.52 * tle.getE() - 229838.2 * e0sq + 109377.94 * eoc;
g521 = -51752.104 + 218913.95 * tle.getE() - 309468.16 * e0sq + 146349.42 * eoc;
g532 = -40023.88 + 170470.89 * tle.getE() - 242699.48 * e0sq + 115605.82 * eoc;
}
double temp1 = 3 * xnq * xnq * aqnv * aqnv;
double temp = temp1 * ROOT22;
d2201 = temp * f220 * g201;
d2211 = temp * f221 * g211;
temp1 *= aqnv;
temp = temp1 * ROOT32;
d3210 = temp * f321 * g310;
d3222 = temp * f322 * g322;
temp1 *= aqnv;
temp = 2 * temp1 * ROOT44;
d4410 = temp * f441 * g410;
d4422 = temp * f442 * g422;
temp1 *= aqnv;
temp = temp1 * ROOT52;
d5220 = temp * f522 * g520;
d5232 = temp * f523 * g532;
temp = 2 * temp1 * ROOT54;
d5421 = temp * f542 * g521;
d5433 = temp * f543 * g533;
xlamo = tle.getMeanAnomaly() + tle.getRaan() + tle.getRaan() - thgr - thgr;
bfact = xmdot + xnodot + xnodot - THDT - THDT;
bfact += ssl + ssh + ssh;
} else if ((xnq < 0.0052359877) && (xnq > 0.0034906585)) {
// if mean motion is .8 to 1.2 revs/day : (geosynch)
final double cosio_plus_1 = 1.0 + cosi0;
final double g200 = 1 + e0sq * (-2.5 + 0.8125 * e0sq);
final double g300 = 1 + e0sq * (-6 + 6.60937 * e0sq);
final double f311 = 0.9375 * sini0 * sini0 * (1 + 3 * cosi0) - 0.75 * cosio_plus_1;
final double g310 = 1 + 2 * e0sq;
final double f220 = 0.75 * cosio_plus_1 * cosio_plus_1;
final double f330 = 2.5 * f220 * cosio_plus_1;
resonant = true;
synchronous = true;
// Synchronous resonance terms initialization
del1 = 3 * xnq * xnq * aqnv * aqnv;
del2 = 2 * del1 * f220 * g200 * Q22;
del3 = 3 * del1 * f330 * g300 * Q33 * aqnv;
del1 = del1 * f311 * g310 * Q31 * aqnv;
xlamo = tle.getMeanAnomaly() + tle.getRaan() + tle.getPerigeeArgument() - thgr;
bfact = xmdot + omgdot + xnodot - THDT;
bfact = bfact + ssl + ssg + ssh;
} else {
// it's neither a high-e 12-hours orbit nor a geosynchronous:
resonant = false;
synchronous = false;
}
if (resonant) {
xfact = bfact - xnq;
// Initialize integrator
xli = xlamo;
xni = xnq;
atime = 0;
}
derivs = new double[SECULAR_INTEGRATION_ORDER];
}
/** Computes secular terms from current coordinates and epoch.
* @param t offset from initial epoch (minutes)
*/
protected void deepSecularEffects(final double t) {
xll += ssl * t;
omgadf += ssg * t;
xnode += ssh * t;
em = tle.getE() + sse * t;
xinc = tle.getI() + ssi * t;
if (resonant) {
// If we're closer to t = 0 than to the currently-stored data
// from the previous call to this function, then we're
// better off "restarting", going back to the initial data.
// The Dundee code rigs things up to _always_ take 720-minute
// steps from epoch to end time, except for the final step.
// Easiest way to arrange similar behavior in this code is
// just to always do a restart, if we're in Dundee-compliant
// mode.
if (Math.abs(t) < Math.abs(t - atime) || isDundeeCompliant) {
// Epoch restart
atime = 0;
xni = xnq;
xli = xlamo;
}
boolean lastIntegrationStep = false;
// if |step|>|step max| then do one step at step max
while (!lastIntegrationStep) {
double delt = t - atime;
if (delt > SECULAR_INTEGRATION_STEP) {
delt = SECULAR_INTEGRATION_STEP;
} else if (delt < -SECULAR_INTEGRATION_STEP) {
delt = -SECULAR_INTEGRATION_STEP;
} else {
lastIntegrationStep = true;
}
computeSecularDerivs();
final double xldot = xni + xfact;
double xlpow = 1.;
xli += delt * xldot;
xni += delt * derivs[0];
double delt_factor = delt;
for (int j = 2; j <= SECULAR_INTEGRATION_ORDER; ++j) {
xlpow *= xldot;
derivs[j - 1] *= xlpow;
delt_factor *= delt / (double) j;
xli += delt_factor * derivs[j - 2];
xni += delt_factor * derivs[j - 1];
}
atime += delt;
}
xn = xni;
final double temp = -xnode + thgr + t * THDT;
xll = xli + temp + (synchronous ? -omgadf : temp);
}
}
/** Computes periodic terms from current coordinates and epoch.
* @param t offset from initial epoch (min)
*/
protected void deepPeriodicEffects(final double t) {
// If the time didn't change by more than 30 minutes,
// there's no good reason to recompute the perturbations;
// they don't change enough over so short a time span.
// However, the Dundee code _always_ recomputes, so if
// we're attempting to replicate its results, we've gotta
// recompute everything, too.
if ((Math.abs(savtsn - t) >= 30.0) || isDundeeCompliant) {
savtsn = t;
// Update solar perturbations for time T
double zm = zmos + ZNS * t;
double zf = zm + 2 * ZES * Math.sin(zm);
double sinzf = Math.sin(zf);
double f2 = 0.5 * sinzf * sinzf - 0.25;
double f3 = -0.5 * sinzf * Math.cos(zf);
final double ses = se2 * f2 + se3 * f3;
final double sis = si2 * f2 + si3 * f3;
final double sls = sl2 * f2 + sl3 * f3 + sl4 * sinzf;
final double sghs = sgh2 * f2 + sgh3 * f3 + sgh4 * sinzf;
final double shs = sh2 * f2 + sh3 * f3;
// Update lunar perturbations for time T
zm = zmol + ZNL * t;
zf = zm + 2 * ZEL * Math.sin(zm);
sinzf = Math.sin(zf);
f2 = 0.5 * sinzf * sinzf - 0.25;
f3 = -0.5 * sinzf * Math.cos(zf);
final double sel = ee2 * f2 + e3 * f3;
final double sil = xi2 * f2 + xi3 * f3;
final double sll = xl2 * f2 + xl3 * f3 + xl4 * sinzf;
final double sghl = xgh2 * f2 + xgh3 * f3 + xgh4 * sinzf;
final double sh1 = xh2 * f2 + xh3 * f3;
// Sum the solar and lunar contributions
pe = ses + sel;
pinc = sis + sil;
pl = sls + sll;
pgh = sghs + sghl;
ph = shs + sh1;
}
xinc += pinc;
final double sinis = Math.sin( xinc);
final double cosis = Math.cos( xinc);
/* Add solar/lunar perturbation correction to eccentricity: */
em += pe;
xll += pl;
omgadf += pgh;
xinc = MathUtils.normalizeAngle(xinc, 0);
if (Math.abs(xinc) >= 0.2) {
// Apply periodics directly
final double temp_val = ph / sinis;
omgadf -= cosis * temp_val;
xnode += temp_val;
} else {
// Apply periodics with Lyddane modification
final double sinok = Math.sin(xnode);
final double cosok = Math.cos(xnode);
final double alfdp = ph * cosok + (pinc * cosis + sinis) * sinok;
final double betdp = -ph * sinok + (pinc * cosis + sinis) * cosok;
final double delta_xnode = MathUtils.normalizeAngle(Math.atan2(alfdp, betdp) - xnode, 0);
final double dls = -xnode * sinis * pinc;
omgadf += dls - cosis * delta_xnode;
xnode += delta_xnode;
}
}
/** Computes internal secular derivs. */
private void computeSecularDerivs() {
final double sin_li = Math.sin(xli);
final double cos_li = Math.cos(xli);
final double sin_2li = 2. * sin_li * cos_li;
final double cos_2li = 2. * cos_li * cos_li - 1.;
// Dot terms calculated :
if (synchronous) {
final double sin_3li = sin_2li * cos_li + cos_2li * sin_li;
final double cos_3li = cos_2li * cos_li - sin_2li * sin_li;
double term1a = del1 * (sin_li * C_FASX2 - cos_li * S_FASX2);
double term2a = del2 * (sin_2li * C_2FASX4 - cos_2li * S_2FASX4);
double term3a = del3 * (sin_3li * C_3FASX6 - cos_3li * S_3FASX6);
double term1b = del1 * (cos_li * C_FASX2 + sin_li * S_FASX2);
double term2b = 2.0 * del2 * (cos_2li * C_2FASX4 + sin_2li * S_2FASX4);
double term3b = 3.0 * del3 * (cos_3li * C_3FASX6 + sin_3li * S_3FASX6);
for (int j = 0; j < SECULAR_INTEGRATION_ORDER; j += 2) {
derivs[j] = term1a + term2a + term3a;
derivs[j + 1] = term1b + term2b + term3b;
if ((i + 2) < SECULAR_INTEGRATION_ORDER) {
term1a = -term1a;
term2a *= -4.0;
term3a *= -9.0;
term1b = -term1b;
term2b *= -4.0;
term3b *= -9.0;
}
}
} else {
// orbit is a 12-hour resonant one
final double xomi = omegaq + omgdot * atime;
final double sin_omi = Math.sin(xomi);
final double cos_omi = Math.cos(xomi);
final double sin_li_m_omi = sin_li * cos_omi - sin_omi * cos_li;
final double sin_li_p_omi = sin_li * cos_omi + sin_omi * cos_li;
final double cos_li_m_omi = cos_li * cos_omi + sin_omi * sin_li;
final double cos_li_p_omi = cos_li * cos_omi - sin_omi * sin_li;
final double sin_2omi = 2. * sin_omi * cos_omi;
final double cos_2omi = 2. * cos_omi * cos_omi - 1.;
final double sin_2li_m_omi = sin_2li * cos_omi - sin_omi * cos_2li;
final double sin_2li_p_omi = sin_2li * cos_omi + sin_omi * cos_2li;
final double cos_2li_m_omi = cos_2li * cos_omi + sin_omi * sin_2li;
final double cos_2li_p_omi = cos_2li * cos_omi - sin_omi * sin_2li;
final double sin_2li_p_2omi = sin_2li * cos_2omi + sin_2omi * cos_2li;
final double cos_2li_p_2omi = cos_2li * cos_2omi - sin_2omi * sin_2li;
final double sin_2omi_p_li = sin_li * cos_2omi + sin_2omi * cos_li;
final double cos_2omi_p_li = cos_li * cos_2omi - sin_2omi * sin_li;
double term1a = d2201 * (sin_2omi_p_li * C_G22 - cos_2omi_p_li * S_G22) +
d2211 * (sin_li * C_G22 - cos_li * S_G22) +
d3210 * (sin_li_p_omi * C_G32 - cos_li_p_omi * S_G32) +
d3222 * (sin_li_m_omi * C_G32 - cos_li_m_omi * S_G32) +
d5220 * (sin_li_p_omi * C_G52 - cos_li_p_omi * S_G52) +
d5232 * (sin_li_m_omi * C_G52 - cos_li_m_omi * S_G52);
double term2a = d4410 * (sin_2li_p_2omi * C_G44 - cos_2li_p_2omi * S_G44) +
d4422 * (sin_2li * C_G44 - cos_2li * S_G44) +
d5421 * (sin_2li_p_omi * C_G54 - cos_2li_p_omi * S_G54) +
d5433 * (sin_2li_m_omi * C_G54 - cos_2li_m_omi * S_G54);
double term1b = d2201 * (cos_2omi_p_li * C_G22 + sin_2omi_p_li * S_G22) +
d2211 * (cos_li * C_G22 + sin_li * S_G22) +
d3210 * (cos_li_p_omi * C_G32 + sin_li_p_omi * S_G32) +
d3222 * (cos_li_m_omi * C_G32 + sin_li_m_omi * S_G32) +
d5220 * (cos_li_p_omi * C_G52 + sin_li_p_omi * S_G52) +
d5232 * (cos_li_m_omi * C_G52 + sin_li_m_omi * S_G52);
double term2b = 2.0 * (d4410 * (cos_2li_p_2omi * C_G44 + sin_2li_p_2omi * S_G44) +
d4422 * (cos_2li * C_G44 + sin_2li * S_G44) +
d5421 * (cos_2li_p_omi * C_G54 + sin_2li_p_omi * S_G54) +
d5433 * (cos_2li_m_omi * C_G54 + sin_2li_m_omi * S_G54));
for (int j = 0; j < SECULAR_INTEGRATION_ORDER; j += 2) {
derivs[j] = term1a + term2a;
derivs[j + 1] = term1b + term2b;
if ((j + 2) < SECULAR_INTEGRATION_ORDER) {
term1a = -term1a;
term2a *= -4.0;
term1b = -term1b;
term2b *= -4.0;
}
}
}
}
}
| lgpl-3.0 |
dihedron/dihedron-crypto | src/main/java/org/dihedron/crypto/providers/smartcard/discovery/Readers.java | 3020 | /**
* Copyright (c) 2012-2014, Andrea Funto'. All rights reserved. See LICENSE for details.
*/
package org.dihedron.crypto.providers.smartcard.discovery;
import java.security.NoSuchAlgorithmException;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import javax.smartcardio.CardException;
import javax.smartcardio.CardTerminal;
import javax.smartcardio.TerminalFactory;
import org.dihedron.core.License;
import org.dihedron.core.filters.Filter;
import org.dihedron.crypto.exceptions.SmartCardException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* @author Andrea Funtò
*/
@License
public final class Readers {
/**
* The logger.
*/
private static final Logger logger = LoggerFactory.getLogger(Readers.class);
/**
* Enumerates all available readers and returns basic information about
* each of them: their assigned slot, the description and, if a smart card
* is present, its ATR.
*
* @return
* a collection of smart card readers information objects ({@code Reader}s).
* @throws SmartCardException
* if an unrecoverable error occurs while loading the PC/SC layer or
* accessing the smart card reader (terminal) factory object.
*/
public static Collection<Reader> enumerate() throws SmartCardException {
List<Reader> readers = new ArrayList<Reader>();
try {
int slot = 0;
for (CardTerminal terminal : TerminalFactory.getInstance("PC/SC", null).terminals().list()) {
ATR atr = null;
String name = terminal.getName();
try {
logger.trace("connecting to smart card reader '{}' at slot {}...", name, slot);
if(terminal.isCardPresent()) {
logger.trace("... smart card available in reader");
atr = new ATR(terminal.connect("*").getATR().getBytes());
logger.trace("... smart card in reader has ATR '{}'", atr);
}
readers.add(new Reader(slot, name, atr));
} catch(CardException e) {
logger.warn("error accessing reader '" + name + "', it will be ignored", e);
}
slot++;
}
} catch(CardException e) {
logger.error("error accessing the smart card reader (terminal) factory", e);
throw new SmartCardException("error accessing the smart card reader (terminal) factory", e);
} catch (NoSuchAlgorithmException e) {
logger.error("error opening PC/SC provider: it may not be available", e);
throw new SmartCardException("error opening PC/SC provider: it may not be available", e);
}
return readers;
}
/**
* Enumerates the available readers, applying a filter to it.
*
* @param filter
* the filter to be applied.
* @return
* a collection of readers filtered according to the given criteria.
* @throws SmartCardException
*/
public static Collection<Reader> enumerate(Filter<Reader> filter) throws SmartCardException {
Collection<Reader> readers = enumerate();
return Filter.apply(filter, readers);
}
/**
* Private constructor, to prevent instantiation of library.
*/
private Readers() {
}
}
| lgpl-3.0 |
ArticulatedSocialAgentsPlatform/AsapRealizer | Engines/AsapEmitterEngine/src/asap/emitterengine/planunit/CreateEmitterEU.java | 5393 | /*******************************************************************************
* Copyright (C) 2009-2020 Human Media Interaction, University of Twente, the Netherlands
*
* This file is part of the Articulated Social Agents Platform BML realizer (ASAPRealizer).
*
* ASAPRealizer is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License (LGPL) as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* ASAPRealizer 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 Lesser General Public License
* along with ASAPRealizer. If not, see http://www.gnu.org/licenses/.
******************************************************************************/
package asap.emitterengine.planunit;
import hmi.util.StringUtil;
import java.util.List;
import asap.emitterengine.Emitter;
import asap.realizer.feedback.FeedbackManager;
import asap.realizer.pegboard.BMLBlockPeg;
import asap.realizer.planunit.InvalidParameterException;
import asap.realizer.planunit.KeyPosition;
import asap.realizer.planunit.KeyPositionManager;
import asap.realizer.planunit.KeyPositionManagerImpl;
import asap.realizer.planunit.ParameterException;
import asap.realizer.planunit.ParameterNotFoundException;
import asap.realizer.planunit.TimedPlanUnitPlayException;
/**
* Templated class; unit to create an emitter of type <E>
* @author Dennis Reidsma
*/
public class CreateEmitterEU implements EmitterUnit
{
private final KeyPositionManager keyPositionManager = new KeyPositionManagerImpl();
private Emitter theEmitter;
public CreateEmitterEU()
{
KeyPosition start = new KeyPosition("start", 0d, 1d);
addKeyPosition(start);
KeyPosition end = new KeyPosition("end", 1d, 1d);
addKeyPosition(end);
}
public void setEmitter(Emitter emitter)
{
theEmitter = emitter;
}
public Emitter getEmitter()
{
return theEmitter;
}
@Override
public void setFloatParameterValue(String name, float value) throws ParameterException
{
if (theEmitter.specifiesFloatParameter(name))
{
theEmitter.setFloatParameterValue(name, value);
}
else throw new ParameterNotFoundException(name);
}
@Override
public void setParameterValue(String name, String value) throws ParameterException
{
if (theEmitter.specifiesStringParameter(name))
{
theEmitter.setParameterValue(name, value);
}
else
{
if (StringUtil.isNumeric(value) && theEmitter.specifiesFloatParameter(name))
{
theEmitter.setFloatParameterValue(name, Float.parseFloat(value));
}
else
{
throw new InvalidParameterException(name, value);
}
}
}
@Override
public String getParameterValue(String name) throws ParameterException
{
return theEmitter.getParameterValue(name);
}
@Override
public float getFloatParameterValue(String name) throws ParameterException
{
if (theEmitter.specifiesFloatParameter(name))
{
return theEmitter.getFloatParameterValue(name);
}
throw new ParameterNotFoundException(name);
}
@Override
public boolean hasValidParameters()
{
return theEmitter.hasValidParameters();
}
public void startUnit(double time) throws TimedPlanUnitPlayException
{
// start the emitter
theEmitter.start();
}
/**
*
* @param t
* execution time, 0 < t < 1
* @throws EUPlayException
* if the play fails for some reason
*/
public void play(double t) throws EUPlayException
{
}
public void cleanup()
{
theEmitter.stop();
}
/**
* Creates the TimedEmitterUnit corresponding to this face unit
*
* @param bmlId
* BML block id
* @param id
* behaviour id
*
* @return the TEU
*/
@Override
public TimedEmitterUnit createTEU(FeedbackManager bfm, BMLBlockPeg bbPeg, String bmlId, String id)
{
return new TimedEmitterUnit(bfm, bbPeg, bmlId, id, this);
}
/**
* @return Prefered duration (in seconds) of this unit, 0 means not determined/infinite
*/
public double getPreferedDuration()
{
return 0d;
}
@Override
public void addKeyPosition(KeyPosition kp)
{
keyPositionManager.addKeyPosition(kp);
}
@Override
public KeyPosition getKeyPosition(String name)
{
return keyPositionManager.getKeyPosition(name);
}
@Override
public List<KeyPosition> getKeyPositions()
{
return keyPositionManager.getKeyPositions();
}
@Override
public void setKeyPositions(List<KeyPosition> p)
{
keyPositionManager.setKeyPositions(p);
}
@Override
public void removeKeyPosition(String id)
{
keyPositionManager.removeKeyPosition(id);
}
}
| lgpl-3.0 |
SupaHam/420BlazeIt | src/main/java/com/supaham/_420blazeit/PuffPuffDaddy.java | 7454 | package com.supaham._420blazeit;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.Effect;
import org.bukkit.Location;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerJoinEvent;
import org.bukkit.event.player.PlayerQuitEvent;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitRunnable;
import java.util.HashSet;
import java.util.Set;
public class PuffPuffDaddy extends JavaPlugin implements Listener {
private final Set<Player> smokers = new HashSet<>();
private final Set<Player> dontShow = new HashSet<>();
private int interval, particleAmount, radius;
private float speed, distanceFromMouth, offset;
private boolean smokeInRain;
private FuckingSmokers task;
@Override
public void onEnable() {
reload();
getServer().getPluginManager().registerEvents(this, this);
}
@EventHandler
public void smokersSpreadingTheirAidsOnTheServer(PlayerJoinEvent event) {
if (event.getPlayer().hasPermission("420blazeit.onjoin")) {
this.smokers.add(event.getPlayer());
}
}
@EventHandler
public void smokersPussyingOut(PlayerQuitEvent event) {
this.smokers.remove(event.getPlayer());
this.dontShow.remove(event.getPlayer());
}
private void reload() {
int oldInterval = interval;
reloadConfig();
FileConfiguration config = getConfig();
config.addDefault("smoke-interval", 3);
config.addDefault("particle-speed", 0.01);
config.addDefault("particle-amount", 3);
config.addDefault("particle-radius", 32);
config.addDefault("particle-dist-from-mouth", 0.4);
config.addDefault("smoke-in-rain", false);
config.addDefault("offset-from-mouth", 30.0);
config.options().copyDefaults(true);
saveConfig();
this.interval = config.getInt("smoke-interval");
if (this.interval < 0) {
this.interval = 0;
}
this.particleAmount = config.getInt("particle-amount");
this.radius = config.getInt("particle-radius");
this.speed = (float) config.getDouble("particle-speed");
this.distanceFromMouth = (float) config.getDouble("particle-dist-from-mouth");
this.smokeInRain = config.getBoolean("smoke-in-rain");
this.offset = (float) config.getDouble("offset-from-mouth");
if (this.interval != oldInterval || this.task == null) {
if (this.task != null) {
this.task.cancel();
this.task = null;
}
(this.task = new FuckingSmokers()).runTaskTimer(this, 0, interval);
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
if (label.equalsIgnoreCase("420blazeit")) {
if (args.length > 0) {
if (args[0].equalsIgnoreCase("reload")) {
if (!sender.hasPermission("420blazeit.reload")) {
sender.sendMessage(ChatColor.RED + "No permissions, bruuuh.");
return true;
}
reload();
sender.sendMessage(ChatColor.YELLOW + "You successfully blazed the config.");
return true;
} else if (args[0].equalsIgnoreCase("with")) {
if (args.length <= 1) {
sender.sendMessage(ChatColor.RED + "Who do you want to blaze it with?");
return true;
}
Player player = Bukkit.getPlayer(args[1]);
if (player == null) {
sender.sendMessage(ChatColor.RED + args[1] + " is not available to blaze it with you.");
return true;
}
this.smokers.add(player);
sender.sendMessage(ChatColor.YELLOW + "You successfully 420blazedit with "
+ args[1] + ".");
return true;
} else {
sender.sendMessage(ChatColor.RED + "Unknown subcommand. Available subcommands: "
+ "reload, with.");
return true;
}
} else {
if (sender instanceof Player) {
if (!sender.hasPermission("420blazeit.smoke")) {
sender.sendMessage(ChatColor.RED + "You're not cool enough to blaze.");
return true;
}
this.smokers.add(((Player) sender));
this.dontShow.remove(sender);
sender.sendMessage(ChatColor.GREEN + "420blazeit.");
return true;
}
}
} else if (label.equalsIgnoreCase("iquit")) {
if (sender instanceof Player) {
if (!sender.hasPermission("420blazeit.quit")) {
sender.sendMessage(ChatColor.RED + "Once you smoke, you can't go broke, or something like that...");
return true;
}
if (args.length > 0) {
this.dontShow.add(((Player) sender));
sender.sendMessage(ChatColor.GRAY + "You can only lie to yourself for so long...");
} else {
this.smokers.remove(sender);
this.dontShow.remove(sender);
sender.sendMessage(ChatColor.GREEN + "You did it, congratulations! How many years did you waste " +
"in Narcotics Anonymous?");
}
return true;
}
}
sender.sendMessage(ChatColor.RED + "You're a computer, you can't blaze it.");
return true;
}
public class FuckingSmokers extends BukkitRunnable {
@Override
public void run() {
for (Player smoker : smokers) {
if ((!smokeInRain && smoker.getWorld().hasStorm())) {
continue;
}
double distance = distanceFromMouth;
Location player_loc = smoker.getLocation();
double rot_x = ((player_loc.getYaw() + 90.0F + offset) % 360.0F);
double rot_y = player_loc.getPitch() * -1.0F;
double h_length = distance * Math.cos(Math.toRadians(rot_y));
double yOff = distance * Math.sin(Math.toRadians(rot_y));
double xOff = h_length * Math.cos(Math.toRadians(rot_x));
double zOff = h_length * Math.sin(Math.toRadians(rot_x));
Location loc = new Location(smoker.getWorld(), xOff + player_loc.getX(),
yOff + player_loc.getY() + 1.5D, zOff + player_loc.getZ());
for (Player player : smoker.getWorld().getPlayers()) {
if (!player.equals(smoker) || !dontShow.contains(smoker)) {
player.spigot().playEffect(loc, Effect.PARTICLE_SMOKE, 0, 0, 0, 0, 0,
speed, particleAmount, radius);
}
}
}
}
}
}
| lgpl-3.0 |
robeio/robe | robe-mail/src/test/java/io/robe/mail/MailManagerTest.java | 1358 | package io.robe.mail;
import org.junit.Test;
import javax.activation.DataSource;
import java.util.Arrays;
import java.util.HashMap;
public class MailManagerTest {
@Test
public void sendMail() throws Exception {
MailItem item1 = new MailItem("title", "body", (DataSource) null, "sender", "receiver");
MailItem item2 = new MailItem("title", "body", (DataSource) null, "sender", Arrays.asList("receiver"));
MailEvent event = new MailEvent() {
@Override
public void before(MailItem item) {
}
@Override
public void success(MailItem item) {
}
@Override
public void error(MailItem item, Exception e) {
}
};
item2.setEvent(event);
assert MailManager.sendMail(item1);
assert MailManager.sendMail(item2);
assert !MailManager.hasConfiguration();
MailConfiguration configuration = new MailConfiguration();
configuration.setPasswordKey("password");
configuration.setUsernameKey("username");
configuration.setProperties(new HashMap<String, Object>());
MailSender sender = new MailSender(configuration);
MailManager.setSender(sender);
assert MailManager.sendMail(item2);
assert MailManager.sendMail(item1);
}
} | lgpl-3.0 |
lbndev/sonarqube | server/sonar-server/src/main/java/org/sonar/server/user/index/package-info.java | 968 | /*
* SonarQube
* Copyright (C) 2009-2017 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.
*/
@ParametersAreNonnullByDefault
package org.sonar.server.user.index;
import javax.annotation.ParametersAreNonnullByDefault;
| lgpl-3.0 |
sghr/iGeo | gui/IMouseWheelEvent.java | 1594 | /*---
iGeo - http://igeo.jp
Copyright (c) 2002-2013 Satoru Sugihara
This file is part of iGeo.
iGeo 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 3.
iGeo 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 iGeo. If not, see <http://www.gnu.org/licenses/>.
---*/
package igeo.gui;
import java.awt.*;
import java.awt.event.*;
/**
Abstracted mouse wheel event
@author Satoru Sugihara
*/
public class IMouseWheelEvent{
public int rotation;
public int scrollAmount;
public int scrollType;
public IMouseWheelEvent(){}
public IMouseWheelEvent(int rot){ rotation = rot; }
public IMouseWheelEvent(MouseWheelEvent e){
rotation = e.getWheelRotation();
scrollAmount = e.getScrollAmount();
scrollType = e.getScrollType();
}
// doesn't compile in processing 1.5
public IMouseWheelEvent(processing.event.MouseEvent e){
rotation = e.getCount();
scrollAmount = 1; // not sure
scrollType = MouseWheelEvent.WHEEL_UNIT_SCROLL;
}
public int getScrollAmount(){ return scrollAmount; }
public int getScrollType(){ return scrollType; }
public int getWheelRotation(){ return rotation; }
}
| lgpl-3.0 |
kbss-cvut/jopa | ontodriver-owlapi/src/main/java/cz/cvut/kbss/ontodriver/owlapi/InferredAxiomLoader.java | 5793 | /**
* Copyright (C) 2022 Czech Technical University in Prague
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU General Public License as published by the Free Software
* Foundation, either version 3 of the License, or (at your option) any
* later version.
*
* This program is distributed in the hope that it will be useful, but WITHOUT
* ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS
* FOR A PARTICULAR PURPOSE. See the GNU General Public License for more
* details. You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package cz.cvut.kbss.ontodriver.owlapi;
import cz.cvut.kbss.ontodriver.model.*;
import cz.cvut.kbss.ontodriver.owlapi.connector.OntologySnapshot;
import cz.cvut.kbss.ontodriver.owlapi.exception.ReasonerNotAvailableException;
import cz.cvut.kbss.ontodriver.owlapi.util.OwlapiUtils;
import org.semanticweb.owlapi.model.*;
import org.semanticweb.owlapi.reasoner.OWLReasoner;
import java.util.*;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class InferredAxiomLoader implements AxiomLoader {
private final OWLReasoner reasoner;
private final OWLOntology ontology;
private final OWLDataFactory dataFactory;
private final OwlapiAdapter adapter;
private final AxiomAdapter axiomAdapter;
private NamedResource subject;
InferredAxiomLoader(OwlapiAdapter adapter, OntologySnapshot snapshot) {
this.adapter = adapter;
this.reasoner = snapshot.getReasoner();
this.ontology = snapshot.getOntology();
this.dataFactory = snapshot.getDataFactory();
this.axiomAdapter = new AxiomAdapter(snapshot.getDataFactory());
}
@Override
public Collection<Axiom<?>> loadAxioms(NamedResource subject, Set<Assertion> assertions) {
this.subject = subject;
if (assertions.isEmpty()) {
return Collections.emptySet();
}
if (reasoner == null) {
throw new ReasonerNotAvailableException();
}
reasoner.flush();
final OWLNamedIndividual individual = OwlapiUtils.getIndividual(subject, dataFactory);
final Collection<Axiom<?>> axioms = new HashSet<>();
for (Assertion a : assertions) {
switch (a.getType()) {
case CLASS:
axioms.addAll(adapter.getTypesHandler().getTypes(subject, null, true));
break;
case DATA_PROPERTY:
axioms.addAll(inferDataPropertyValues(individual, a));
break;
case OBJECT_PROPERTY:
axioms.addAll(inferObjectPropertyValues(individual, a));
break;
case PROPERTY:
// When we don't know, try all
axioms.addAll(adapter.getTypesHandler().getTypes(subject, null, true));
axioms.addAll(inferDataPropertyValues(individual, a));
axioms.addAll(inferObjectPropertyValues(individual, a));
break;
default:
break;
}
}
return axioms;
}
private Collection<Axiom<?>> inferDataPropertyValues(OWLNamedIndividual individual, Assertion dpAssertion) {
final Set<OWLLiteral> literals = reasoner.getDataPropertyValues(individual, dataProperty(dpAssertion));
return literals.stream().filter(lit -> OwlapiUtils.doesLanguageMatch(lit, dpAssertion))
.map(owlLiteral -> new AxiomImpl<>(subject, dpAssertion,
new Value<>(OwlapiUtils.owlLiteralToValue(owlLiteral)))).collect(Collectors.toSet());
}
private OWLDataProperty dataProperty(Assertion dataPropertyAssertion) {
return dataFactory.getOWLDataProperty(IRI.create(dataPropertyAssertion.getIdentifier()));
}
private Collection<Axiom<?>> inferObjectPropertyValues(OWLNamedIndividual individual, Assertion opAssertion) {
final Stream<OWLNamedIndividual> individuals =
reasoner.getObjectPropertyValues(individual, objectProperty(opAssertion)).entities();
return individuals.map(
target -> axiomAdapter.createAxiom(subject, opAssertion, NamedResource.create(target.getIRI().toURI())))
.collect(
Collectors.toList());
}
private OWLObjectProperty objectProperty(Assertion objectPropertyAssertion) {
return dataFactory.getOWLObjectProperty(IRI.create(objectPropertyAssertion.getIdentifier()));
}
@Override
public Collection<Axiom<?>> loadPropertyAxioms(NamedResource subject) {
final Collection<Axiom<?>> axioms = new ArrayList<>();
final OWLNamedIndividual individual = OwlapiUtils.getIndividual(subject, dataFactory);
ontology.dataPropertiesInSignature().forEach(dp -> {
final Set<OWLLiteral> values = reasoner.getDataPropertyValues(individual, dp);
for (OWLLiteral literal : values) {
axioms.add(axiomAdapter.createAxiom(subject,
Assertion.createDataPropertyAssertion(dp.getIRI().toURI(), true), literal));
}
});
ontology.objectPropertiesInSignature().forEach(op -> {
final Assertion opAss = Assertion.createObjectPropertyAssertion(op.getIRI().toURI(), true);
reasoner.getObjectPropertyValues(individual, op).entities()
.forEach(ind -> axioms
.add(axiomAdapter.createAxiom(subject, opAss, NamedResource.create(ind.getIRI().toURI()))));
});
return axioms;
}
}
| lgpl-3.0 |
4Space/4Space-1.7 | src/main/java/mattparks/mods/space/io/world/gen/WorldChunkManagerIo.java | 317 | package mattparks.mods.space.io.world.gen;
import micdoodle8.mods.galacticraft.api.prefab.world.gen.WorldChunkManagerSpace;
import net.minecraft.world.biome.BiomeGenBase;
public class WorldChunkManagerIo extends WorldChunkManagerSpace {
@Override
public BiomeGenBase getBiome() {
return BiomeGenBaseIo.io;
}
}
| lgpl-3.0 |
cismet/cismap-commons | src/main/java/de/cismet/cismap/commons/gui/piccolo/eventlistener/DeleteFeatureListener.java | 14166 | /***************************************************
*
* cismet GmbH, Saarbruecken, Germany
*
* ... and it just works.
*
****************************************************/
/*
* DeleteFeatureListener.java
*
* Created on 20. April 2005, 11:22
*/
package de.cismet.cismap.commons.gui.piccolo.eventlistener;
import com.vividsolutions.jts.geom.*;
import edu.umd.cs.piccolo.PNode;
import edu.umd.cs.piccolo.event.PBasicInputEventHandler;
import edu.umd.cs.piccolo.event.PInputEvent;
import edu.umd.cs.piccolo.nodes.PPath;
import edu.umd.cs.piccolo.nodes.PText;
import edu.umd.cs.piccolox.event.PNotificationCenter;
import java.awt.Color;
import java.awt.Font;
import java.awt.geom.RoundRectangle2D;
import java.util.Arrays;
import java.util.Collection;
import java.util.Comparator;
import de.cismet.cismap.commons.CrsTransformer;
import de.cismet.cismap.commons.features.Feature;
import de.cismet.cismap.commons.gui.MappingComponent;
import de.cismet.cismap.commons.gui.piccolo.PFeature;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.actions.FeatureAddEntityAction;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.actions.FeatureAddHoleAction;
import de.cismet.cismap.commons.gui.piccolo.eventlistener.actions.FeatureCreateAction;
import de.cismet.cismap.commons.tools.PFeatureTools;
/**
* DOCUMENT ME!
*
* @author hell
* @version $Revision$, $Date$
*/
public class DeleteFeatureListener extends PBasicInputEventHandler implements DeregistrationListener {
//~ Static fields/initializers ---------------------------------------------
private static final org.apache.log4j.Logger LOG = org.apache.log4j.Logger.getLogger(DeleteFeatureListener.class);
public static final String FEATURE_DELETE_REQUEST_NOTIFICATION = "FEATURE_DELETE_REQUEST_NOTIFICATION"; // NOI18N
private static final ClassComparator comparator = new ClassComparator();
//~ Instance fields --------------------------------------------------------
private PFeature featureRequestedForDeletion = null;
private final InvalidPolygonTooltip multiPolygonPointerAnnotation = new InvalidPolygonTooltip();
private final MappingComponent mc;
private Class[] allowedFeatureClassesToDelete = null;
//~ Constructors -----------------------------------------------------------
/**
* Creates a new DeleteFeatureListener object.
*
* @param mc DOCUMENT ME!
*/
public DeleteFeatureListener(final MappingComponent mc) {
this.mc = mc;
mc.getCamera().addChild(multiPolygonPointerAnnotation);
}
//~ Methods ----------------------------------------------------------------
@Override
public void mouseMoved(final PInputEvent pInputEvent) {
multiPolygonPointerAnnotation.setOffset(
pInputEvent.getCanvasPosition().getX()
+ 20.0d,
pInputEvent.getCanvasPosition().getY()
+ 20.0d);
final Collection selectedFeatures = mc.getFeatureCollection().getSelectedFeatures();
if (selectedFeatures.size() != 1) {
if (pInputEvent.isAltDown()) {
multiPolygonPointerAnnotation.setMode(InvalidPolygonTooltip.Mode.SELECT_FEATURE);
multiPolygonPointerAnnotation.setVisible(true);
} else {
multiPolygonPointerAnnotation.setVisible(false);
}
} else {
multiPolygonPointerAnnotation.setVisible(false);
}
}
@Override
public void mouseClicked(final edu.umd.cs.piccolo.event.PInputEvent pInputEvent) {
super.mouseClicked(pInputEvent);
if (pInputEvent.getComponent() instanceof MappingComponent) {
final MappingComponent mappingComponent = (MappingComponent)pInputEvent.getComponent();
final PFeature clickedPFeature = (PFeature)PFeatureTools.getFirstValidObjectUnderPointer(
pInputEvent,
new Class[] { PFeature.class },
true);
if ((clickedPFeature != null) && (clickedPFeature.getFeature() != null)
&& (allowedFeatureClassesToDelete != null)
&& (Arrays.binarySearch(
allowedFeatureClassesToDelete,
clickedPFeature.getFeature().getClass(),
comparator) < 0)) {
return;
}
if (pInputEvent.isAltDown()) { // alt-modifier => speziall-handling für
// multipolygone
final Collection selectedFeatures = mappingComponent.getFeatureCollection().getSelectedFeatures();
if (selectedFeatures.size() == 1) { // es ist genau ein feature selektiert
final PFeature selectedPFeature = mappingComponent.getPFeatureHM()
.get((Feature)selectedFeatures.toArray()[0]);
if ((selectedPFeature != null) && selectedPFeature.getFeature().canBeSelected()
&& selectedPFeature.getFeature().isEditable()
&& ((selectedPFeature.getFeature().getGeometry() instanceof MultiPolygon)
|| (selectedPFeature.getFeature().getGeometry() instanceof Polygon))) {
if ((selectedPFeature.getNumOfEntities() == 1) && (selectedPFeature.equals(clickedPFeature))) { // hat nur ein teil-polygon
// "normales" löschen des geklickten features
deletePFeature(selectedPFeature, mappingComponent);
} else { // hat mehrere teil-polygone
// koordinate der maus berechnen
final Coordinate mouseCoord = new Coordinate(
mappingComponent.getWtst().getSourceX(
pInputEvent.getPosition().getX()
- mappingComponent.getClip_offset_x()),
mappingComponent.getWtst().getSourceY(
pInputEvent.getPosition().getY()
- mappingComponent.getClip_offset_y()));
// teil-polygon unter der maus suchen
final GeometryFactory geometryFactory = new GeometryFactory(
new PrecisionModel(PrecisionModel.FLOATING),
CrsTransformer.extractSridFromCrs(
mappingComponent.getMappingModel().getSrs().getCode()));
final Point mousePoint = CrsTransformer.transformToGivenCrs(geometryFactory.createPoint(
mouseCoord),
CrsTransformer.createCrsFromSrid(
selectedPFeature.getFeature().getGeometry().getSRID()));
final int selectedEntityPosition = selectedPFeature.getEntityPositionUnderPoint(mousePoint);
if (selectedEntityPosition >= 0) { // gefunden => teil-polygon entfernen
final Polygon entity = selectedPFeature.getEntityByPosition(selectedEntityPosition);
selectedPFeature.removeEntity(selectedEntityPosition);
mappingComponent.getMemUndo()
.addAction(new FeatureAddEntityAction(
mappingComponent,
selectedPFeature.getFeature(),
entity));
mappingComponent.getMemRedo().clear();
} else { // nicht gefunden => es muss also ein loch sein => suchen
// und entfernen (komplex)
final int entityPosition = selectedPFeature.getMostInnerEntityUnderPoint(mousePoint);
final int holePosition = selectedPFeature.getHolePositionUnderPoint(
mousePoint,
entityPosition);
final LineString hole = selectedPFeature.getHoleByPosition(
entityPosition,
holePosition);
selectedPFeature.removeHoleUnderPoint(mousePoint);
mappingComponent.getMemUndo()
.addAction(new FeatureAddHoleAction(
mappingComponent,
selectedPFeature.getFeature(),
entityPosition,
hole));
mappingComponent.getMemRedo().clear();
}
}
}
} else { // mehrere features selektiert => alt-selektionsmodus
if (clickedPFeature != null) {
mappingComponent.getFeatureCollection().select(clickedPFeature.getFeature());
}
}
} else { // alt-modifier nicht gedrückt
if (clickedPFeature != null) {
// geklicktes feature entfernen
deletePFeature(clickedPFeature, mappingComponent);
}
}
}
}
/**
* DOCUMENT ME!
*
* @param pFeature DOCUMENT ME!
* @param mappingComponent DOCUMENT ME!
*/
private void deletePFeature(final PFeature pFeature, final MappingComponent mappingComponent) {
if (pFeature.getFeature().isEditable() && pFeature.getFeature().canBeSelected()) {
featureRequestedForDeletion = (PFeature)pFeature.clone();
mappingComponent.getFeatureCollection().removeFeature(pFeature.getFeature());
mappingComponent.getMemUndo().addAction(new FeatureCreateAction(mappingComponent, pFeature.getFeature()));
mappingComponent.getMemRedo().clear();
postFeatureDeleteRequest();
}
}
/**
* DOCUMENT ME!
*/
private void postFeatureDeleteRequest() {
final PNotificationCenter pn = PNotificationCenter.defaultCenter();
pn.postNotification(FEATURE_DELETE_REQUEST_NOTIFICATION, this);
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public PFeature getFeatureRequestedForDeletion() {
return featureRequestedForDeletion;
}
/**
* DOCUMENT ME!
*
* @return the allowedFeatrueClassesToDelete
*/
public Class[] getAllowedFeatureClassesToDelete() {
return allowedFeatureClassesToDelete;
}
/**
* Set the feature types, which are allowed to remove. If null is set, all feature types are allowed to remove. The
* given array will be sorted.
*
* @param allowedFeatureClassesToDelete the allowedFeatrueClassesToDelete to set
*/
public void setAllowedFeatureClassesToDelete(final Class[] allowedFeatureClassesToDelete) {
this.allowedFeatureClassesToDelete = allowedFeatureClassesToDelete;
if (allowedFeatureClassesToDelete != null) {
Arrays.sort(this.allowedFeatureClassesToDelete, comparator);
}
}
@Override
public void deregistration() {
if ((multiPolygonPointerAnnotation != null) && multiPolygonPointerAnnotation.getVisible()) {
multiPolygonPointerAnnotation.setVisible(false);
}
}
//~ Inner Classes ----------------------------------------------------------
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
class Tooltip extends PNode {
//~ Instance fields ----------------------------------------------------
private final Color COLOR_BACKGROUND = new Color(255, 255, 222, 200);
//~ Constructors -------------------------------------------------------
/**
* Creates a new Tooltip object.
*
* @param text DOCUMENT ME!
*/
public Tooltip(final String text) {
final PText pText = new PText(text);
final Font defaultFont = pText.getFont();
final Font boldDefaultFont = new Font(defaultFont.getName(),
defaultFont.getStyle()
+ Font.BOLD,
defaultFont.getSize());
pText.setFont(boldDefaultFont);
pText.setOffset(5, 5);
final PPath background = new PPath(new RoundRectangle2D.Double(
0,
0,
pText.getWidth()
+ 15,
pText.getHeight()
+ 15,
10,
10));
background.setPaint(COLOR_BACKGROUND);
background.addChild(pText);
setTransparency(0.85f);
addChild(background);
}
}
/**
* DOCUMENT ME!
*
* @version $Revision$, $Date$
*/
private static class ClassComparator implements Comparator<Class> {
//~ Methods ------------------------------------------------------------
@Override
public int compare(final Class o1, final Class o2) {
return o1.getName().compareTo(o2.getName());
}
}
}
| lgpl-3.0 |
esporx-tv/esporx | src/test/java/tv/esporx/domain/front/ConfigurableSlotTest.java | 1627 | package tv.esporx.domain.front;
import org.junit.Before;
import org.junit.Test;
import tv.esporx.domain.ConfigurableSlot;
import static org.fest.assertions.Assertions.assertThat;
public class ConfigurableSlotTest {
private ConfigurableSlot slot;
@Before
public void setup() {
slot = new ConfigurableSlot();
}
@Test
public void when_getting_id_then_must_be_positive() {
assertThat(slot.getId()).isGreaterThanOrEqualTo(0L);
}
@Test
public void when_instanciating_then_description_is_empty() {
assertThat(slot.getDescription()).isEmpty();
}
@Test
public void when_instanciating_then_link_is_empty() {
assertThat(slot.getLink()).isEmpty();
}
@Test
public void when_instanciating_then_picture_is_empty() {
assertThat(slot.getPicture()).isEmpty();
}
@Test
public void when_instanciating_then_title_is_empty() {
assertThat(slot.getTitle()).isEmpty();
}
@Test
public void when_setting_description_then_is_retrieved() {
String description = "This is a description";
slot.setDescription(description);
assertThat(slot.getDescription()).isEqualTo(description);
}
@Test
public void when_setting_link_then_is_retrieved() {
String link = "http://www.google.cn";
slot.setLink(link);
assertThat(slot.getLink()).isEqualTo(link);
}
@Test
public void when_setting_picture_then_is_retrieved() {
String picture = "toto.png";
slot.setPicture(picture);
assertThat(slot.getPicture()).isEqualTo(picture);
}
@Test
public void when_setting_title_then_is_retrieved() {
String title = "This is a title";
slot.setTitle(title);
assertThat(slot.getTitle()).isEqualTo(title);
}
}
| lgpl-3.0 |
pjgrace/connect-iot | src/main/java/uk/ac/soton/itinnovation/xifiinteroperability/guitool/editor/GraphGenerator.java | 19949 | /////////////////////////////////////////////////////////////////////////
//
// © University of Southampton IT Innovation Centre, 2015
//
// Copyright in this library belongs to the University of Southampton
// University Road, Highfield, Southampton, UK, SO17 1BJ
//
// This software may not be used, sold, licensed, transferred, copied
// or reproduced in whole or in part in any manner or form or in or
// on any media by any person other than in accordance with the terms
// of the Licence Agreement supplied with the software, or otherwise
// without the prior written consent of the copyright owners.
//
// This software is distributed WITHOUT ANY WARRANTY, without even the
// implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
// PURPOSE, except where stated in the Licence Agreement supplied with
// the software.
//
// Created By : Paul Grace
// Created for Project : XIFI (http://www.fi-xifi.eu)
//
/////////////////////////////////////////////////////////////////////////
//
// License : GNU Lesser General Public License, version 3
//
/////////////////////////////////////////////////////////////////////////
package uk.ac.soton.itinnovation.xifiinteroperability.guitool.editor;
import com.mxgraph.model.mxCell;
import com.mxgraph.model.mxGeometry;
import com.mxgraph.model.mxGraphModel;
import com.mxgraph.view.mxGraph;
import java.io.IOException;
import java.io.StringReader;
import javax.swing.JOptionPane;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import org.w3c.dom.DOMException;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.xml.sax.InputSource;
import org.xml.sax.SAXException;
import uk.ac.soton.itinnovation.xifiinteroperability.ServiceLogger;
import uk.ac.soton.itinnovation.xifiinteroperability.guitool.data.ArchitectureNode;
import uk.ac.soton.itinnovation.xifiinteroperability.guitool.data.DataModel;
import uk.ac.soton.itinnovation.xifiinteroperability.guitool.data.Function;
import uk.ac.soton.itinnovation.xifiinteroperability.guitool.data.GraphNode;
import uk.ac.soton.itinnovation.xifiinteroperability.guitool.data.Guard;
import uk.ac.soton.itinnovation.xifiinteroperability.guitool.data.Message;
import uk.ac.soton.itinnovation.xifiinteroperability.modelframework.InvalidPatternException;
import uk.ac.soton.itinnovation.xifiinteroperability.modelframework.specification.XMLStateMachine;
/**
* Code to generate XML documents from a drawn graphical representation. That is
* a state machine diagram to an xml specification. The methods also do the reverse
* i.e. take an xml specification and draw a graph.
* @author pjg
*/
public class GraphGenerator {
/**
* The behaviour Graph to/from convert to xml.
*/
private final transient mxGraph graphPanel;
/**
* The system graph to/from convert to xml.
*/
private final transient mxGraph archPanel;
/**
* The data model elements to leverage in specifying the xml.
*/
private final transient DataModel dataModel;
/**
* The position to draw on horizontal axis.
*/
private transient double currentHorizontal = 75.0;
/**
* The position to draw on the vertical axis.
*/
private transient double currentVertical = 50.0;
/**
* Reference to UI object
*/
private final transient BasicGraphEditor UIEditor;
/**
* Configure the graph/specification generator.
* @param editor The graph UI object to extract elements from.
*/
public GraphGenerator(final BasicGraphEditor editor) {
this.graphPanel = editor.getBehaviourGraph().getGraph();
this.archPanel = editor.getSystemGraph().getGraph();
this.dataModel = editor.getDataModel();
this.UIEditor = editor;
}
/**
* Given a xml string create a java object of the document.
* @param xml The xml input
* @return The java object of the document.
* @throws SAXException XML exception
* @throws IOException input exception
* @throws ParserConfigurationException XML parser set up problem.
*/
public static Document loadXMLFromString(final String xml) throws SAXException, IOException, ParserConfigurationException {
final DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
final DocumentBuilder builder = factory.newDocumentBuilder();
final InputSource inSource = new InputSource(new StringReader(xml));
return builder.parse(inSource);
}
private void addMessageTransition(final String fromID, final Element eElement, mxCell myCell3) throws XMLInputException {
final Message message = (Message) dataModel.getTransition(myCell3.getId());
final NodeList msgDataList = eElement.getElementsByTagName("message");
if (msgDataList == null || msgDataList.getLength() == 0) {
throw new XMLInputException("The <message> tag is missing, or incorrect in the " + fromID + "<transition>");
}
final Node msgData = msgDataList.item(0);
if (((Element) msgData).getElementsByTagName("url") == null) {
throw new XMLInputException("The <url> tag is missing, or incorrect in the " + fromID + "<transition>");
}
final String url = ((Element) msgData).getElementsByTagName("url").item(0).getTextContent();
if (((Element) msgData).getElementsByTagName("path").item(0) == null) {
throw new XMLInputException("The <path> tag is missing, or incorrect in the " + fromID + "<transition>");
}
final String path = ((Element) msgData).getElementsByTagName("path").item(0).getTextContent();
if (((Element) msgData).getElementsByTagName("method") == null) {
throw new XMLInputException("The <method> tag is missing, or incorrect in the " + fromID + "<transition>");
}
final String method = ((Element) msgData).getElementsByTagName("method").item(0).getTextContent();
if (((Element) msgData).getElementsByTagName("type") == null) {
throw new XMLInputException("The <type> tag is missing, or incorrect in the " + fromID + "<transition>");
}
final String type = ((Element) msgData).getElementsByTagName("type").item(0).getTextContent();
if (((Element) msgData).getElementsByTagName("body") == null) {
throw new XMLInputException("The <body> tag is missing, or incorrect in the " + fromID + "<transition>");
}
final NodeList bodyTag = ((Element) msgData).getElementsByTagName("body");
String body = "";
if (bodyTag.getLength() > 0) {
body = bodyTag.item(0).getTextContent();
}
message.addMessage(url, path, method, type, body);
final NodeList headers = eElement.getElementsByTagName("header");
for (int j = 0; j < headers.getLength(); j++) {
final String param = ((Element) headers.item(j)).getElementsByTagName("name").item(0).getTextContent();
final String value = ((Element) headers.item(j)).getElementsByTagName("value").item(0).getTextContent();
message.addHeader(param, value);
}
}
/**
* Generate a series of transitions from the xml input and then add them
* to the data model which forms the basis of the newly drawn graph.
*
* @param fromID The source ID of the transition - the GUI id.
* @param eElement The xml description of the transition.
*/
private void generateTransitions(final String fromID, final Element eElement)
throws XMLInputException{
try {
// Get the info about the two from nodes in the graph to draw connection.
final String toNode = eElement.getElementsByTagName("to").item(0).getTextContent();
if (toNode == null) {
throw new XMLInputException("The <to> tag is missing, or incorrect in the " + fromID + "<transition>");
}
final GraphNode toID = (GraphNode) dataModel.getNodeByLabel(toNode);
final GraphNode from = (GraphNode) dataModel.getNode(fromID);
final Object parent = graphPanel.getDefaultParent();
// Insert the edge into the visual graph
final mxCell myCell1 = (mxCell) ((mxGraphModel) graphPanel.getModel()).getCell(from.getUIIdentifier());
final mxCell myCell2 = (mxCell) ((mxGraphModel) graphPanel.getModel()).getCell(toID.getUIIdentifier());
final mxCell myCell3 = (mxCell) graphPanel.insertEdge(parent, null, "", myCell1, myCell2);
// update the data model with new connection
dataModel.addConnection(myCell3.getId(), fromID, toID.getUIIdentifier());
// Add the attribute data to the connection (message/guard data)
final String nodeType = from.getType();
if (nodeType.equalsIgnoreCase(XMLStateMachine.TRIGGER_LABEL) || nodeType.equalsIgnoreCase(XMLStateMachine.TRIGGERSTART_LABEL)) {
addMessageTransition(fromID, eElement, myCell3);
}
else if (nodeType.equalsIgnoreCase(XMLStateMachine.LOOP_LABEL) && eElement.getElementsByTagName("guards").getLength() == 0) {
addMessageTransition(fromID, eElement, myCell3);
}
else {
final Guard guardData = (Guard) dataModel.getTransition(myCell3.getId());
if (guardData != null) {
final NodeList guards = eElement.getElementsByTagName("guards").item(0).getChildNodes();
for (int i = 0; i < guards.getLength(); i++) {
final Node currentItem = guards.item(i);
if (currentItem.getNodeType() != 3) {
final String fName = currentItem.getNodeName();
final String param = ((Element) currentItem).getElementsByTagName("param").item(0).getTextContent();
final String value = ((Element) currentItem).getElementsByTagName("value").item(0).getTextContent();
guardData.addGuard(Function.getFunction(fName), param, value);
}
}
}
}
} catch (DOMException ex) {
ServiceLogger.LOG.error("Error creating graph - could not generate xml transitions", ex);
}
}
/**
* The XML input of the REST Interface transfered into an element in the
* system graph.
* @param eElement The xml of a rest interface.
*/
public final void generateRESTInterfaceVertex(final Element eElement) {
try {
// Insert the node into the graph ui
final mxGeometry geo1 = new mxGeometry(currentHorizontal, currentVertical, 50, 50);
final String label = eElement.getElementsByTagName("id").item(0).getTextContent();
final Node interfaceData = eElement.getElementsByTagName(XMLStateMachine.INTERFACE_LABEL).item(0);
mxCell port1 = null;
if (interfaceData == null) {
port1 = new mxCell(
label, geo1,
"image;image=/images/workplace.png");
} else {
port1 = new mxCell(
label, geo1,
"image;image=/images/server.png");
}
port1.setVertex(true);
final mxCell restul = (mxCell) archPanel.addCell(port1);
dataModel.addNode(restul.getId(), label, XMLStateMachine.INTERFACE_LABEL);
final ArchitectureNode gNode = (ArchitectureNode) dataModel.getNode(GUIdentifier.setArchID(restul.getId()));
gNode.setData(label,
eElement.getElementsByTagName("address").item(0).getTextContent());
if (interfaceData != null) {
final Element interfa = (Element) interfaceData;
gNode.addInterfaceData(interfa.getElementsByTagName("id").item(0).getTextContent(),
interfa.getElementsByTagName("url").item(0).getTextContent());
this.currentHorizontal += 100;
}
} catch (DOMException ex) {
ServiceLogger.LOG.error("Error creating graph - could not generate xml nodes", ex);
}
}
/**
* The XML input of the State Machine Node (state) transformed into a GUI
* behaviour element.
* @param eElement The xml of the state node to draw.
* @return the identifier of the generated graph node.
* @throws InvalidPatternException The xml pattern is invalid.
*/
private String generateStateVertex(final Element eElement)
throws InvalidPatternException {
try {
final String nodeType = eElement.getElementsByTagName("type").item(0).getTextContent();
final String label = eElement.getElementsByTagName("label").item(0).getTextContent();
final mxGeometry geo1 = new mxGeometry(currentHorizontal, currentVertical, 50, 50);
mxCell nNode = null;
switch(nodeType) {
case XMLStateMachine.START_LABEL: nNode = new mxCell(
nodeType, geo1,
"image;image=/images/event_end.png");
break;
case XMLStateMachine.TRIGGERSTART_LABEL: nNode = new mxCell(
nodeType, geo1,
"image;image=/images/event_triggerstart.png");
break;
case XMLStateMachine.END_LABEL: nNode = new mxCell(
nodeType, geo1,
"image;image=/images/terminate.png");
break;
case XMLStateMachine.TRIGGER_LABEL: nNode = new mxCell(
nodeType, geo1,
"image;image=/images/link.png");
break;
case XMLStateMachine.LOOP_LABEL: nNode = new mxCell(
nodeType, geo1,
"image;image=/images/loop.png");
break;
case XMLStateMachine.NORMAL_LABEL: nNode = new mxCell(
nodeType, geo1,
"image;image=/images/event.png");
break;
default:
throw new InvalidPatternException("State is not one of the five types");
}
// Insert the node into the graph ui
if (nNode != null) {
nNode.setValue(label);
nNode.setVertex(true);
}
final mxCell restul = (mxCell) graphPanel.addCell(nNode);
dataModel.addNode(restul.getId(), nodeType, "state");
final GraphNode grphNode = (GraphNode) dataModel.getNode(restul.getId());
grphNode.setLabel(label);
this.currentHorizontal += 100;
if (nodeType.equalsIgnoreCase("start") || nodeType.equalsIgnoreCase("triggerstart")) {
return restul.getId();
} else {
return null;
}
} catch (DOMException ex) {
throw new InvalidPatternException("XML description of state is invalid", ex);
}
}
/**
* Public method to create a visual graph from the xml specification. There
* are two graph views displayed in the GUI: 1) the system graph, and 2)
* the behaviour graph.
* @param dom the parsed xml as a dom document.
* @throws InvalidPatternException Invalid pattern input to method.
*/
public final void importGraph(final Document dom) throws InvalidPatternException {
NodeList nList = dom.getElementsByTagName("component");
for (int i = 0; i < nList.getLength(); i++) {
final Element eElement = (Element) nList.item(i);
final String label = eElement.getElementsByTagName("id").item(0).getTextContent();
if (this.dataModel.getComponentByLabel(label) != null) {
throw new InvalidPatternException("Component id: " + label + " is not unique, rename before importing");
}
}
nList = dom.getElementsByTagName("state");
for (int i = 0; i < nList.getLength(); i++) {
final Element eElement = (Element) nList.item(i);
final String label = eElement.getElementsByTagName("label").item(0).getTextContent();
if (this.dataModel.getNodeByLabel(label) != null) {
throw new InvalidPatternException("State label: " + label + " is not unique, rename before importing");
}
}
createGraph(dom);
}
/**
* Public method to create a visual graph from the xml specification. There
* are two graph views displayed in the GUI: 1) the system graph, and 2)
* the behaviour graph.
* @param dom the parsed xml as a dom document.
* @throws InvalidPatternException Invalid pattern input to method.
*/
public final void createGraph(final Document dom) throws InvalidPatternException {
NodeList nList = dom.getElementsByTagName("component");
for (int i = 0; i < nList.getLength(); i++) {
generateRESTInterfaceVertex((Element) nList.item(i));
}
this.currentHorizontal = 75.0;
this.currentVertical += 100.0;
String startID = null;
nList = dom.getElementsByTagName("state");
for (int i = 0; i < nList.getLength(); i++) {
final String result = generateStateVertex((Element) nList.item(i));
if (result != null) {
startID = result;
}
}
for (int i = 0; i < nList.getLength(); i++) {
final NodeList transitions = ((Element) nList.item(i)).getElementsByTagName("transition");
final String label = ((Element) nList.item(i)).getElementsByTagName("label").item(0).getTextContent();
final String srcID = dataModel.getNodeByLabel(label).getUIIdentifier();
for (int j = 0; j < transitions.getLength(); j++) {
try{
generateTransitions(srcID , (Element) transitions.item(j));
} catch (XMLInputException ex) {
JOptionPane.showMessageDialog(UIEditor,
ex.getLocalizedMessage(),
"Import Graph Error",
JOptionPane.PLAIN_MESSAGE);
this.graphPanel.clearSelection();
this.archPanel.clearSelection();
return;
}
}
}
// Add the pattern data
final NodeList patternTag = dom.getElementsByTagName("patterndata");
if (patternTag.getLength() > 0) {
final NodeList pattern = dom.getElementsByTagName("patterndata").item(0).getChildNodes();
final GraphNode start = (GraphNode) dataModel.getNode(startID);
for (int i = 0; i < pattern.getLength(); i++) {
final Node currentItem = pattern.item(i);
if (currentItem.getNodeType() != 3) {
final String param = ((Element) currentItem).getElementsByTagName("name").item(0).getTextContent();
final String value = ((Element) currentItem).getElementsByTagName("value").item(0).getTextContent();
start.addConstantData(param, value);
}
}
}
}
}
| lgpl-3.0 |
Jaspersoft/js-android-sdk | core-integration-tests/src/test/java/com/jaspersoft/android/sdk/env/JrsEnvironmentRule.java | 9960 | /*
* Copyright (C) 2016 TIBCO Jaspersoft Corporation. All rights reserved.
* http://community.jaspersoft.com/project/mobile-sdk-android
*
* Unless you have purchased a commercial license agreement from TIBCO Jaspersoft,
* the following license terms apply:
*
* This program is part of TIBCO Jaspersoft Mobile SDK for Android.
*
* TIBCO Jaspersoft Mobile SDK 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.
*
* TIBCO Jaspersoft Mobile SDK 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 TIBCO Jaspersoft Mobile SDK for Android. If not, see
* <http://www.gnu.org/licenses/lgpl>.
*/
package com.jaspersoft.android.sdk.env;
import com.jaspersoft.android.sdk.network.AnonymousClient;
import com.jaspersoft.android.sdk.network.AuthorizedClient;
import com.jaspersoft.android.sdk.network.Server;
import com.jaspersoft.android.sdk.network.SpringCredentials;
import com.jaspersoft.android.sdk.testkit.ListReportParamsCommand;
import com.jaspersoft.android.sdk.testkit.ListResourcesUrisCommand;
import com.jaspersoft.android.sdk.testkit.LocalCookieManager;
import com.jaspersoft.android.sdk.testkit.TestKitClient;
import com.jaspersoft.android.sdk.testkit.dto.AuthConfig;
import com.jaspersoft.android.sdk.testkit.dto.Info;
import com.jaspersoft.android.sdk.testkit.dto.SampleServer;
import com.jaspersoft.android.sdk.testkit.exception.HttpException;
import org.junit.rules.ExternalResource;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.Proxy;
import java.net.Socket;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.concurrent.TimeUnit;
/**
* @author Tom Koptel
* @since 2.3
*/
public final class JrsEnvironmentRule extends ExternalResource {
private static final InetSocketAddress CHARLES_ADDRESS = new InetSocketAddress("0.0.0.0", 8888);
private static final Proxy CHARLES = new Proxy(Proxy.Type.HTTP, CHARLES_ADDRESS);
private IntegrationEnv mIntegrationEnv;
private Object[] mAuthorizedClients;
private Object[] mAnonymousClients;
private Object[] mReports;
private Object[] mDashboards;
private Object[] mFiles;
public Object[] listAnonymousClients() {
if (mAnonymousClients == null) {
mAnonymousClients = loadAnonymousClients();
}
return mAnonymousClients;
}
private Object[] loadAnonymousClients() {
List<SampleServer> sampleServers = getLazyEnv().getServers();
List<AnonymousServerTestBundle> bundles = new ArrayList<>();
for (SampleServer sampleServer : sampleServers) {
Server server = createServer(sampleServer);
AnonymousClient client = server.newClient()
.withCookieHandler(LocalCookieManager.get())
.create();
Info info = requestServerInfo(server);
for (AuthConfig authConfig : sampleServer.getAuthConfigs()) {
SpringCredentials credentials = SpringCredentials.builder()
.withOrganization(authConfig.getOrganization())
.withPassword(authConfig.getPassword())
.withUsername(authConfig.getPassword())
.build();
bundles.add(new AnonymousServerTestBundle(credentials, client, info));
}
}
Object[] result = new Object[bundles.size()];
bundles.toArray(result);
return result;
}
private Info requestServerInfo(Server server) {
TestKitClient kitClient = getTestKitClient(server.getBaseUrl());
try {
return kitClient.getServerInfo();
} catch (IOException | HttpException e) {
System.out.println(e);
}
return null;
}
public Object[] listAuthorizedClients() {
if (mAuthorizedClients == null) {
mAuthorizedClients = loadClients();
}
return mAuthorizedClients;
}
private Object[] loadClients() {
List<SampleServer> sampleServers = getLazyEnv().getServers();
List<ServerTestBundle> bundles = new ArrayList<>();
for (SampleServer sampleServer : sampleServers) {
Server server = createServer(sampleServer);
Info info = requestServerInfo(server);
for (AuthConfig authConfig : sampleServer.getAuthConfigs()) {
SpringCredentials credentials = SpringCredentials.builder()
.withOrganization(authConfig.getOrganization())
.withPassword(authConfig.getPassword())
.withUsername(authConfig.getPassword())
.build();
AuthorizedClient client = server.newClient(credentials)
.withCookieHandler(LocalCookieManager.get())
.create();
try {
client.authenticationApi().authenticate(credentials);
} catch (Exception e) {
System.out.println(e);
}
bundles.add(new ServerTestBundle(credentials, client, info));
}
}
Object[] result = new Object[bundles.size()];
bundles.toArray(result);
return result;
}
private Server createServer(SampleServer sampleServer) {
Server.Builder serverBuilder = Server.builder()
.withBaseUrl(sampleServer.getUrl())
.withConnectionTimeOut(30, TimeUnit.SECONDS)
.withReadTimeout(30, TimeUnit.SECONDS);
if (isProxyReachable()) {
serverBuilder.withProxy(CHARLES);
}
return serverBuilder.build();
}
public Object[] listReports() {
if (mReports == null) {
mReports = loadReports();
}
return mReports;
}
public Object[] listFiles() {
if (mFiles == null) {
mFiles = loadFiles();
}
return mFiles;
}
public Object[] listDashboards() {
if (mDashboards == null) {
mDashboards = loadDashboards();
}
return mDashboards;
}
private Object[] loadDashboards() {
return loadResources("dashboard");
}
private Object[] loadFiles() {
return loadResources("file");
}
private Object[] loadResources(String type) {
List<ResourceTestBundle> bundle = new ArrayList<>();
Object[] clients = listAuthorizedClients();
for (Object o : clients) {
ServerTestBundle sererBundle = (ServerTestBundle) o;
String baseUrl = sererBundle.getClient().getBaseUrl();
final TestKitClient kitClient = getTestKitClient(baseUrl);
int reportsNumber = getLazyEnv().resourceExecNumber();
ListResourcesUrisCommand listDashboardUris = new ListResourcesUrisCommand(reportsNumber, type);
try {
List<String> uris = kitClient.getResourcesUris(listDashboardUris);
for (String uri : uris) {
bundle.add(new ResourceTestBundle(uri, sererBundle));
}
} catch (IOException | HttpException e) {
System.out.println(e);
}
}
Object[] result = new Object[bundle.size()];
return bundle.toArray(result);
}
private TestKitClient getTestKitClient(String baseUrl) {
return TestKitClient.newClient(baseUrl, isProxyReachable() ? CHARLES : null);
}
private Object[] loadReports() {
List<ReportTestBundle> bundle = new ArrayList<>();
Object[] clients = listAuthorizedClients();
for (Object o : clients) {
ServerTestBundle sererBundle = (ServerTestBundle) o;
String baseUrl = sererBundle.getClient().getBaseUrl();
final TestKitClient kitClient = getTestKitClient(baseUrl);
int reportsNumber = getLazyEnv().resourceExecNumber();
ListResourcesUrisCommand listResourcesUris = new ListResourcesUrisCommand(reportsNumber, "reportUnit");
try {
List<String> uris = kitClient.getResourcesUris(listResourcesUris);
for (final String uri : uris) {
PendingTask<Map<String, Set<String>>> pendingLookup = new PendingTask<Map<String, Set<String>>>() {
@Override
public Map<String, Set<String>> perform() throws Exception {
ListReportParamsCommand listReportParams = new ListReportParamsCommand(uri);
return kitClient.resourceParameter(listReportParams);
}
};
bundle.add(new ReportTestBundle(uri, pendingLookup, sererBundle));
}
} catch (IOException | HttpException e) {
System.out.println(e);
}
}
Object[] result = new Object[bundle.size()];
return bundle.toArray(result);
}
private IntegrationEnv getLazyEnv() {
if (mIntegrationEnv == null) {
mIntegrationEnv = IntegrationEnv.load();
}
return mIntegrationEnv;
}
private static boolean isProxyReachable() {
try {
Socket socket = new Socket();
socket.connect(CHARLES_ADDRESS);
socket.close();
return true;
} catch (IOException e) {
return false;
}
}
}
| lgpl-3.0 |
lbndev/sonarqube | server/sonar-server/src/test/java/org/sonar/server/notification/ws/NotificationsWsTest.java | 1937 | /*
* SonarQube
* Copyright (C) 2009-2017 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.server.notification.ws;
import org.junit.Test;
import org.sonar.api.server.ws.Request;
import org.sonar.api.server.ws.Response;
import org.sonar.api.server.ws.WebService;
import org.sonar.api.server.ws.WebService.Controller;
import org.sonar.server.ws.WsTester;
import static org.assertj.core.api.Assertions.assertThat;
public class NotificationsWsTest {
private NotificationsWsAction action = new FakeNotificationAction();
private NotificationsWsAction[] actions = {action};
private WsTester ws = new WsTester(new NotificationsWs(actions));
private Controller underTest = ws.controller("api/notifications");
@Test
public void definition() {
assertThat(underTest.path()).isEqualTo("api/notifications");
}
private static class FakeNotificationAction implements NotificationsWsAction {
@Override
public void define(WebService.NewController context) {
context.createAction("fake")
.setHandler(this);
}
@Override
public void handle(Request request, Response response) throws Exception {
// do nothing
}
}
}
| lgpl-3.0 |
FyberOptic/MeddleGuide | src/main/java/net/fybertech/meddleguide/GuideCommand.java | 1546 | package net.fybertech.meddleguide;
import java.util.Collections;
import java.util.List;
import net.minecraft.command.CommandException;
import net.minecraft.command.ICommand;
import net.minecraft.command.ICommandSender;
import net.minecraft.entity.player.EntityPlayer;
import net.minecraft.server.MinecraftServer;
import net.minecraft.util.BlockPos;
public class GuideCommand implements ICommand
{
@Override
public int compareTo(ICommand o) {
return this.getCommandName().compareTo(o.getCommandName());
}
@Override
public List<String> addTabCompletionOptions(MinecraftServer arg0, ICommandSender arg1, String[] arg2, BlockPos arg3) {
return Collections.emptyList();
}
@Override
public boolean canCommandSenderUseCommand(MinecraftServer server, ICommandSender sender) {
//return sender.canCommandSenderUseCommand(1, this.getCommandName());
return true;
}
@Override
public List<String> getCommandAliases() {
return Collections.emptyList();
}
@Override
public String getCommandName() {
return "recipe";
}
@Override
public String getCommandUsage(ICommandSender arg0) {
return "recipe [search]";
}
@Override
public boolean isUsernameIndex(String[] arg0, int arg1) {
return false;
}
@Override
public void processCommand(MinecraftServer server, ICommandSender sender, String[] args) throws CommandException
{
if (sender.getCommandSenderEntity() instanceof EntityPlayer) {
((EntityPlayer)sender).displayGUIChest(new InventoryGuide("Recipe Guide", true, 9 * 6, args));
}
}
} | lgpl-3.0 |
sporniket/javabeans | seeg-maven-plugin/src/main/java/com/sporniket/libre/javabeans/seeg/CodeGenerator.java | 1443 | package com.sporniket.libre.javabeans.seeg;
import java.io.PrintStream;
/**
* Generator of source code.
*
* <p>
* © Copyright 2012-2020 David Sporn
* </p>
* <hr>
*
* <p>
* This file is part of <i>The Sporniket Javabeans Project – doclet</i>.
*
* <p>
* <i>The Sporniket Javabeans Project – seeg</i> 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.
*
* <p>
* <i>The Sporniket Javabeans Project – seeg</i> 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.
*
* <p>
* You should have received a copy of the GNU Lesser General Public License along with <i>The Sporniket Javabeans Library –
* core</i>. If not, see <a href="http://www.gnu.org/licenses/">http://www.gnu.org/licenses/</a>. 2
*
* <hr>
*
* @author David SPORN
* @version 20.07.00
* @since 20.04.01
*
* @param <DefinitionType>
* the type of internal representation to convert into source code.
*/
public interface CodeGenerator<DefinitionType>
{
void generate(DefinitionType specs, String targetDir, String targetPackage, PrintStream out);
}
| lgpl-3.0 |
daniel-he/community-edition | projects/repository/source/java/org/alfresco/repo/policy/TransactionInvocationHandlerFactory.java | 7686 | /*
* Copyright (C) 2005-2010 Alfresco Software Limited.
*
* This file is part of Alfresco
*
* Alfresco 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.
*
* Alfresco 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 Alfresco. If not, see <http://www.gnu.org/licenses/>.
*/
package org.alfresco.repo.policy;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;
import org.alfresco.repo.policy.Behaviour.NotificationFrequency;
import org.alfresco.repo.policy.Policy.Arg;
import org.alfresco.repo.transaction.AlfrescoTransactionSupport;
/**
* Factory for creating transaction-aware behaviour invocation handlers.
*/
public class TransactionInvocationHandlerFactory
{
/** Transaction Key for Behaviour Execution state */
private final static String EXECUTED_KEY = TransactionHandler.class.getName() + ".executed";
/** Transaction behaviour Queue */
private TransactionBehaviourQueue queue;
/**
* Construct
*
* @param queue behaviour queue
*/
public TransactionInvocationHandlerFactory(TransactionBehaviourQueue queue)
{
this.queue = queue;
}
/**
* Create Invocation Handler
*
* @param <P>
* @param behaviour
* @param definition
* @param policyInterface
* @return invocation handler
*/
public <P extends Policy> InvocationHandler createHandler(Behaviour behaviour, PolicyDefinition<P> definition, P policyInterface)
{
return new TransactionHandler<P>(behaviour, definition, policyInterface);
}
/**
* Transaction Invocation Handler.
*
* @param <P> policy interface
*/
private class TransactionHandler<P extends Policy> implements InvocationHandler
{
private Behaviour behaviour;
private PolicyDefinition<P> definition;
private P policyInterface;
/**
* Construct
*/
public TransactionHandler(Behaviour behaviour, PolicyDefinition<P> definition, P policyInterface)
{
this.behaviour = behaviour;
this.definition = definition;
this.policyInterface = policyInterface;
}
/* (non-Javadoc)
* @see java.lang.reflect.InvocationHandler#invoke(java.lang.Object, java.lang.reflect.Method, java.lang.Object[])
*/
@SuppressWarnings("unchecked")
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable
{
// Handle Object level methods
if (method.getName().equals("toString"))
{
return policyInterface.toString();
}
else if (method.getName().equals("hashCode"))
{
return policyInterface.hashCode();
}
else if (method.getName().equals("equals"))
{
return policyInterface.equals(args[0]);
}
// Invoke policy based on its notification frequency
Object result = null;
if (behaviour.getNotificationFrequency().equals(NotificationFrequency.FIRST_EVENT))
{
Map<ExecutionInstanceKey, Object> executedBehaviours = (Map<ExecutionInstanceKey, Object>)AlfrescoTransactionSupport.getResource(EXECUTED_KEY);
if (executedBehaviours == null)
{
executedBehaviours = new HashMap<ExecutionInstanceKey, Object>();
AlfrescoTransactionSupport.bindResource(EXECUTED_KEY, executedBehaviours);
}
ExecutionInstanceKey key = new ExecutionInstanceKey(behaviour, definition.getArguments(), args);
if (executedBehaviours.containsKey(key) == false)
{
// Invoke behavior for first time and mark as executed
try
{
result = method.invoke(policyInterface, args);
executedBehaviours.put(key, result);
}
catch (InvocationTargetException e)
{
throw e.getTargetException();
}
}
else
{
// Return result of previous execution
result = executedBehaviours.get(key);
}
}
else if (behaviour.getNotificationFrequency().equals(NotificationFrequency.TRANSACTION_COMMIT))
{
// queue policy invocation for end of transaction
queue.queue(behaviour, definition, policyInterface, method, args);
}
else
{
// Note: shouldn't get here
throw new PolicyException("Invalid Notification frequency " + behaviour.getNotificationFrequency());
}
return result;
}
}
/**
* Execution Instance Key - to uniquely identify an ExecutionContext
*/
private class ExecutionInstanceKey
{
public ExecutionInstanceKey(Behaviour behaviour, Arg[] argDefs, Object[] args)
{
this.behaviour = behaviour;
for (int i = 0; i < argDefs.length; i++)
{
if (argDefs[i].equals(Arg.KEY))
{
keys.add(args[i]);
}
}
}
Behaviour behaviour;
ArrayList<Object> keys = new ArrayList<Object>();
/**
* @see java.lang.Object#hashCode()
*/
@Override
public int hashCode()
{
int key = behaviour.hashCode();
for (int i = 0; i < keys.size(); i++)
{
key = (37 * key) + keys.get(i).hashCode();
}
return key;
}
/**
* @see java.lang.Object#equals(java.lang.Object)
*/
@Override
public boolean equals(Object obj)
{
if (this == obj)
{
return true;
}
if (obj instanceof ExecutionInstanceKey)
{
ExecutionInstanceKey that = (ExecutionInstanceKey) obj;
if(this.behaviour.equals(that.behaviour))
{
if(keys.size() != that.keys.size())
{
// different number of keys
return false;
}
if(keys.containsAll(that.keys))
{
// yes keys are equal
return true;
}
}
// behavior is different
return false;
}
else
{
// Object is wrong type
return false;
}
} // equals
} // ExecutionInstanceKey
} | lgpl-3.0 |
nhesusrz/EditorDePlanes | src/interfaceEditordePlanes/IntefaceEditordePlanes.java | 1403 | /*
* IntefaceEditordePlanes.java
*/
package interfaceEditordePlanes;
import javax.swing.JFrame;
import org.jdesktop.application.Application;
import org.jdesktop.application.SingleFrameApplication;
/**
*
* @author mpacheco
*/
/**
* The main class of the application.
*/
public class IntefaceEditordePlanes extends SingleFrameApplication {
/**
* At startup create and show the main frame of the application.
*/
@Override protected void startup() {
show(new InterfaceEditordePlanesView(this));
}
/**
* This method is to initialize the specified window by injecting resources.
* Windows shown in our application come fully initialized from the GUI
* builder, so this additional configuration is not needed.
*/
@Override protected void configureWindow(java.awt.Window root) {
}
/**
* A convenient static getter for the application instance.
* @return the instance of IntefaceEditordePlanes
*/
public static IntefaceEditordePlanes getApplication() {
return Application.getInstance(IntefaceEditordePlanes.class);
}
/**
* Main method launching the application.
*/
public static void main(String[] args) {
JFrame jf= new JFrame();
SplashWindow miSplash = new SplashWindow(".//images//splash.jpg",jf,4000);
launch(IntefaceEditordePlanes.class, args);
}
}
| lgpl-3.0 |
liflab/sealtest | Source/CoreTest/src/ca/uqac/lif/ecp/atomic/TestSettings.java | 1266 | /*
Log trace triaging and etc.
Copyright (C) 2016 Sylvain Hallé
This program is free software: you can redistribute it and/or modify
it under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package ca.uqac.lif.ecp.atomic;
import java.io.InputStream;
import java.util.Scanner;
import org.junit.Test;
public class TestSettings
{
/**
* The folder where the test data is located
*/
public static String s_dataFolder = "data/";
@Test
public void dummyTest()
{
}
public static Automaton loadAutomaton(String filename)
{
InputStream is = TestSettings.class.getResourceAsStream(s_dataFolder + filename);
Scanner scanner = new Scanner(is);
return Automaton.parseDot(scanner);
}
}
| lgpl-3.0 |
claudejin/evosuite | master/src/test/java/com/examples/with/different/packagename/ReadFromSystemIn.java | 1117 | /**
* Copyright (C) 2010-2016 Gordon Fraser, Andrea Arcuri and EvoSuite
* contributors
*
* This file is part of EvoSuite.
*
* EvoSuite 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.0 of the License, or
* (at your option) any later version.
*
* EvoSuite 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 Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with EvoSuite. If not, see <http://www.gnu.org/licenses/>.
*/
package com.examples.with.different.packagename;
import java.util.Scanner;
public class ReadFromSystemIn {
public boolean readHelloWorld(){
Scanner scanner = new Scanner(System.in);
String line = scanner.nextLine();
scanner.close();
if(line.equals("Hello World")){
return true;
} else {
return false;
}
}
}
| lgpl-3.0 |
tyotann/tyo-java-frame | src/com/ihidea/core/base/CoreEntity.java | 122 | package com.ihidea.core.base;
import java.io.Serializable;
public abstract class CoreEntity implements Serializable {
}
| lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-squid/src/main/java/org/sonar/squid/api/SourceCodeSearchEngine.java | 1074 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 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.squid.api;
import java.util.Collection;
public interface SourceCodeSearchEngine {
SourceCode search(String key);
Collection<SourceCode> search(Query... query);
}
| lgpl-3.0 |
snmaher/xacml4j | xacml-test/src/main/java/org/xacml4j/v30/AttributeResolverTestSupport.java | 1518 | package org.xacml4j.v30;
/*
* #%L
* Xacml4J Policy Unit Test Support
* %%
* Copyright (C) 2009 - 2014 Xacml4J.org
* %%
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General 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-3.0.html>.
* #L%
*/
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertTrue;
import java.util.Map;
public class AttributeResolverTestSupport {
protected <T extends AttributeExpType> void checkHasAttribute(
Map<String, BagOfAttributeExp> v, String attributeName,
AttributeExp ...values) {
BagOfAttributeExp bag = v.get(attributeName);
checkHasValues(bag, values);
}
protected <T extends AttributeExpType> void checkHasValues(BagOfAttributeExp bag,
AttributeExp ...values) {
assertNotNull(bag);
assertEquals(values.length, bag.size());
for(AttributeExp value: values) {
assertTrue(bag.contains(value));
}
}
}
| lgpl-3.0 |
flashpixx/Light-Jason | src/main/java/org/lightjason/agentspeak/language/execution/achievementtest/CAchievementGoalLiteral.java | 3429 | /*
* @cond LICENSE
* ######################################################################################
* # LGPL License #
* # #
* # This file is part of the LightJason #
* # Copyright (c) 2015-19, LightJason (info@lightjason.org) #
* # This program is free software: you can redistribute it and/or modify #
* # it under the terms of the GNU Lesser General Public License as #
* # published by the Free Software Foundation, either version 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/ #
* ######################################################################################
* @endcond
*/
package org.lightjason.agentspeak.language.execution.achievementtest;
import org.lightjason.agentspeak.language.ILiteral;
import org.lightjason.agentspeak.language.ITerm;
import org.lightjason.agentspeak.language.execution.IContext;
import org.lightjason.agentspeak.language.execution.instantiable.plan.trigger.ITrigger;
import org.lightjason.agentspeak.language.fuzzy.IFuzzyValue;
import javax.annotation.Nonnull;
import java.text.MessageFormat;
import java.util.List;
import java.util.stream.Stream;
/**
* achievement-goal action based on a literal
*/
public final class CAchievementGoalLiteral extends IAchievementGoal<ILiteral>
{
/**
* serial id
*/
private static final long serialVersionUID = -8534258655371085840L;
/**
* ctor
*
* @param p_type value of the achievment-goal
*/
public CAchievementGoalLiteral( @Nonnull final ILiteral p_type )
{
super( p_type, false );
}
/**
* ctor
*
* @param p_type value of the achievment-goal
* @param p_immediately immediately execution
*/
public CAchievementGoalLiteral( @Nonnull final ILiteral p_type, final boolean p_immediately )
{
super( p_type, p_immediately );
}
@Override
public String toString()
{
return MessageFormat.format( "{0}{1}", m_immediately ? "!!" : "!", m_value );
}
@Nonnull
@Override
public Stream<IFuzzyValue<?>> execute( final boolean p_parallel, @Nonnull final IContext p_context,
@Nonnull final List<ITerm> p_argument, @Nonnull final List<ITerm> p_return
)
{
return p_context.agent().trigger( ITrigger.EType.ADDGOAL.builddefault( m_value.allocate( p_context ) ), m_immediately );
}
}
| lgpl-3.0 |
mcapino/trajectorytools | src/main/java/tt/euclidtime3i/vis/SpatialProjectionTo2d.java | 281 | package tt.euclidtime3i.vis;
import javax.vecmath.Point2d;
import tt.euclidtime3i.Point;
public class SpatialProjectionTo2d implements tt.vis.ProjectionTo2d<Point> {
@Override
public Point2d project(Point point) {
return new Point2d(point.x, point.y);
}
}
| lgpl-3.0 |
xXKeyleXx/MyPet | modules/v1_16_R3/src/main/java/de/Keyle/MyPet/compat/v1_16_R3/entity/types/EntityMySkeletonHorse.java | 7325 | /*
* This file is part of MyPet
*
* Copyright © 2011-2020 Keyle
* MyPet is licensed under the GNU Lesser General Public License.
*
* MyPet 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.
*
* MyPet is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package de.Keyle.MyPet.compat.v1_16_R3.entity.types;
import de.Keyle.MyPet.api.Configuration;
import de.Keyle.MyPet.api.entity.EntitySize;
import de.Keyle.MyPet.api.entity.MyPet;
import de.Keyle.MyPet.api.entity.types.MySkeletonHorse;
import de.Keyle.MyPet.compat.v1_16_R3.entity.EntityMyPet;
import net.minecraft.server.v1_16_R3.*;
import org.bukkit.craftbukkit.v1_16_R3.inventory.CraftItemStack;
import java.lang.reflect.InvocationTargetException;
import java.util.Optional;
import java.util.UUID;
import static de.Keyle.MyPet.compat.v1_16_R3.CompatManager.ENTITY_LIVING_broadcastItemBreak;
@EntitySize(width = 1.4F, height = 1.6F)
public class EntityMySkeletonHorse extends EntityMyPet {
protected static final DataWatcherObject<Boolean> AGE_WATCHER = DataWatcher.a(EntityMySkeletonHorse.class, DataWatcherRegistry.i);
protected static final DataWatcherObject<Byte> SADDLE_CHEST_WATCHER = DataWatcher.a(EntityMySkeletonHorse.class, DataWatcherRegistry.a);
protected static final DataWatcherObject<Optional<UUID>> OWNER_WATCHER = DataWatcher.a(EntityMySkeletonHorse.class, DataWatcherRegistry.o);
int soundCounter = 0;
int rearCounter = -1;
public EntityMySkeletonHorse(World world, MyPet myPet) {
super(world, myPet);
indirectRiding = true;
}
/**
* Possible visual horse effects:
* 4 saddle
* 8 chest
* 32 head down
* 64 rear
* 128 mouth open
*/
protected void applyVisual(int value, boolean flag) {
int i = getDataWatcher().get(SADDLE_CHEST_WATCHER);
if (flag) {
getDataWatcher().set(SADDLE_CHEST_WATCHER, (byte) (i | value));
} else {
getDataWatcher().set(SADDLE_CHEST_WATCHER, (byte) (i & (~value)));
}
}
@Override
public boolean attack(Entity entity) {
boolean flag = false;
try {
flag = super.attack(entity);
if (flag) {
applyVisual(64, true);
rearCounter = 10;
}
} catch (Exception e) {
e.printStackTrace();
}
return flag;
}
@Override
protected String getDeathSound() {
return "entity.skeleton_horse.death";
}
@Override
protected String getHurtSound() {
return "entity.skeleton_horse.hurt";
}
@Override
protected String getLivingSound() {
return "entity.skeleton_horse.ambient";
}
@Override
public EnumInteractionResult handlePlayerInteraction(EntityHuman entityhuman, EnumHand enumhand, ItemStack itemStack) {
if (super.handlePlayerInteraction(entityhuman, enumhand, itemStack).a()) {
return EnumInteractionResult.CONSUME;
}
if (itemStack != null && canUseItem()) {
if (itemStack.getItem() == Items.SADDLE && !getMyPet().hasSaddle() && getOwner().getPlayer().isSneaking() && canEquip()) {
getMyPet().setSaddle(CraftItemStack.asBukkitCopy(itemStack));
if (itemStack != ItemStack.b && !entityhuman.abilities.canInstantlyBuild) {
itemStack.subtract(1);
if (itemStack.getCount() <= 0) {
entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, ItemStack.b);
}
}
return EnumInteractionResult.CONSUME;
} else if (itemStack.getItem() == Items.SHEARS && getOwner().getPlayer().isSneaking() && canEquip()) {
if (getMyPet().hasSaddle()) {
EntityItem entityitem = new EntityItem(this.world, this.locX(), this.locY() + 1, this.locZ(), CraftItemStack.asNMSCopy(getMyPet().getSaddle()));
entityitem.pickupDelay = 10;
entityitem.setMot(entityitem.getMot().add(0, this.random.nextFloat() * 0.05F, 0));
this.world.addEntity(entityitem);
}
makeSound("entity.sheep.shear", 1.0F, 1.0F);
getMyPet().setSaddle(null);
if (itemStack != ItemStack.b && !entityhuman.abilities.canInstantlyBuild) {
try {
itemStack.damage(1, entityhuman, (entityhuman1) -> entityhuman1.broadcastItemBreak(enumhand));
} catch (Error e) {
// TODO REMOVE
itemStack.damage(1, entityhuman, (entityhuman1) -> {
try {
ENTITY_LIVING_broadcastItemBreak.invoke(entityhuman1, enumhand);
} catch (IllegalAccessException | InvocationTargetException ex) {
ex.printStackTrace();
}
});
}
}
return EnumInteractionResult.CONSUME;
} else if (Configuration.MyPet.SkeletonHorse.GROW_UP_ITEM.compare(itemStack) && getMyPet().isBaby() && getOwner().getPlayer().isSneaking()) {
if (itemStack != ItemStack.b && !entityhuman.abilities.canInstantlyBuild) {
itemStack.subtract(1);
if (itemStack.getCount() <= 0) {
entityhuman.inventory.setItem(entityhuman.inventory.itemInHandIndex, ItemStack.b);
}
}
getMyPet().setBaby(false);
return EnumInteractionResult.CONSUME;
}
}
return EnumInteractionResult.PASS;
}
@Override
protected void initDatawatcher() {
super.initDatawatcher();
getDataWatcher().register(AGE_WATCHER, false);
getDataWatcher().register(SADDLE_CHEST_WATCHER, (byte) 0);
getDataWatcher().register(OWNER_WATCHER, Optional.empty());
}
@Override
public void updateVisuals() {
getDataWatcher().set(AGE_WATCHER, getMyPet().isBaby());
applyVisual(4, getMyPet().hasSaddle());
}
@Override
public void onLivingUpdate() {
boolean oldRiding = hasRider;
super.onLivingUpdate();
if (!hasRider) {
if (rearCounter > -1 && rearCounter-- == 0) {
applyVisual(64, false);
rearCounter = -1;
}
}
if (oldRiding != hasRider) {
if (hasRider) {
applyVisual(4, true);
} else {
applyVisual(4, getMyPet().hasSaddle());
}
}
}
@Override
public void playStepSound(BlockPosition blockposition, IBlockData blockdata) {
if (!blockdata.getMaterial().isLiquid()) {
IBlockData blockdataUp = this.world.getType(blockposition.up());
SoundEffectType soundeffecttype = blockdata.getStepSound();
if (blockdataUp.getBlock() == Blocks.SNOW) {
soundeffecttype = blockdata.getStepSound();
}
if (this.isVehicle()) {
++this.soundCounter;
if (this.soundCounter > 5 && this.soundCounter % 3 == 0) {
this.playSound(SoundEffects.ENTITY_HORSE_GALLOP, soundeffecttype.getVolume() * 0.15F, soundeffecttype.getPitch());
} else if (this.soundCounter <= 5) {
this.playSound(SoundEffects.ENTITY_HORSE_STEP_WOOD, soundeffecttype.getVolume() * 0.15F, soundeffecttype.getPitch());
}
} else if (!blockdata.getMaterial().isLiquid()) {
this.soundCounter += 1;
playSound(SoundEffects.ENTITY_HORSE_STEP_WOOD, soundeffecttype.getVolume() * 0.15F, soundeffecttype.getPitch());
} else {
playSound(SoundEffects.ENTITY_HORSE_STEP, soundeffecttype.getVolume() * 0.15F, soundeffecttype.getPitch());
}
}
}
@Override
public MySkeletonHorse getMyPet() {
return (MySkeletonHorse) myPet;
}
} | lgpl-3.0 |
jmecosta/sonar | sonar-squid/src/main/java/org/sonar/squid/api/SourceCodeIndexer.java | 959 | /*
* Sonar, open source software quality management tool.
* Copyright (C) 2008-2012 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.squid.api;
public interface SourceCodeIndexer {
void index(SourceCode sourceCode);
}
| lgpl-3.0 |
xinghuangxu/xinghuangxu.sonarqube | sonar-squid/src/main/java/org/sonar/squid/measures/MetricDef.java | 1148 | /*
* SonarQube, open source software quality management tool.
* Copyright (C) 2008-2013 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.squid.measures;
public interface MetricDef {
String getName();
boolean isCalculatedMetric();
boolean aggregateIfThereIsAlreadyAValue();
boolean isThereAggregationFormula();
CalculatedMetricFormula getCalculatedMetricFormula();
}
| lgpl-3.0 |
cismet/watergis-server | src/main/java/de/cismet/watergisserver/cidslayer/WrSgWsgCidsLayer.java | 886 | /***************************************************
*
* 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.watergisserver.cidslayer;
import Sirius.server.middleware.types.MetaClass;
import Sirius.server.newuser.User;
/**
* DOCUMENT ME!
*
* @author therter
* @version $Revision$, $Date$
*/
public class WrSgWsgCidsLayer extends WatergisDefaultCidsLayer {
//~ Constructors -----------------------------------------------------------
/**
* Creates a new VwDvgStaluCidsLayer object.
*
* @param mc DOCUMENT ME!
* @param user DOCUMENT ME!
*/
public WrSgWsgCidsLayer(final MetaClass mc, final User user) {
super(mc, user);
}
}
| lgpl-3.0 |
SergiyKolesnikov/fuji | benchmark_typechecker/subjectSystems/Violet/ExportImage_stubfix/com/horstmann/violet/framework/ExtensionFilter.java | 1221 | /*
Violet - A program for editing UML diagrams.
Copyright (C) 2002 Cay S. Horstmann (http://horstmann.com)
This program is free software; you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation; either version 2 of the License, or
(at your option) any later version.
This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU General Public License for more details.
You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA
*/
package com.horstmann.violet.framework;
import de.uni_passau.spl.bytecodecomposer.stubs.Stub;
import java.io.File;
/**
* A file filter that accepts all files with a given set of extensions.
*/
public class ExtensionFilter extends javax.swing.filechooser.FileFilter {
@Stub
public boolean accept(File f) {
return false;
}
@Stub
public String getDescription() {
return null;
}
}
| lgpl-3.0 |
VolatileDream/shrieking-mushroom | src/orb/quantum/shriek/common/Connection.java | 283 | package orb.quantum.shriek.common;
import java.nio.ByteBuffer;
import java.nio.channels.ClosedChannelException;
public interface Connection extends AutoCloseable {
public boolean write( ByteBuffer buf ) throws ClosedChannelException ;
public void close() throws Exception ;
}
| lgpl-3.0 |
tango-controls/JTango | server/src/main/java/org/tango/server/testserver/TestStateServer.java | 1637 | /**
* Copyright (C) : 2012
*
* Synchrotron Soleil
* L'Orme des merisiers
* Saint Aubin
* BP48
* 91192 GIF-SUR-YVETTE CEDEX
*
* This file is part of Tango.
*
* Tango 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.
*
* Tango 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 Tango. If not, see <http://www.gnu.org/licenses/>.
*/
package org.tango.server.testserver;
import org.tango.DeviceState;
import org.tango.server.annotation.Device;
import org.tango.server.annotation.Init;
import org.tango.server.annotation.State;
import org.tango.server.annotation.Status;
/**
* Device to test state
*
* @author ABEILLE
*
*/
@Device
public final class TestStateServer {
@State
private DeviceState state = DeviceState.OFF;
@Status
private String status = "empty";
@Init
public void init() {
state = DeviceState.ON;
status = "OK";
}
public DeviceState getState() {
return state;
}
public void setState(final DeviceState state) {
this.state = state;
}
public String getStatus() {
return status;
}
public void setStatus(final String status) {
this.status = status;
}
}
| lgpl-3.0 |
caduandrade/japura-gui | src/examples/java/org/japura/examples/gui/tooltip/example1/Example1.java | 755 | package org.japura.examples.gui.tooltip.example1;
import org.japura.examples.gui.AbstractExample;
import org.japura.examples.gui.ExampleImages;
import org.japura.gui.ToolTipButton;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import java.awt.Component;
import java.net.URL;
public class Example1 extends AbstractExample {
@Override
protected Component buildExampleComponent() {
URL url = ExampleImages.QUESTION_IMAGE;
Icon icon = new ImageIcon(url);
String text = "Visit Japura project at http://www.japura.org";
ToolTipButton toolTipButton = new ToolTipButton(icon, text);
return toolTipButton;
}
public static void main(String args[]) {
Example1 example = new Example1();
example.runExample();
}
}
| lgpl-3.0 |
flashpixx/Light-Jason | src/test/java/org/lightjason/agentspeak/beliefbase/TestCBeliefbase.java | 9528 | /*
* @cond LICENSE
* ######################################################################################
* # LGPL License #
* # #
* # This file is part of the LightJason #
* # Copyright (c) 2015-19, LightJason (info@lightjason.org) #
* # This program is free software: you can redistribute it and/or modify #
* # it under the terms of the GNU Lesser General Public License as #
* # published by the Free Software Foundation, either version 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/ #
* ######################################################################################
* @endcond
*/
package org.lightjason.agentspeak.beliefbase;
import org.apache.commons.io.IOUtils;
import org.junit.jupiter.api.Assertions;
import org.junit.jupiter.api.Test;
import org.lightjason.agentspeak.agent.IAgent;
import org.lightjason.agentspeak.agent.IBaseAgent;
import org.lightjason.agentspeak.beliefbase.storage.CClassStorage;
import org.lightjason.agentspeak.beliefbase.view.IView;
import org.lightjason.agentspeak.configuration.IAgentConfiguration;
import org.lightjason.agentspeak.generator.IActionGenerator;
import org.lightjason.agentspeak.generator.IBaseAgentGenerator;
import org.lightjason.agentspeak.generator.ILambdaStreamingGenerator;
import org.lightjason.agentspeak.language.CLiteral;
import org.lightjason.agentspeak.language.CRawTerm;
import org.lightjason.agentspeak.language.ILiteral;
import org.lightjason.agentspeak.testing.IBaseTest;
import javax.annotation.Nonnull;
import java.util.Set;
import java.util.stream.Collectors;
import java.util.stream.Stream;
/**
* test agent with beliebase
*/
public final class TestCBeliefbase extends IBaseTest
{
/**
* test beliefs exists
*
* @throws Exception is thrown on intialization error
*/
@Test
public void propertybeliefbase() throws Exception
{
final IAgent<?> l_agent = new CAgent.CAgentGenerator( "" ).generatesingle();
if ( PRINTENABLE )
l_agent.beliefbase().stream().forEach( System.out::println );
Assertions.assertArrayEquals(
Stream.of(
"self/m_fuzzy",
"self/m_trigger",
"self/m_cycletime",
"self/m_rules",
"self/m_stringvalue",
"self/m_storage",
"self/m_sleepingterm",
"self/m_runningplans",
"self/m_sleepingcycles",
"self/m_beliefbase",
"self/m_unifier",
"self/m_variablebuilder",
"self/m_plans",
"self/m_integervalue"
).toArray(),
l_agent.beliefbase().stream().map( i -> i.fqnfunctor().path() ).toArray()
);
final Set<ILiteral> l_beliefs = l_agent.beliefbase().stream().collect( Collectors.toSet() );
Assertions.assertTrue(
Stream.of(
CLiteral.of( "self/m_stringvalue" ),
CLiteral.of( "self/m_integervalue", CRawTerm.of( 42 ) )
).allMatch( l_beliefs::contains ),
"beliefs not found"
);
}
/**
* test empty beliefbase
*/
@Test
public void emptybeliefbase()
{
Assertions.assertTrue( IBeliefbase.EMPY.isempty() );
Assertions.assertEquals( 0, IBeliefbase.EMPY.size() );
Assertions.assertEquals( IAgent.EMPTY, IBeliefbase.EMPY.update( IAgent.EMPTY ) );
Assertions.assertEquals( 0, IBeliefbase.EMPY.trigger( IView.EMPTY ).count() );
Assertions.assertEquals( 0, IBeliefbase.EMPY.streamliteral().count() );
Assertions.assertEquals( 0, IBeliefbase.EMPY.streamview().count() );
Assertions.assertEquals( IBeliefbase.EMPY, IBeliefbase.EMPY.clear() );
Assertions.assertEquals( ILiteral.EMPTY, IBeliefbase.EMPY.add( ILiteral.EMPTY ) );
Assertions.assertEquals( IView.EMPTY, IBeliefbase.EMPY.add( IView.EMPTY ) );
Assertions.assertEquals( ILiteral.EMPTY, IBeliefbase.EMPY.remove( ILiteral.EMPTY ) );
Assertions.assertEquals( IView.EMPTY, IBeliefbase.EMPY.remove( IView.EMPTY ) );
Assertions.assertFalse( IBeliefbase.EMPY.containsliteral( "bar" ) );
Assertions.assertFalse( IBeliefbase.EMPY.containsview( "bar" ) );
Assertions.assertEquals( IView.EMPTY, IBeliefbase.EMPY.view( "bar " ) );
Assertions.assertTrue( IBeliefbase.EMPY.literal( "x" ).isEmpty() );
Assertions.assertEquals( IView.EMPTY, IBeliefbase.EMPY.create( "a" ) );
Assertions.assertEquals( IView.EMPTY, IBeliefbase.EMPY.create( "a", null ) );
Assertions.assertEquals( IView.EMPTY, IBeliefbase.EMPY.viewordefault( "x", IView.EMPTY ) );
}
/**
* test on-demand beliefbase
*/
@Test
public void ondemandbeliefbase()
{
final IBeliefbase l_beliefbase = new CBeliefbaseOnDemand();
Assertions.assertEquals( 0, l_beliefbase.size() );
Assertions.assertTrue( l_beliefbase.isempty() );
Assertions.assertEquals( 0, l_beliefbase.streamview().count() );
Assertions.assertEquals( 0, l_beliefbase.streamliteral().count() );
Assertions.assertFalse( l_beliefbase.containsliteral( "y" ) );
Assertions.assertFalse( l_beliefbase.containsview( "z" ) );
Assertions.assertEquals( l_beliefbase, l_beliefbase.clear() );
Assertions.assertTrue( l_beliefbase.literal( "u" ).isEmpty() );
}
/**
* test on-demand beliefbase add error
*/
@Test
public void ondemandaddviewerror()
{
Assertions.assertThrows(
IllegalStateException.class,
() -> new CBeliefbaseOnDemand().add( IView.EMPTY )
);
}
/**
* test on-demand beliefbase remove error
*/
@Test
public void ondemandremoveviewerror()
{
Assertions.assertThrows(
IllegalStateException.class,
() -> new CBeliefbaseOnDemand().remove( IView.EMPTY )
);
}
/**
* test on-demand beliefbase view error
*/
@Test
public void ondemandviewerror()
{
Assertions.assertThrows(
IllegalStateException.class,
() -> new CBeliefbaseOnDemand().view( "i" )
);
}
/**
* test on-demand beliefbase view-default error
*/
@Test
public void ondemandviewdefaulterror()
{
Assertions.assertThrows(
IllegalStateException.class,
() -> new CBeliefbaseOnDemand().viewordefault( "j", IView.EMPTY )
);
}
// ---------------------------------------------------------------------------------------------------------------------------------------------------------
/**
* on-demand beliefbase
*/
private static final class CBeliefbaseOnDemand extends IBeliefbaseOnDemand
{
}
/**
* agent class
*/
private static final class CAgent extends IBaseAgent<IAgent<?>>
{
/**
* serial id
*/
private static final long serialVersionUID = 3053608318122134408L;
/**
* test string property
*/
private String m_stringvalue;
/**
* test int property
*/
private final int m_integervalue = 42;
/**
* test string property
*/
private final transient String m_stringvaluenotlisten = "not shown";
/**
* ctor
*
* @param p_configuration agent configuration
*/
private CAgent( final IAgentConfiguration<IAgent<?>> p_configuration )
{
super( p_configuration );
m_beliefbase.add( new CBeliefbase( new CClassStorage<>( this ) ).create( "self", m_beliefbase ) );
}
/**
* agent generator class
*/
private static final class CAgentGenerator extends IBaseAgentGenerator<IAgent<?>>
{
/**
* ctor
*
* @param p_asl asl string code
* @throws Exception thrown on error
*/
CAgentGenerator( final String p_asl ) throws Exception
{
super( IOUtils.toInputStream( p_asl, "UTF-8" ), IActionGenerator.EMPTY, ILambdaStreamingGenerator.EMPTY );
}
@Nonnull
@Override
public IAgent<?> generatesingle( final Object... p_data )
{
return new CAgent( m_configuration );
}
}
}
}
| lgpl-3.0 |
Realmcraft/Vault | src/net/milkbowl/vault/Metrics.java | 27403 | package net.milkbowl.vault;
/*
* Copyright 2011 Tyler Blair. All rights reserved.
*
* Redistribution and use in source and binary forms, with or without modification, are
* permitted provided that the following conditions are met:
*
* 1. Redistributions of source code must retain the above copyright notice, this list of
* conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright notice, this list
* of conditions and the following disclaimer in the documentation and/or other materials
* provided with the distribution.
*
* THIS SOFTWARE IS PROVIDED BY THE AUTHOR ''AS IS'' AND ANY EXPRESS OR IMPLIED
* WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND
* FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
* CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON
* ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
* ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*
* The views and conclusions contained in the software and documentation are those of the
* authors and contributors and should not be interpreted as representing official policies,
* either expressed or implied, of anybody else.
*/
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.io.UnsupportedEncodingException;
import java.net.Proxy;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.util.Collections;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedHashSet;
import java.util.Set;
import java.util.UUID;
import java.util.logging.Level;
import java.util.zip.GZIPOutputStream;
import net.milkbowl.vault.chat.Chat;
import net.milkbowl.vault.economy.Economy;
import net.milkbowl.vault.permission.Permission;
import org.bukkit.Bukkit;
import org.bukkit.configuration.InvalidConfigurationException;
import org.bukkit.configuration.file.YamlConfiguration;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginDescriptionFile;
import org.bukkit.plugin.RegisteredServiceProvider;
import org.bukkit.scheduler.BukkitTask;
public class Metrics {
/**
* The current revision number
*/
private final static int REVISION = 7;
/**
* The base url of the metrics domain
*/
private static final String BASE_URL = "http://report.mcstats.org";
/**
* The url used to report a server's status
*/
private static final String REPORT_URL = "/plugin/%s";
/**
* Interval of time to ping (in minutes)
*/
private static final int PING_INTERVAL = 15;
/**
* The plugin this metrics submits for
*/
private final Plugin plugin;
/**
* All of the custom graphs to submit to metrics
*/
private final Set<Graph> graphs = Collections.synchronizedSet(new HashSet<Graph>());
/**
* The plugin configuration file
*/
private final YamlConfiguration configuration;
/**
* The plugin configuration file
*/
private final File configurationFile;
/**
* Unique server id
*/
private final String guid;
/**
* Debug mode
*/
private final boolean debug;
/**
* Lock for synchronization
*/
private final Object optOutLock = new Object();
/**
* The scheduled task
*/
private volatile BukkitTask task = null;
public Metrics(Plugin plugin) throws IOException {
if (plugin == null) {
throw new IllegalArgumentException("Plugin cannot be null");
}
this.plugin = plugin;
// load the config
configurationFile = getConfigFile();
configuration = YamlConfiguration.loadConfiguration(configurationFile);
// add some defaults
configuration.addDefault("opt-out", false);
configuration.addDefault("guid", UUID.randomUUID().toString());
configuration.addDefault("debug", false);
// Do we need to create the file?
if (configuration.get("guid", null) == null) {
configuration.options().header("http://mcstats.org").copyDefaults(true);
configuration.save(configurationFile);
}
// Load the guid then
guid = configuration.getString("guid");
debug = configuration.getBoolean("debug", false);
}
public void findCustomData() {
// Create our Economy Graph and Add our Economy plotters
Graph econGraph = createGraph("Economy");
RegisteredServiceProvider<Economy> rspEcon = Bukkit.getServer().getServicesManager().getRegistration(Economy.class);
Economy econ = null;
if (rspEcon != null) {
econ = rspEcon.getProvider();
}
final String econName = econ != null ? econ.getName() : "No Economy";
econGraph.addPlotter(new Metrics.Plotter(econName) {
@Override
public int getValue() {
return 1;
}
});
// Create our Permission Graph and Add our permission Plotters
Graph permGraph = createGraph("Permission");
final String permName = Bukkit.getServer().getServicesManager().getRegistration(Permission.class).getProvider().getName();
permGraph.addPlotter(new Metrics.Plotter(permName) {
@Override
public int getValue() {
return 1;
}
});
// Create our Chat Graph and Add our chat Plotters
Graph chatGraph = createGraph("Chat");
RegisteredServiceProvider<Chat> rspChat = Bukkit.getServer().getServicesManager().getRegistration(Chat.class);
Chat chat = null;
if (rspChat != null) {
chat = rspChat.getProvider();
}
final String chatName = chat != null ? chat.getName() : "No Chat";
// Add our Chat Plotters
chatGraph.addPlotter(new Metrics.Plotter(chatName) {
@Override
public int getValue() {
return 1;
}
});
}
/**
* Construct and create a Graph that can be used to separate specific plotters to their own graphs on the metrics
* website. Plotters can be added to the graph object returned.
*
* @param name The name of the graph
* @return Graph object created. Will never return NULL under normal circumstances unless bad parameters are given
*/
public Graph createGraph(final String name) {
if (name == null) {
throw new IllegalArgumentException("Graph name cannot be null");
}
// Construct the graph object
final Graph graph = new Graph(name);
// Now we can add our graph
graphs.add(graph);
// and return back
return graph;
}
/**
* Add a Graph object to BukkitMetrics that represents data for the plugin that should be sent to the backend
*
* @param graph The name of the graph
*/
public void addGraph(final Graph graph) {
if (graph == null) {
throw new IllegalArgumentException("Graph cannot be null");
}
graphs.add(graph);
}
/**
* Start measuring statistics. This will immediately create an async repeating task as the plugin and send the
* initial data to the metrics backend, and then after that it will post in increments of PING_INTERVAL * 1200
* ticks.
*
* @return True if statistics measuring is running, otherwise false.
*/
public boolean start() {
synchronized (optOutLock) {
// Did we opt out?
if (isOptOut()) {
return false;
}
// Is metrics already running?
if (task != null) {
return true;
}
// Begin hitting the server with glorious data
task = plugin.getServer().getScheduler().runTaskTimerAsynchronously(plugin, new Runnable() {
private boolean firstPost = true;
public void run() {
try {
// This has to be synchronized or it can collide with the disable method.
synchronized (optOutLock) {
// Disable Task, if it is running and the server owner decided to opt-out
if (isOptOut() && task != null) {
task.cancel();
task = null;
// Tell all plotters to stop gathering information.
for (Graph graph : graphs) {
graph.onOptOut();
}
}
}
// We use the inverse of firstPost because if it is the first time we are posting,
// it is not a interval ping, so it evaluates to FALSE
// Each time thereafter it will evaluate to TRUE, i.e PING!
postPlugin(!firstPost);
// After the first post we set firstPost to false
// Each post thereafter will be a ping
firstPost = false;
} catch (IOException e) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + e.getMessage());
}
}
}
}, 0, PING_INTERVAL * 1200);
return true;
}
}
/**
* Has the server owner denied plugin metrics?
*
* @return true if metrics should be opted out of it
*/
public boolean isOptOut() {
synchronized (optOutLock) {
try {
// Reload the metrics file
configuration.load(getConfigFile());
} catch (IOException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
} catch (InvalidConfigurationException ex) {
if (debug) {
Bukkit.getLogger().log(Level.INFO, "[Metrics] " + ex.getMessage());
}
return true;
}
return configuration.getBoolean("opt-out", false);
}
}
/**
* Enables metrics for the server by setting "opt-out" to false in the config file and starting the metrics task.
*
* @throws java.io.IOException
*/
public void enable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (isOptOut()) {
configuration.set("opt-out", false);
configuration.save(configurationFile);
}
// Enable Task, if it is not running
if (task == null) {
start();
}
}
}
/**
* Disables metrics for the server by setting "opt-out" to true in the config file and canceling the metrics task.
*
* @throws java.io.IOException
*/
public void disable() throws IOException {
// This has to be synchronized or it can collide with the check in the task.
synchronized (optOutLock) {
// Check if the server owner has already set opt-out, if not, set it.
if (!isOptOut()) {
configuration.set("opt-out", true);
configuration.save(configurationFile);
}
// Disable Task, if it is running
if (task != null) {
task.cancel();
task = null;
}
}
}
/**
* Gets the File object of the config file that should be used to store data such as the GUID and opt-out status
*
* @return the File object for the config file
*/
public File getConfigFile() {
// I believe the easiest way to get the base folder (e.g craftbukkit set via -P) for plugins to use
// is to abuse the plugin object we already have
// plugin.getDataFolder() => base/plugins/PluginA/
// pluginsFolder => base/plugins/
// The base is not necessarily relative to the startup directory.
File pluginsFolder = plugin.getDataFolder().getParentFile();
// return => base/plugins/PluginMetrics/config.yml
return new File(new File(pluginsFolder, "PluginMetrics"), "config.yml");
}
/**
* Generic method that posts a plugin to the metrics website
*/
private void postPlugin(final boolean isPing) throws IOException {
// Server software specific section
PluginDescriptionFile description = plugin.getDescription();
String pluginName = description.getName();
boolean onlineMode = Bukkit.getServer().getOnlineMode(); // TRUE if online mode is enabled
String pluginVersion = description.getVersion();
String serverVersion = Bukkit.getVersion();
int playersOnline = Bukkit.getServer().getOnlinePlayers().length;
// END server software specific section -- all code below does not use any code outside of this class / Java
// Construct the post data
StringBuilder json = new StringBuilder(1024);
json.append('{');
// The plugin's description file containg all of the plugin data such as name, version, author, etc
appendJSONPair(json, "guid", guid);
appendJSONPair(json, "plugin_version", pluginVersion);
appendJSONPair(json, "server_version", serverVersion);
appendJSONPair(json, "players_online", Integer.toString(playersOnline));
// New data as of R6
String osname = System.getProperty("os.name");
String osarch = System.getProperty("os.arch");
String osversion = System.getProperty("os.version");
String java_version = System.getProperty("java.version");
int coreCount = Runtime.getRuntime().availableProcessors();
// normalize os arch .. amd64 -> x86_64
if (osarch.equals("amd64")) {
osarch = "x86_64";
}
appendJSONPair(json, "osname", osname);
appendJSONPair(json, "osarch", osarch);
appendJSONPair(json, "osversion", osversion);
appendJSONPair(json, "cores", Integer.toString(coreCount));
appendJSONPair(json, "auth_mode", onlineMode ? "1" : "0");
appendJSONPair(json, "java_version", java_version);
// If we're pinging, append it
if (isPing) {
appendJSONPair(json, "ping", "1");
}
if (graphs.size() > 0) {
synchronized (graphs) {
json.append(',');
json.append('"');
json.append("graphs");
json.append('"');
json.append(':');
json.append('{');
boolean firstGraph = true;
final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
Graph graph = iter.next();
StringBuilder graphJson = new StringBuilder();
graphJson.append('{');
for (Plotter plotter : graph.getPlotters()) {
appendJSONPair(graphJson, plotter.getColumnName(), Integer.toString(plotter.getValue()));
}
graphJson.append('}');
if (!firstGraph) {
json.append(',');
}
json.append(escapeJSON(graph.getName()));
json.append(':');
json.append(graphJson);
firstGraph = false;
}
json.append('}');
}
}
// close json
json.append('}');
// Create the url
URL url = new URL(BASE_URL + String.format(REPORT_URL, urlEncode(pluginName)));
// Connect to the website
URLConnection connection;
// Mineshafter creates a socks proxy, so we can safely bypass it
// It does not reroute POST requests so we need to go around it
if (isMineshafterPresent()) {
connection = url.openConnection(Proxy.NO_PROXY);
} else {
connection = url.openConnection();
}
byte[] uncompressed = json.toString().getBytes();
byte[] compressed = gzip(json.toString());
// Headers
connection.addRequestProperty("User-Agent", "MCStats/" + REVISION);
connection.addRequestProperty("Content-Type", "application/json");
connection.addRequestProperty("Content-Encoding", "gzip");
connection.addRequestProperty("Content-Length", Integer.toString(compressed.length));
connection.addRequestProperty("Accept", "application/json");
connection.addRequestProperty("Connection", "close");
connection.setDoOutput(true);
if (debug) {
System.out.println("[Metrics] Prepared request for " + pluginName + " uncompressed=" + uncompressed.length + " compressed=" + compressed.length);
}
// Write the data
OutputStream os = connection.getOutputStream();
os.write(compressed);
os.flush();
// Now read the response
final BufferedReader reader = new BufferedReader(new InputStreamReader(connection.getInputStream()));
String response = reader.readLine();
// close resources
os.close();
reader.close();
if (response == null || response.startsWith("ERR") || response.startsWith("7")) {
if (response == null) {
response = "null";
} else if (response.startsWith("7")) {
response = response.substring(response.startsWith("7,") ? 2 : 1);
}
throw new IOException(response);
} else {
// Is this the first update this hour?
if (response.equals("1") || response.contains("This is your first update this hour")) {
synchronized (graphs) {
final Iterator<Graph> iter = graphs.iterator();
while (iter.hasNext()) {
final Graph graph = iter.next();
for (Plotter plotter : graph.getPlotters()) {
plotter.reset();
}
}
}
}
}
}
/**
* GZip compress a string of bytes
*
* @param input
* @return
*/
public static byte[] gzip(String input) {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
GZIPOutputStream gzos = null;
try {
gzos = new GZIPOutputStream(baos);
gzos.write(input.getBytes("UTF-8"));
} catch (IOException e) {
e.printStackTrace();
} finally {
if (gzos != null) try {
gzos.close();
} catch (IOException ignore) {
}
}
return baos.toByteArray();
}
/**
* Check if mineshafter is present. If it is, we need to bypass it to send POST requests
*
* @return true if mineshafter is installed on the server
*/
private boolean isMineshafterPresent() {
try {
Class.forName("mineshafter.MineServer");
return true;
} catch (Exception e) {
return false;
}
}
/**
* Appends a json encoded key/value pair to the given string builder.
*
* @param json
* @param key
* @param value
* @throws UnsupportedEncodingException
*/
private static void appendJSONPair(StringBuilder json, String key, String value) throws UnsupportedEncodingException {
boolean isValueNumeric;
try {
Double.parseDouble(value);
isValueNumeric = true;
} catch (NumberFormatException e) {
isValueNumeric = false;
}
if (json.charAt(json.length() - 1) != '{') {
json.append(',');
}
json.append(escapeJSON(key));
json.append(':');
if (isValueNumeric) {
json.append(value);
} else {
json.append(escapeJSON(value));
}
}
/**
* Escape a string to create a valid JSON string
*
* @param text
* @return
*/
private static String escapeJSON(String text) {
StringBuilder builder = new StringBuilder();
builder.append('"');
for (int index = 0; index < text.length(); index++) {
char chr = text.charAt(index);
switch (chr) {
case '"':
case '\\':
builder.append('\\');
builder.append(chr);
break;
case '\b':
builder.append("\\b");
break;
case '\t':
builder.append("\\t");
break;
case '\n':
builder.append("\\n");
break;
case '\r':
builder.append("\\r");
break;
default:
if (chr < ' ') {
String t = "000" + Integer.toHexString(chr);
builder.append("\\u" + t.substring(t.length() - 4));
} else {
builder.append(chr);
}
break;
}
}
builder.append('"');
return builder.toString();
}
/**
* Encode text as UTF-8
*
* @param text the text to encode
* @return the encoded text, as UTF-8
*/
private static String urlEncode(final String text) throws UnsupportedEncodingException {
return URLEncoder.encode(text, "UTF-8");
}
/**
* Represents a custom graph on the website
*/
public static class Graph {
/**
* The graph's name, alphanumeric and spaces only :) If it does not comply to the above when submitted, it is
* rejected
*/
private final String name;
/**
* The set of plotters that are contained within this graph
*/
private final Set<Plotter> plotters = new LinkedHashSet<Plotter>();
private Graph(final String name) {
this.name = name;
}
/**
* Gets the graph's name
*
* @return the Graph's name
*/
public String getName() {
return name;
}
/**
* Add a plotter to the graph, which will be used to plot entries
*
* @param plotter the plotter to add to the graph
*/
public void addPlotter(final Plotter plotter) {
plotters.add(plotter);
}
/**
* Remove a plotter from the graph
*
* @param plotter the plotter to remove from the graph
*/
public void removePlotter(final Plotter plotter) {
plotters.remove(plotter);
}
/**
* Gets an <b>unmodifiable</b> set of the plotter objects in the graph
*
* @return an unmodifiable {@link java.util.Set} of the plotter objects
*/
public Set<Plotter> getPlotters() {
return Collections.unmodifiableSet(plotters);
}
@Override
public int hashCode() {
return name.hashCode();
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof Graph)) {
return false;
}
final Graph graph = (Graph) object;
return graph.name.equals(name);
}
/**
* Called when the server owner decides to opt-out of BukkitMetrics while the server is running.
*/
protected void onOptOut() {
}
}
/**
* Interface used to collect custom data for a plugin
*/
public static abstract class Plotter {
/**
* The plot's name
*/
private final String name;
/**
* Construct a plotter with the default plot name
*/
public Plotter() {
this("Default");
}
/**
* Construct a plotter with a specific plot name
*
* @param name the name of the plotter to use, which will show up on the website
*/
public Plotter(final String name) {
this.name = name;
}
/**
* Get the current value for the plotted point. Since this function defers to an external function it may or may
* not return immediately thus cannot be guaranteed to be thread friendly or safe. This function can be called
* from any thread so care should be taken when accessing resources that need to be synchronized.
*
* @return the current value for the point to be plotted.
*/
public abstract int getValue();
/**
* Get the column name for the plotted point
*
* @return the plotted point's column name
*/
public String getColumnName() {
return name;
}
/**
* Called after the website graphs have been updated
*/
public void reset() {
}
@Override
public int hashCode() {
return getColumnName().hashCode();
}
@Override
public boolean equals(final Object object) {
if (!(object instanceof Plotter)) {
return false;
}
final Plotter plotter = (Plotter) object;
return plotter.name.equals(name) && plotter.getValue() == getValue();
}
}
}
| lgpl-3.0 |
SonarSource/sonarqube | sonar-ws/src/main/java/org/sonarqube/ws/client/plugins/PluginsService.java | 5101 | /*
* SonarQube
* Copyright (C) 2009-2022 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.sonarqube.ws.client.plugins;
import java.util.stream.Collectors;
import javax.annotation.Generated;
import org.sonarqube.ws.MediaTypes;
import org.sonarqube.ws.client.BaseService;
import org.sonarqube.ws.client.GetRequest;
import org.sonarqube.ws.client.PostRequest;
import org.sonarqube.ws.client.WsConnector;
/**
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins">Further information about this web service online</a>
*/
@Generated("sonar-ws-generator")
public class PluginsService extends BaseService {
public PluginsService(WsConnector wsConnector) {
super(wsConnector, "api/plugins");
}
/**
*
* This is part of the internal API.
* This is a GET request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/available">Further information about this action online (including a response example)</a>
* @since 5.2
*/
public String available() {
return call(
new GetRequest(path("available"))
.setMediaType(MediaTypes.JSON)
).content();
}
/**
*
* This is part of the internal API.
* This is a POST request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/cancel_all">Further information about this action online (including a response example)</a>
* @since 5.2
*/
public void cancelAll() {
call(
new PostRequest(path("cancel_all"))
.setMediaType(MediaTypes.JSON)
).content();
}
/**
*
* This is part of the internal API.
* This is a POST request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/install">Further information about this action online (including a response example)</a>
* @since 5.2
*/
public void install(InstallRequest request) {
call(
new PostRequest(path("install"))
.setParam("key", request.getKey())
.setMediaType(MediaTypes.JSON)
).content();
}
/**
*
* This is part of the internal API.
* This is a GET request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/installed">Further information about this action online (including a response example)</a>
* @since 5.2
*/
public String installed(InstalledRequest request) {
return call(
new GetRequest(path("installed"))
.setParam("f", request.getF() == null ? null : request.getF().stream().collect(Collectors.joining(",")))
.setMediaType(MediaTypes.JSON)
).content();
}
/**
*
* This is part of the internal API.
* This is a GET request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/pending">Further information about this action online (including a response example)</a>
* @since 5.2
*/
public String pending() {
return call(
new GetRequest(path("pending"))
.setMediaType(MediaTypes.JSON)
).content();
}
/**
*
* This is part of the internal API.
* This is a POST request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/uninstall">Further information about this action online (including a response example)</a>
* @since 5.2
*/
public void uninstall(UninstallRequest request) {
call(
new PostRequest(path("uninstall"))
.setParam("key", request.getKey())
.setMediaType(MediaTypes.JSON)
).content();
}
/**
*
* This is part of the internal API.
* This is a POST request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/update">Further information about this action online (including a response example)</a>
* @since 5.2
*/
public void update(UpdateRequest request) {
call(
new PostRequest(path("update"))
.setParam("key", request.getKey())
.setMediaType(MediaTypes.JSON)
).content();
}
/**
*
* This is part of the internal API.
* This is a GET request.
* @see <a href="https://next.sonarqube.com/sonarqube/web_api/api/plugins/updates">Further information about this action online (including a response example)</a>
* @since 5.2
*/
public String updates() {
return call(
new GetRequest(path("updates"))
.setMediaType(MediaTypes.JSON)
).content();
}
}
| lgpl-3.0 |
SonarSource/sonarqube | server/sonar-webserver-webapi/src/test/java/org/sonar/server/platform/ws/LogsActionTest.java | 5439 | /*
* SonarQube
* Copyright (C) 2009-2022 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.server.platform.ws;
import java.io.File;
import java.io.IOException;
import java.util.Set;
import org.apache.commons.io.FileUtils;
import org.junit.Rule;
import org.junit.Test;
import org.junit.rules.TemporaryFolder;
import org.sonar.server.exceptions.ForbiddenException;
import org.sonar.server.log.ServerLogging;
import org.sonar.server.tester.UserSessionRule;
import org.sonar.server.ws.TestResponse;
import org.sonar.server.ws.WsActionTester;
import org.sonarqube.ws.MediaTypes;
import static java.util.Arrays.asList;
import static org.assertj.core.api.Assertions.assertThat;
import static org.assertj.core.api.Assertions.assertThatThrownBy;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
public class LogsActionTest {
@Rule
public UserSessionRule userSession = UserSessionRule.standalone();
@Rule
public TemporaryFolder temp = new TemporaryFolder();
private ServerLogging serverLogging = mock(ServerLogging.class);
private LogsAction underTest = new LogsAction(userSession, serverLogging);
private WsActionTester actionTester = new WsActionTester(underTest);
@Test
public void values_of_process_parameter_are_names_of_processes() {
Set<String> values = actionTester.getDef().param("process").possibleValues();
// values are lower-case and alphabetically ordered
assertThat(values).containsExactly("access", "app", "ce", "es", "web");
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_logged_in() {
assertThatThrownBy(() -> actionTester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void request_fails_with_ForbiddenException_when_user_is_not_system_administrator() {
userSession.logIn();
assertThatThrownBy(() -> actionTester.newRequest().execute())
.isInstanceOf(ForbiddenException.class);
}
@Test
public void get_app_logs_by_default() throws IOException {
logInAsSystemAdministrator();
createAllLogsFiles();
TestResponse response = actionTester.newRequest().execute();
assertThat(response.getMediaType()).isEqualTo(MediaTypes.TXT);
assertThat(response.getInput()).isEqualTo("{app}");
}
@Test
public void return_404_not_found_if_file_does_not_exist() throws IOException {
logInAsSystemAdministrator();
createLogsDir();
TestResponse response = actionTester.newRequest().execute();
assertThat(response.getStatus()).isEqualTo(404);
}
@Test
public void download_logs() throws IOException {
logInAsSystemAdministrator();
createAllLogsFiles();
asList("ce", "es", "web", "access").forEach(process -> {
TestResponse response = actionTester.newRequest()
.setParam("process", process)
.execute();
assertThat(response.getMediaType()).isEqualTo(MediaTypes.TXT);
assertThat(response.getInput()).isEqualTo("{" + process + "}");
});
}
@Test
public void do_not_return_rotated_files() throws IOException {
logInAsSystemAdministrator();
File dir = createLogsDir();
FileUtils.write(new File(dir, "sonar.1.log"), "{old}");
FileUtils.write(new File(dir, "sonar.log"), "{recent}");
TestResponse response = actionTester.newRequest()
.setParam("process", "app")
.execute();
assertThat(response.getMediaType()).isEqualTo(MediaTypes.TXT);
assertThat(response.getInput()).isEqualTo("{recent}");
}
@Test
public void create_latest_created_file() throws IOException {
logInAsSystemAdministrator();
File dir = createLogsDir();
FileUtils.write(new File(dir, "sonar.20210101.log"), "{old}");
FileUtils.write(new File(dir, "sonar.20210201.log"), "{recent}");
TestResponse response = actionTester.newRequest()
.setParam("process", "app")
.execute();
assertThat(response.getMediaType()).isEqualTo(MediaTypes.TXT);
assertThat(response.getInput()).isEqualTo("{recent}");
}
private File createAllLogsFiles() throws IOException {
File dir = createLogsDir();
FileUtils.write(new File(dir, "access.log"), "{access}");
FileUtils.write(new File(dir, "sonar.log"), "{app}");
FileUtils.write(new File(dir, "ce.log"), "{ce}");
FileUtils.write(new File(dir, "es.log"), "{es}");
FileUtils.write(new File(dir, "web.log"), "{web}");
return dir;
}
private File createLogsDir() throws IOException {
File dir = temp.newFolder();
when(serverLogging.getLogsDir()).thenReturn(dir);
return dir;
}
private void logInAsSystemAdministrator() {
userSession.logIn().setSystemAdministrator();
}
}
| lgpl-3.0 |
WELTEN/dojo-ibl | src/main/java/org/celstec/arlearn2/portal/client/AddContactPage.java | 5924 | package org.celstec.arlearn2.portal.client;
import com.google.gwt.user.client.ui.RootPanel;
import com.smartgwt.client.widgets.layout.VLayout;
import org.celstec.arlearn2.gwtcommonlib.client.network.AccountClient;
import org.celstec.arlearn2.gwtcommonlib.client.network.CollaborationClient;
import org.celstec.arlearn2.gwtcommonlib.client.network.JsonCallback;
import com.google.gwt.json.client.JSONObject;
import com.google.gwt.json.client.JSONValue;
import com.google.gwt.user.client.Window.Location;
import com.smartgwt.client.types.Alignment;
import com.smartgwt.client.util.SC;
import com.smartgwt.client.widgets.HTMLPane;
import com.smartgwt.client.widgets.IButton;
import com.smartgwt.client.widgets.Window;
import com.smartgwt.client.widgets.events.ClickEvent;
import com.smartgwt.client.widgets.events.ClickHandler;
import com.smartgwt.client.widgets.events.CloseClickEvent;
import com.smartgwt.client.widgets.events.CloseClickHandler;
import com.smartgwt.client.widgets.layout.HStack;
import com.smartgwt.client.widgets.layout.LayoutSpacer;
import com.smartgwt.client.widgets.layout.VStack;
import org.celstec.arlearn2.portal.client.account.AccountManager;
import org.celstec.arlearn2.portal.client.toolbar.ToolBar;
public class AddContactPage {
ToolBar toolStrip;
public void loadPage() {
AccountManager accountManager = AccountManager.getInstance();
accountManager.setAccountNotification(new AccountManager.NotifyAccountLoaded() {
@Override
public void accountLoaded(boolean success) {
if (success) {
toolStrip = new ToolBar(false);
LayoutSpacer vSpacer = new LayoutSpacer();
vSpacer.setWidth(50);
vSpacer.setHeight(10);
VLayout vertical = new VLayout();
vertical.setWidth("98%");
vertical.setHeight("100%");
vertical.addMember(toolStrip);
vertical.addMember(vSpacer);
RootPanel.get("contact").add(vertical);
AccountClient.getInstance().accountDetails(new JsonCallback(){
public void onJsonReceived(JSONValue jsonValue) {
loadContactDetails(jsonValue.isObject());
}
});
} else {
SC.say("Credentials are invalid. Log in again.");
}
}
});
}
private void loadContactDetails(final JSONObject self) {
final String addContactToken = Location.getParameter("id");
CollaborationClient.getInstance().getContactDetails(addContactToken, new JsonCallback() {
public void onJsonReceived(JSONValue jsonValue) {
if (jsonValue.isObject().containsKey("error")) {
SC.say("Error", "This invitation is no longer valid");
} else {
JSONObject contact = jsonValue.isObject();
if (self.get("localId").isString().stringValue().equals(contact.get("localId").isString().stringValue()) && self.get("accountType").isNumber().equals(contact.get("accountType").isNumber())) {
SC.say("You cannot add your own account as a contact. <br> Login with a different account to ARLearn to accept this invitation.");
} else {
buildPage(jsonValue.isObject(), addContactToken);
}
}
}
});
}
public void buildPage(JSONObject contactJson, final String addContactToken) {
final Window winModal = new Window();
winModal.setWidth(360);
winModal.setHeight(140);
winModal.setTitle("Add contact");
winModal.setShowMinimizeButton(false);
winModal.setIsModal(true);
winModal.setShowModalMask(true);
winModal.centerInPage();
winModal.addCloseClickHandler(new CloseClickHandler() {
@Override
public void onCloseClick(CloseClickEvent event) {
// TODO Auto-generated method stub
}
});
VStack hStack = new VStack();
hStack.setHeight(100);
HTMLPane paneLink = new HTMLPane();
paneLink.setHeight(75);
String displayString = "<img style=\"float:left;margin:0 5px 0 0;\" height=\"50\" src=\""+contactJson.get("picture").isString().stringValue()+"\"/>Do you want to add "+contactJson.get("name").isString().stringValue()+ " as a contact?";
paneLink.setContents(displayString);
hStack.addMember(paneLink);
winModal.addItem(hStack);
final IButton addContactButton = new IButton("Add Contact");
addContactButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
addContact(addContactToken);
}
});
final IButton ignoreButton = new IButton("Ignore");
ignoreButton.addClickHandler(new ClickHandler() {
@Override
public void onClick(ClickEvent event) {
ignore();
}
});
LayoutSpacer vSpacer = new LayoutSpacer();
vSpacer.setWidth(5);
HStack horStack = new HStack();
horStack.setAlign(Alignment.CENTER);
horStack.addMember(addContactButton);
horStack.addMember(vSpacer);
horStack.addMember(ignoreButton);
horStack.setHeight(20);
hStack.addMember(horStack);
winModal.show();
}
public void addContact(final String addContactToken) {
CollaborationClient.getInstance().confirmAddContact(addContactToken, new JsonCallback(){
public void onJsonReceived(JSONValue jsonValue) {
com.google.gwt.user.client.Window.open("/index.html", "_self", "");
}
});
}
public void ignore() {
com.google.gwt.user.client.Window.open("/index.html", "_self", "");
}
}
| lgpl-3.0 |
ethereum/ethereumj | ethereumj-core/src/test/java/org/ethereum/datasource/BlockSerializerTest.java | 5033 | /*
* Copyright (c) [2016] [ <ether.camp> ]
* This file is part of the ethereumJ library.
*
* The ethereumJ 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.
*
* The ethereumJ 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 the ethereumJ library. If not, see <http://www.gnu.org/licenses/>.
*/
package org.ethereum.datasource;
import org.ethereum.db.IndexedBlockStore;
import org.ethereum.db.IndexedBlockStore.BlockInfo;
import org.ethereum.util.ByteUtil;
import org.ethereum.util.FastByteComparisons;
import org.junit.Ignore;
import org.junit.Test;
import java.math.BigInteger;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
import java.util.Random;
import static org.ethereum.crypto.HashUtil.sha3;
/**
* Test for {@link IndexedBlockStore.BLOCK_INFO_SERIALIZER}
*/
public class BlockSerializerTest {
private static final Random rnd = new Random();
private List<BlockInfo> generateBlockInfos(int count) {
List<BlockInfo> blockInfos = new ArrayList<>();
for (int i = 0; i < count; i++) {
BlockInfo blockInfo = new BlockInfo();
blockInfo.setHash(sha3(ByteUtil.intToBytes(i)));
blockInfo.setTotalDifficulty(BigInteger.probablePrime(512, rnd));
blockInfo.setMainChain(rnd.nextBoolean());
blockInfos.add(blockInfo);
}
return blockInfos;
}
@Test
public void testTest() {
List<BlockInfo> blockInfoList = generateBlockInfos(100);
byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(blockInfoList);
System.out.printf("Blocks total byte size: %s%n", data.length);
List<BlockInfo> blockInfoList2 = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data);
assert blockInfoList.size() == blockInfoList2.size();
for (int i = 0; i < blockInfoList2.size(); i++) {
assert FastByteComparisons.equal(blockInfoList2.get(i).getHash(), blockInfoList.get(i).getHash());
assert blockInfoList2.get(i).getTotalDifficulty().compareTo(blockInfoList.get(i).getTotalDifficulty()) == 0;
assert blockInfoList2.get(i).isMainChain() == blockInfoList.get(i).isMainChain();
}
}
@Test
@Ignore
public void testTime() {
int BLOCKS = 100;
int PASSES = 10_000;
List<BlockInfo> blockInfoList = generateBlockInfos(BLOCKS);
long s = System.currentTimeMillis();
for (int i = 0; i < PASSES; i++) {
byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(blockInfoList);
List<BlockInfo> blockInfoList2 = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data);
}
long e = System.currentTimeMillis();
System.out.printf("Serialize/deserialize blocks per 1 ms: %s%n", PASSES * BLOCKS / (e - s));
}
@Test(expected = RuntimeException.class)
public void testNullTotalDifficulty() {
BlockInfo blockInfo = new BlockInfo();
blockInfo.setMainChain(true);
blockInfo.setTotalDifficulty(null);
blockInfo.setHash(new byte[0]);
byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(Collections.singletonList(blockInfo));
List<BlockInfo> blockInfos = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data);
}
@Test(expected = RuntimeException.class)
public void testNegativeTotalDifficulty() {
BlockInfo blockInfo = new BlockInfo();
blockInfo.setMainChain(true);
blockInfo.setTotalDifficulty(BigInteger.valueOf(-1));
blockInfo.setHash(new byte[0]);
byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(Collections.singletonList(blockInfo));
List<BlockInfo> blockInfos = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data);
}
@Test
public void testZeroTotalDifficultyEmptyHash() {
BlockInfo blockInfo = new BlockInfo();
blockInfo.setMainChain(true);
blockInfo.setTotalDifficulty(BigInteger.ZERO);
blockInfo.setHash(new byte[0]);
byte[] data = IndexedBlockStore.BLOCK_INFO_SERIALIZER.serialize(Collections.singletonList(blockInfo));
List<BlockInfo> blockInfos = IndexedBlockStore.BLOCK_INFO_SERIALIZER.deserialize(data);
assert blockInfos.size() == 1;
BlockInfo actualBlockInfo = blockInfos.get(0);
assert actualBlockInfo.isMainChain();
assert actualBlockInfo.getTotalDifficulty().compareTo(BigInteger.ZERO) == 0;
assert actualBlockInfo.getHash().length == 0;
}
}
| lgpl-3.0 |
mateusduboli/arquillian-example | src/main/java/br/com/realmtech/bean/builder/PersonBuilder.java | 866 | package br.com.realmtech.bean.builder;
import br.com.realmtech.bean.Address;
import br.com.realmtech.bean.Name;
import br.com.realmtech.bean.Person;
import br.com.realmtech.bean.Telephone;
import br.com.realmtech.bean.impl.PersonImpl;
/**
* Created with IntelliJ IDEA.
* User: mateus
* Date: 11/1/13
* Time: 7:01 PM
* To change this template use File | Settings | File Templates.
*/
public class PersonBuilder {
private Name name;
private Telephone telephone;
private Address address;
public PersonBuilder setName(Name name) {
this.name = name;
return this;
}
public PersonBuilder setTelephone(Telephone telephone) {
this.telephone = telephone;
return this;
}
public PersonBuilder setAddress(Address address) {
this.address = address;
return this;
}
public Person create() {
return new PersonImpl(name, telephone, address);
}
}
| lgpl-3.0 |
tweninger/nina | src/edu/nd/nina/graph/load/TokenSequenceLowercase.java | 1050 | /* Copyright (C) 2002 Univ. of Massachusetts Amherst, Computer Science Dept.
This file is part of "MALLET" (MAchine Learning for LanguagE Toolkit).
http://www.cs.umass.edu/~mccallum/mallet
This software is provided under the terms of the Common Public License,
version 1.0, as published by http://www.opensource.org. For further
information, see the file `LICENSE' included with this distribution. */
package edu.nd.nina.graph.load;
import edu.nd.nina.types.Instance;
import edu.nd.nina.types.Token;
import edu.nd.nina.types.TokenSequence;
/**
* Convert the text in each token in the token sequence in the data field to
* lower case.
*
* @author Andrew McCallum <a
* href="mailto:mccallum@cs.umass.edu">mccallum@cs.umass.edu</a>
*/
public class TokenSequenceLowercase extends Pipe {
public Instance pipe(Instance carrier) {
TokenSequence ts = (TokenSequence) carrier.getData();
for (int i = 0; i < ts.size(); i++) {
Token t = ts.get(i);
t.setText(t.getText().toLowerCase());
}
return carrier;
}
}
| lgpl-3.0 |
notepass/npGenerals | src/de/notepass/general/util/Util.java | 24618 | package de.notepass.general.util;
import de.notepass.general.logger.Log;
//import de.notepass.general.objects.gui.GroupBox;
import org.w3c.dom.Document;
import org.w3c.dom.NodeList;
import org.xml.sax.SAXException;
import javax.swing.*;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.*;
import java.awt.*;
import java.io.*;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.net.URI;
import java.net.URL;
import java.net.URLClassLoader;
import java.nio.channels.Channels;
import java.nio.channels.FileChannel;
import java.nio.channels.ReadableByteChannel;
import java.util.*;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import java.util.Properties;
import de.notepass.general.internalConfig.InternalConfigDummy;
//The Util-Class of this project. You will find random stuff here...
public class Util implements Serializable {
/**
* <p>This method returns the line-separator
* in a Java-6 compatible way
* On Java7 please use System.lineSeperator();</p>
* @return System line separator
*/
public static String getLineSeparator() {
return System.getProperty("line.separator");
}
/**
* <p>This method can read a specified config-node</p>
* @param node Name of the node to read
* @return Config-node
*/
//This function can read the Config-File of the program
public static String readConfig(String node) {
try {
Properties mainProperties = new Properties();
FileInputStream fis = new FileInputStream(InternalConfigDummy.CONFIG_FILE);
mainProperties.load(fis);
return mainProperties.getProperty(InternalConfigDummy.CONFIG_MAIN_PREFIX+node);
} catch (Exception e) {
Log.logError(e);
Log.logError("Couldn't read the main Config file... Stopping..."); //TODO: Translate
System.exit(1);
}
return null;
}
/**
* <p>This method generates the node list
* matching to a XPath-Expression.
* Hint: Use the {@link #nodeListToString(org.w3c.dom.NodeList)}-method to get the String value</p>
* @param sourcefile Path to the XML-File
* @param xpath_exp XPath to execute
* @return All matches nodes
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
* @throws XPathExpressionException
*/
//This function executes a XPath-Statement (From a file)
public static NodeList executeXPath(File sourcefile, String xpath_exp) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
//This Function will execute an XPath Expression
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = domFactory.newDocumentBuilder();
//This Loads the File...
Document doc = builder.parse(sourcefile);
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
//... and this will execute the XPath
XPathExpression expr = xpath.compile(xpath_exp);
Object result = expr.evaluate(doc, XPathConstants.NODESET);
//The Output is a NoteList
return (NodeList) result;
}
/**
* <p>This function grabs the nodeList of a previous XPath execute
* and executes another XPath on it</p>
* @param nl Node list to use
* @param xpath_exp XPath-Expression to execute
* @return XPath expression nodeList
* @throws ParserConfigurationException
* @throws IOException
* @throws SAXException
* @throws XPathExpressionException
*/
//This function executes a XPath-Statement (From a NodeList)
public static NodeList executeXPath(NodeList nl, String xpath_exp) throws ParserConfigurationException, IOException, SAXException, XPathExpressionException {
XPathFactory factory = XPathFactory.newInstance();
XPath xpath = factory.newXPath();
//... and this will execute the XPath
XPathExpression expr = xpath.compile(xpath_exp);
Object result = expr.evaluate(nl, XPathConstants.NODESET);
//The Output is a NoteList
return (NodeList) result;
}
/**
* <p>This converts a XPath to a String<br>
* Please note: This function will return ALL matches as a single String! If you don't want this, please use {@link #nodeListToStringArray(org.w3c.dom.NodeList)}</p>
* @param nodeList Node List to convert
* @return String equivalent of nodeList
*/
//This function converts an NodeList to a String
public static String nodeListToString(NodeList nodeList) {
String result = "";
//Read every Node and put it into the String
for (int i = 0; i < nodeList.getLength(); i++) {
result = result + nodeList.item(i).getNodeValue();
}
return result;
}
/**
* <p>This is the new way to convert a nodelist to a string. It will create a array entry for every node</p>
* @param nodeList Source node list
* @return String[] - One array-slot per node
*/
public static String[] nodeListToStringArray(NodeList nodeList) {
ArrayList<String> nodes = new ArrayList<String>();
//Read every Node and put it into the String
for (int i = 0; i < nodeList.getLength(); i++) {
nodes.add(nodeList.item(i).getNodeValue());
}
return nodes.toArray(new String[nodes.size()]);
}
/**
* <p>This function lists all FILES in a folder
* No folders are listed (Difference to the list function of File)</p>
* @param path Folder to search trough
* @return File[] - List of Files
*/
//List all Files in a given folder
public static File[] listFiles(File path)
{
ArrayList<File> foundFiles = new ArrayList<File>();
File[] fileList = path.listFiles();
if (fileList != null) {
for (File scopeFile:fileList) {
if (scopeFile.isFile()) {
foundFiles.add(scopeFile);
}
}
}
return foundFiles.toArray(new File[foundFiles.size()]);
}
/**
* <p>This function lists all FOLDERS in a folder
* No files are listed (Difference to the list function of File)</p>
* @param path Folder to search trough
* @return File[] - List of Folders
*/
//List all folders in a given folder
public static File[] listDirectorys(File path)
{
ArrayList<File> foundFiles = new ArrayList<File>();
File[] fileList = path.listFiles();
if (fileList != null) {
for (File scopeFile:fileList) {
if (scopeFile.isDirectory()) {
foundFiles.add(scopeFile);
}
}
}
return foundFiles.toArray(new File[foundFiles.size()]);
}
/**
* <p>This method will delete the extension from a file name</p>
* @param str Filename with fileextension
* @return File name without extension
*/
//Deletes the File-Extension of a Filename
public static String deleteFileExtension(String str) {
int lastIndex = str.toLowerCase().lastIndexOf(".");
if (lastIndex > 0) {
char [] charArray;
charArray = str.toCharArray();
String ret = "";
for (int i=0;i<lastIndex;i++) {
ret = ret + charArray[i];
}
return ret;
} else {
return str;
}
}
/**
* <p>This method translates a text.
* It needs the ID of the text to translate.
* Normally there are many more of these methods, specialised for the class</p>
* @param id Name iof the text to translate
* @return Translated text
*/
//The raw translate routine. This is more an "abstract" routine. There are specialised methods in some classes (Mostly for replacing local variables)
//The installer uses an other translation routine! Its in the Installer class!
public static String translate(String id) {
String langFile = readConfig("langFile");
try {
Properties properties = new Properties();
FileInputStream fis = new FileInputStream(new File(InternalConfigDummy.LANG_ROOT+"/"+langFile));
properties.load(fis);
String translatedText = properties.getProperty(id);
if (translatedText != null) {
return translatedText;
} else {
Log.logWarning("Couldn't translate text with ID " + id + "... This is normally an error in the language-file...");
return "Text translation error";
}
} catch (Exception e) {
Log.logError(e);
Log.logWarning("Couldn't translate text with ID " + id + "... This is normally an error in the language-file...");
return "Text translation error";
}
}
/**
* <p>Saves an Object to a file (can only be used on serializable Objects)</p>
* @param saveObject Object to save
* @param path Path to save the Object to
* @throws IOException
*/
//Saves an Object to a file
public static void saveObject(Object saveObject, File path) throws IOException {
ObjectOutputStream o = new ObjectOutputStream(new FileOutputStream(path,false));
o.writeObject(saveObject);
o.close();
}
/**
* <p>Loads an Object from a file (You need to know the type yourself)</p>
* @param path Path to load the Object from
* @return Object - The loaded object
* @throws IOException
* @throws ClassNotFoundException
*/
//Loads an Object from a file
public static Object loadObject(File path) throws IOException, ClassNotFoundException {
ObjectInputStream o = new ObjectInputStream(new FileInputStream(path));
Object result = o.readObject();
o.close();
return result;
}
/**
* <p>Executes a RegEx statement on a string</p>
* @param source The source String
* @param regEx RegEx to execute
* @return RegEx manipulated String
*/
//Function to execute RegEx, gives back the first String that matches the RegEx
public static String execRegEx(String source, String regEx) {
Pattern p = Pattern.compile(regEx);
Matcher m = p.matcher(source);
if (m.find()) {
return source.substring(m.start(), m.end());
} else {
return null;
}
}
/**
* <p>Reads the content of a Text-File to a String</p>
* @param pathname Path to the textfile
* @return Content of textfile
* @throws IOException
*/
//Reads a Text-File and converts it to a String
public static String textFileToString(File pathname) throws IOException {
StringBuilder fileContents = new StringBuilder((int)pathname.length());
Scanner scanner = new Scanner(pathname);
String lineSeparator = getLineSeparator();
try {
while(scanner.hasNextLine()) {
fileContents.append(scanner.nextLine() + lineSeparator);
}
return fileContents.toString();
} finally {
scanner.close();
}
}
/**
* <p>Executes a command as a Shell-Command</p>
* @param command Command to execute
* @throws IOException
* @throws InterruptedException
*/
//Executes a Shell-Command
public static void shellExec(String command) throws IOException, InterruptedException {
Process process = Runtime.getRuntime().exec(command);
process.waitFor();
}
/**
* <p>Saves the content of a String as Textfile</p>
* @param file File to save to
* @param string String to save
* @throws FileNotFoundException
*/
//Saves a String as Textfile
public static void stringToTextfile(File file, String string) throws IOException {
file.getParentFile().mkdirs();
file.createNewFile();
PrintStream out = null;
out = new PrintStream(new FileOutputStream(file));
out.print(string);
out.close();
}
/**
* <p>Opens a file with it's registerted application</p>
* @param file File to open
* @throws IOException
*/
//opens a file with it's associated application
public static void openWithStandartApp(File file) throws IOException {
Desktop.getDesktop().open(file);
}
/**
* <p>Shows a standard error-dialog</p>
* @param text Text to show
* @param title Title to show
*/
//Shows an Error Message
public static void showError(String text, String title) {
JOptionPane.showMessageDialog(new Frame(),translate("stdErrorPrefix")+text+translate("stdErrorSuffix"), title,JOptionPane.ERROR_MESSAGE);
}
/**
* <p>Shows a standard error-dialog</p>
* @param text Text to show
*/
//Shows an Error Message
public static void showError(String text) {
showError(text, translate("stdErrorTitle"));
}
/**
* <p>Shows a standard error-dialog</p>
* @param e Exception to use
* @param title Title of the window
*/
public static void showError(Exception e, String title) {
showError(exceptionToString(e),title);
}
/**
* <p>Shows a standard error-dialog</p>
* @param e Exception to use
*/
public static void showError(Exception e) {
showError(e,translate("stdErrorTitle"));
}
/**
* <p>Shows a plain error-dialog (No external Stuff will be read, just for emergency purpose)</p>
* @param text Text to show
* @param title Title of the window
*/
//This method shows only the given message (Only used when there is an initialisation error)
public static void showPureError(String text, String title) {
JOptionPane.showMessageDialog(new Frame(),text, title,JOptionPane.ERROR_MESSAGE);
}
/**
* <p>Shows a plain error-dialog (No external Stuff will be read, just for emergency purpose)</p>
* @param text Text to show
*/
public static void showPureError(String text) {
showPureError(text,"Fatal Error");
}
/**
* <p>Translates a error to a String</p>
* @param e Exception to use
* @return Error-String (Stacktrace)
*/
public static String exceptionToString(Exception e) {
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
e.printStackTrace(pw);
return sw.toString();
}
/**
* <p>Shows a standard warning-dialog</p>
* @param text Text to show
* @param title Title of the window
*/
public static void showWarning(String text, String title) {
JOptionPane.showMessageDialog(new Frame(),translate("stdWarnPrefix")+text+translate("stdWarnSuffix"), title,JOptionPane.WARNING_MESSAGE);
}
/**
* <p>Shows a standard info-dialog</p>
* @param text Text to show
* @param title Title of the window
*/
public static void showInfo(String text, String title) {
JOptionPane.showMessageDialog(new Frame(),translate("stdInfoPrefix")+text+translate("stdInfoSuffix"), title,JOptionPane.INFORMATION_MESSAGE);
}
/**
* <p>Shows a info-dialog without prefix and duffix</p>
* @param text Text to show
* @param title Title of the window
*/
public static void showPureInfo(String text, String title) {
JOptionPane.showMessageDialog(new Frame(),text, title,JOptionPane.INFORMATION_MESSAGE);
}
/**
* <p>Executes a method from a external jar</p>
* @param AjarFile Jar-File from that the code should be excuted
* @param sourceClass Class from which the code should be executed
* @param method Execution method
* @param parameterTypes List of classes to use for the call
* @param args Value of the parameters
* @return Return of method
* @throws IOException
* @throws ClassNotFoundException
* @throws NoSuchMethodException
* @throws IllegalAccessException
* @throws InstantiationException
* @throws InvocationTargetException
*/
//Executes an Method form an external Java-Application
public static Object execMethod(File AjarFile, String sourceClass, String method, Class<?> [] parameterTypes, Object [] args) throws IOException, ClassNotFoundException, NoSuchMethodException, IllegalAccessException, InstantiationException, InvocationTargetException {
//Load .jar Files
String jarFilePath=AjarFile.getAbsolutePath();
JarFile jarFile = new JarFile( jarFilePath/*path*/);
Enumeration e = jarFile.entries();
URL[] urls = {new URL("jar:file:"+jarFilePath+"!/")};
URLClassLoader c1 = URLClassLoader.newInstance(urls);
while (e.hasMoreElements()) {
JarEntry je = (JarEntry) e.nextElement();
if (je.isDirectory() || !je.getName().endsWith(".class")) {
continue;
}
String className = je.getName().substring(0,je.getName().length()-6);
className = className.replace("/",".");
Class<?> endClass = c1.loadClass(className);
if (className.equals(sourceClass)) {
Method m1 = endClass.getDeclaredMethod(method,parameterTypes);
return m1.invoke(endClass.newInstance(),args);
}
}
return null;
}
public static Locale getLocale() {
return Locale.getDefault();
}
/**
* <p>Resolves an XPath value to a File (eg.: Value: EUR, XPath: /currency/ISO4217, Search Folder: data/currnecy) would resolve to euro.xml</p>
* @param xpath Xpath to use
* @param value Value it has to match
* @param searchFolder Folder to search in
* @param recursive Decide if wether or not the function should be executed recursively
* @return File[] - Matching Files
* @throws ParserConfigurationException
* @throws SAXException
* @throws XPathExpressionException
* @throws IOException
*/
//Resolves an XPath value to a File (eg.: Value: EUR, XPath: /currency/ISO4217, Search Folder: data/currnecy) would resolve to euro.xml
public static File[] xmlFileToXpathExpression(String xpath, String value, File searchFolder, boolean recursive) throws ParserConfigurationException, SAXException, XPathExpressionException, IOException {
ArrayList<File> foundFiles = new ArrayList<File>();
for (File scopeFile:searchFolder.listFiles()) {
if (scopeFile.isFile()) {
if (isValidXml(scopeFile)) {
if (Util.nodeListToString(Util.executeXPath(scopeFile,xpath)).equals(value)) {
foundFiles.add(scopeFile);
}
}
}
if (scopeFile.isDirectory()) {
if (recursive) {
Collections.addAll(foundFiles,xmlFileToXpathExpression(xpath, value, searchFolder, recursive));
}
}
}
return foundFiles.toArray(new File[foundFiles.size()]);
}
/**
* <p>Formats a load String so it is valid</p>
* @param path Path relative from Util-Class
* @return URL to the recourse
*/
//Formats a load String so it is valid
public static String createLoadString(String path) {
URL url = Util.class.getResource(path);
return url.toExternalForm();
}
/**
* <p>Returns the Screen size of the Computer (without side/menu-bars)</p>
* @return Screen size
*/
//Get the REAL screen Size
public static Dimension getScreenSize() {
GraphicsEnvironment ge = GraphicsEnvironment.getLocalGraphicsEnvironment();
Rectangle bounds = ge.getMaximumWindowBounds();
return bounds.getSize();
}
/**
* <p>Copys a file</p>
* @param source Sourcefile
* @param destination Destination of copy
* @throws IOException
*/
public static void copy(File source, File destination) throws IOException {
//File in = new File(source);
//File out = new File(destination);
FileChannel inChannel = new FileInputStream(source).getChannel();
FileChannel outChannel = new FileOutputStream(destination).getChannel();
inChannel.transferTo(0, inChannel.size(), outChannel);
}
/**
* <p>Chekcs if an XML-File is valid</p>
* @param xml XML-File to check
* @return boolean - isValidXml
*/
public static boolean isValidXml(File xml) {
//This Function will execute an XPath Expression
if (!xml.exists()) {
return false;
}
DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
DocumentBuilder builder = null;
try {
builder = domFactory.newDocumentBuilder();
} catch (ParserConfigurationException e) {
return false;
}
//This Loads the File...
try {
Document doc = builder.parse(xml.getAbsolutePath());
} catch (SAXException e) {
return false;
} catch (IOException e) {
return false;
}
return true;
}
/**
* <p>Downloads a file from the Internet</p>
* @param source URI to file
* @param target Local file to save to
* @throws IOException
*/
public static void download(URI source, File target) throws IOException {
ReadableByteChannel rbc = Channels.newChannel(source.toURL().openStream());
FileOutputStream fos = new FileOutputStream(target,false);
fos.getChannel().transferFrom(rbc, 0, Long.MAX_VALUE);
}
/**
* <p>Read the main-Configuration from the Disk</p>
* @return Properties in the VisualProperties format
* @throws IOException
*/
public static VisualProperties loadConfigurationFromDisk() throws IOException {
VisualProperties vprop = new VisualProperties();
vprop.loadFromFile(InternalConfigDummy.CONFIG_FILE);
return vprop;
}
/**
* <p>Writes the main Configuration to the disk</p>
* @param vprop
* @throws IOException
*/
public static void saveConfigurationToDisk(VisualProperties vprop) throws IOException {
vprop.saveToFile(InternalConfigDummy.CONFIG_FILE);
}
/**
* <p>Generates a scratch-configuration</p>
* @return The default configuration
*/
public static VisualProperties getDefaultConfigurationFile() {
VisualProperties vprops = new VisualProperties();
vprops.addComment("This is a configuration template. Log- & main-settings are maintained here.");
vprops.addComment("Log setting begin with \"log.\" the main setting begin with \"main.\"");
vprops.addEmptyLine();
vprops.addComment("===================== MAIN CONFIGURATION =====================#");
vprops.setProperty("main.langFile", "en_GB.properties");
vprops.addEmptyLine();
vprops.addEmptyLine();
vprops.addComment("===================== LOG CONFIGURATION =====================#");
vprops.addComment("his configuration XML will generate an Output like: [19.10.2013 20:14:17] Info: ==== STARTING SESSION ====");
vprops.addComment("(Relative) path for the log file");
vprops.setProperty("log.path", "data/log/log.log");
vprops.addEmptyLine();
vprops.addComment("What will be logged");
vprops.setProperty("log.debug", "false");
vprops.setProperty("log.info", "true");
vprops.setProperty("log.warn", "true");
vprops.setProperty("log.error","true");
vprops.addEmptyLine();
vprops.addComment("Text for Logging");
vprops.setProperty("log.debugText","Debug: ");
vprops.setProperty("log.infoText","Info: ");
vprops.setProperty("log.warnText","Warn: ");
vprops.setProperty("log.errorText","Error: ");
vprops.addEmptyLine();
vprops.addComment("Formatting settings for the Date/Time Output");
vprops.setProperty("log.dateTimeFormat","dd.MM.yyyy HH:mm:ss");
vprops.setProperty("log.dateTimePrefix","[");
vprops.setProperty("log.dateTimeSuffix","]");
return vprops;
}
}
| lgpl-3.0 |
christopher-worley/common-app | core-commonapp-model-jpa/src/main/java/core/data/model/jpa/agreement/AgreementJpaImpl.java | 8130 | /**
* Copyright 2009 Core Information Solutions LLC
*
* This file is part of Core CommonApp Framework.
*
* Core CommonApp Framework 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.
*
* Core CommonApp Framework 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 Core CommonApp Framework. If not, see <http://www.gnu.org/licenses/>.
*
*/
package core.data.model.jpa.agreement;
import java.util.Date;
import java.util.List;
import javax.persistence.CascadeType;
import javax.persistence.Column;
import javax.persistence.Entity;
import javax.persistence.GeneratedValue;
import javax.persistence.GenerationType;
import javax.persistence.Id;
import javax.persistence.JoinColumn;
import javax.persistence.ManyToOne;
import javax.persistence.OneToMany;
import javax.persistence.Table;
import core.data.model.agreement.Agreement;
import core.data.model.agreement.AgreementContactMech;
import core.data.model.agreement.AgreementRole;
import core.data.model.agreement.AgreementStatus;
import core.data.model.agreement.AgreementType;
import core.data.model.util.DataUtil;
@Entity
@Table (name="agreement")
public class AgreementJpaImpl implements Agreement
{
@Id
@GeneratedValue (strategy=GenerationType.IDENTITY)
@Column (name="agreement_id")
private Integer agreementId;
@ManyToOne (targetEntity=AgreementTypeJpaImpl.class)
@JoinColumn (name="agreement_type_id")
private AgreementType agreementType;
@Column (name="created_date")
private Date createdDate;
@Column (name="effective_date")
private Date effectiveDate;
@Column (name="title")
private String title;
@OneToMany (cascade={CascadeType.ALL}, targetEntity=AgreementContactMechJpaImpl.class)
@JoinColumn (name="agreement_id")
private List<AgreementContactMech> agreementContactMechs;
@OneToMany (cascade={CascadeType.ALL}, targetEntity=AgreementRoleJpaImpl.class)
@JoinColumn (name="agreement_id")
private List<AgreementRole> agreementRoles;
@OneToMany (cascade={CascadeType.ALL}, targetEntity=AgreementStatusJpaImpl.class)
@JoinColumn (name="agreement_id")
private List<AgreementStatus> agreementStatus;
/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object obj)
{
// TODO data object equals
return super.equals(obj);
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getAgreementContactMechs()
*/
public List<AgreementContactMech> getAgreementContactMechs()
{
return agreementContactMechs;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getAgreementId()
*/
public Integer getAgreementId()
{
return agreementId;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getAgreementRoles()
*/
public List<AgreementRole> getAgreementRoles()
{
return agreementRoles;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getAgreementStatus()
*/
public List<AgreementStatus> getAgreementStatus()
{
return agreementStatus;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getAgreementType()
*/
public AgreementType getAgreementType()
{
return agreementType;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getCreatedDate()
*/
public Date getCreatedDate()
{
return createdDate;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getEffectiveDate()
*/
public Date getEffectiveDate()
{
return effectiveDate;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getId()
*/
public Integer getId()
{
return getAgreementId();
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#getTitle()
*/
public String getTitle()
{
return title;
}
/* (non-Javadoc)
* @see java.lang.Object#hashCode()
*/
public int hashCode()
{
// TODO data object hash code
return super.hashCode();
}
public boolean isEquivalent(Object object)
{
Agreement agreement = (Agreement) object;
return getAgreementId().equals(agreement.getAgreementId())
&& DataUtil.isEquivalent(getAgreementType(), agreement.getAgreementType())
&& getCreatedDate().equals(agreement.getCreatedDate())
&& getEffectiveDate().equals(agreement.getEffectiveDate())
&& getTitle().equals(agreement.getTitle())
&& DataUtil.isEquivalent(getAgreementContactMechs(), agreement.getAgreementContactMechs())
&& DataUtil.isEquivalent(getAgreementRoles(), agreement.getAgreementRoles())
&& DataUtil.isEquivalent(getAgreementStatus(), agreement.getAgreementStatus());
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setAgreementContactMechs(java.util.List)
*/
public void setAgreementContactMechs(List<AgreementContactMech> agreementContactMechs)
{
this.agreementContactMechs = agreementContactMechs;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setAgreementId(java.lang.Integer)
*/
public void setAgreementId(Integer agreementId)
{
this.agreementId = agreementId;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setAgreementRoles(java.util.List)
*/
public void setAgreementRoles(List<AgreementRole> agreementRoles)
{
this.agreementRoles = agreementRoles;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setAgreementStatus(java.util.List)
*/
public void setAgreementStatus(List<AgreementStatus> agreementStatus)
{
this.agreementStatus = agreementStatus;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setAgreementType(core.data.model.agreement.AgreementType)
*/
public void setAgreementType(AgreementType agreementType)
{
this.agreementType = agreementType;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setCreatedDate(java.sql.Date)
*/
public void setCreatedDate(Date createdDate)
{
this.createdDate = createdDate;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setEffectiveDate(java.sql.Date)
*/
public void setEffectiveDate(Date effectiveDate)
{
this.effectiveDate = effectiveDate;
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setId(java.lang.Integer)
*/
public void setId(Integer id)
{
setAgreementId(id);
}
/* (non-Javadoc)
* @see core.data.model.agreement.IAgreement#setTitle(java.lang.String)
*/
public void setTitle(String title)
{
this.title = title;
}
/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString()
{
return "Agreement("
+ "agreementId="
+ getAgreementId()
+ ",agreementType="
+ getAgreementType()
+ ",createdDate="
+ getCreatedDate()
+ ",effectiveDate="
+ getEffectiveDate()
+ ",title="
+ getTitle()
+ ",agreementContactMech="
+ getAgreementContactMechs()
+ ",agreementRoles="
+ getAgreementRoles()
+ ",agreementStatus="
+ getAgreementStatus()
+ ")";
}
}
| lgpl-3.0 |
neeker/umsp | umsp-core/src/com/partsoft/umsp/utils/UmspUtils.java | 6773 | package com.partsoft.umsp.utils;
import java.io.UnsupportedEncodingException;
import com.partsoft.umsp.Constants.LineProtocols;
import com.partsoft.umsp.Constants.LineTypes;
import com.partsoft.umsp.Constants.MessageCodes;
import com.partsoft.umsp.io.ByteArrayBuffer;
import com.partsoft.utils.StringUtils;
public class UmspUtils {
public static String lineType2Protocol(int type) {
String protocol_result = null;
switch (type) {
case 1:
protocol_result = LineProtocols.CMPP;
break;
case 2:
protocol_result = LineProtocols.SMGP;
break;
case 3:
protocol_result = LineProtocols.SGIP;
break;
default:
protocol_result = LineProtocols.UNKN;
break;
}
return protocol_result;
}
public static int lineProtocol2Type(String protocol) {
int line_type_result = LineTypes.UNKN;
if (LineProtocols.CMPP.equalsIgnoreCase(protocol)) {
line_type_result = LineTypes.CMPP;
} else if (LineProtocols.SMGP.equalsIgnoreCase(protocol)) {
line_type_result = LineTypes.SMGP;
} else if (LineProtocols.SGIP.equalsIgnoreCase(protocol)) {
line_type_result = LineTypes.SGIP;
}
return line_type_result;
}
public static byte[] string2FixedBytes(String s, int fixLength) {
ByteArrayBuffer resultBuffer = new ByteArrayBuffer(fixLength);
byte sBytes[] = s == null ? new byte[0] : new byte[s.length()];
int byLen = sBytes.length;
for (int i = 0; i < byLen; i++) {
sBytes[i] = (byte) s.charAt(i);
}
int fixZero = 0;
if (byLen > fixLength) {
byLen = fixLength;
} else if (byLen < fixLength) {
fixZero = fixLength - byLen;
}
resultBuffer.put(sBytes);
for (; fixZero > 0; fixZero--) {
resultBuffer.put((byte)0);
}
return resultBuffer.array();
}
public static int fromBcdBytes(byte[] bcdBytes, int index, int length) {
StringBuffer temp = new StringBuffer(length * 2);
for (int i = index; i < index + length; i++) {
temp.append((char) ((bcdBytes[i] & 0xF0) >>> 4 | 0x30));
temp.append((char) (bcdBytes[i] & 0x0F | 0x30));
}
return Integer.parseInt(temp.toString());
}
public static int fromBcdBytes(byte[] bcdBytes) {
return fromBcdBytes(bcdBytes, 0, bcdBytes.length);
}
public static byte[] toBcdBytes(int value) {
String str_value = "" + value;
if (str_value.length() % 2 != 0)
str_value = "0" + str_value;
byte[] result = new byte[str_value.length() / 2];
for (int i = 0; i < result.length; i++) {
result[i] = (byte) ((((str_value.charAt(i * 2) - '0') & 0x0F) << 4) | ((str_value.charAt(i * 2 + 1) - '0') & 0x0F));
}
return result;
}
public static byte[] toGsmBytes(String msg) {
return toGsmBytes(msg, MessageCodes.ASCII);
}
public static byte[] toGsmBytes(String msg, int code) {
byte result[] = null;
if (msg != null) {
switch (code) {
case MessageCodes.UCS2:
result = StringUtils.toUCS2Bytes(msg);
break;
case MessageCodes.GBK:
try {
result = msg.getBytes("GBK");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
break;
default:
result = new byte[msg.length()];
for (int i = 0; i < result.length; i++) {
result[i] = (byte) msg.charAt(i);
}
break;
}
}
return result;
}
public static String fromGsmBytes(byte[] msg) {
return fromGsmBytes(msg, 0, msg == null ? 0 : msg.length, MessageCodes.ASCII);
}
public static String fromGsmBytes(byte[] msg, int index, int length) {
return fromGsmBytes(msg, index, length, MessageCodes.ASCII);
}
public static String fromGsmBytes(byte[] msg, int index, int length, int code) {
String result = null;
if (msg != null) {
switch (code) {
case MessageCodes.UCS2:
result = StringUtils.fromUCS2Bytes(msg, index, length);
break;
case MessageCodes.GBK:
try {
result = new String(msg, index, length, "GBK");
} catch (UnsupportedEncodingException e) {
throw new IllegalArgumentException(e);
}
break;
default:
char msg_chars[] = new char[msg.length];
for (int i = 0; i < msg.length; i++) {
msg_chars[i] = (char) msg[i];
}
result = new String(msg_chars, index, length);
break;
}
}
return result;
}
public static String fromGsmBytes(byte[] msg, int code) {
String result = null;
if (msg != null) {
result = fromGsmBytes(msg, 0, msg.length, code);
}
return result;
}
/**
* 是否为移动号码
*
* @param userNumber
* @return
*/
@Deprecated
public static boolean isPhoneNumberOfCM(String userNumber) {
userNumber = UmspUtils.getStandardPhoneNumberOfCN(userNumber);
return userNumber.startsWith("86134") || userNumber.startsWith("86135") || userNumber.startsWith("86136")
|| userNumber.startsWith("86137") || userNumber.startsWith("86138") || userNumber.startsWith("86139")
|| userNumber.startsWith("86147") || userNumber.startsWith("86150") || userNumber.startsWith("86151")
|| userNumber.startsWith("86152") || userNumber.startsWith("86157") || userNumber.startsWith("86158")
|| userNumber.startsWith("86159") || userNumber.startsWith("86187") || userNumber.startsWith("86188")
|| userNumber.startsWith("86183") || userNumber.startsWith("86182");
}
/**
* 是否为联通号码
*
* @param userNumber
* @return
*/
@Deprecated
public static boolean isPhoneNumberOfCU(String userNumber) {
userNumber = UmspUtils.getStandardPhoneNumberOfCN(userNumber);
return userNumber.startsWith("86130") || userNumber.startsWith("86131") || userNumber.startsWith("86132")
|| userNumber.startsWith("86145") || userNumber.startsWith("86155") || userNumber.startsWith("86156")
|| userNumber.startsWith("86186");
}
/**
* 是否为电信号码
*
* @param userNumber
* @return
*/
@Deprecated
public static boolean isPhoneNumberOfCT(String userNumber) {
userNumber = UmspUtils.getStandardPhoneNumberOfCN(userNumber);
return userNumber.startsWith("86133") || userNumber.startsWith("86153") || userNumber.startsWith("86180")
|| userNumber.startsWith("86189");
}
@Deprecated
public static String getSmsProtocolPrefixByPhoneNumber(String userNumber) throws IllegalArgumentException {
String protocal_name = null;
if (isPhoneNumberOfCT(userNumber)) {
protocal_name = "SMGP";
} else if (isPhoneNumberOfCU(userNumber)) {
protocal_name = "SGIP";
} else if (isPhoneNumberOfCM(userNumber)) {
protocal_name = "CMPP";
} else {
throw new IllegalArgumentException("error phone number");
}
return protocal_name;
}
public static String getStandardPhoneNumberOfCN(String userNumber) {
if (userNumber.startsWith("01")) {
userNumber = userNumber.substring(1);
}
if (userNumber.startsWith("1")) {
if (!userNumber.startsWith("86")) {
userNumber = "86" + userNumber;
}
}
return userNumber;
}
}
| lgpl-3.0 |