diff
stringlengths 262
553k
| is_single_chunk
bool 2
classes | is_single_function
bool 1
class | buggy_function
stringlengths 20
391k
| fixed_function
stringlengths 0
392k
|
---|---|---|---|---|
diff --git a/tubular-core/src/main/java/org/trancecode/xproc/PipelineParser.java b/tubular-core/src/main/java/org/trancecode/xproc/PipelineParser.java
index 2fe91c5f..751577d0 100644
--- a/tubular-core/src/main/java/org/trancecode/xproc/PipelineParser.java
+++ b/tubular-core/src/main/java/org/trancecode/xproc/PipelineParser.java
@@ -1,650 +1,652 @@
/*
* Copyright (C) 2008 Herve Quiroz
*
* 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
*
* $Id$
*/
package org.trancecode.xproc;
import com.google.common.base.Function;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import com.google.common.collect.Maps;
import com.google.common.collect.Sets;
import java.net.URI;
import java.util.Collection;
import java.util.List;
import java.util.Map;
import java.util.Set;
import javax.xml.transform.Source;
import javax.xml.transform.TransformerException;
import net.sf.saxon.s9api.DocumentBuilder;
import net.sf.saxon.s9api.QName;
import net.sf.saxon.s9api.SaxonApiException;
import net.sf.saxon.s9api.XdmNode;
import net.sf.saxon.s9api.XdmNodeKind;
import org.trancecode.logging.Logger;
import org.trancecode.xml.Location;
import org.trancecode.xml.saxon.Saxon;
import org.trancecode.xml.saxon.SaxonAxis;
import org.trancecode.xml.saxon.SaxonLocation;
import org.trancecode.xproc.XProcXmlModel.Attributes;
import org.trancecode.xproc.XProcXmlModel.Elements;
import org.trancecode.xproc.binding.DocumentPortBinding;
import org.trancecode.xproc.binding.EmptyPortBinding;
import org.trancecode.xproc.binding.InlinePortBinding;
import org.trancecode.xproc.binding.PipePortBinding;
import org.trancecode.xproc.binding.PortBinding;
import org.trancecode.xproc.port.Port;
import org.trancecode.xproc.port.Port.Type;
import org.trancecode.xproc.port.PortReference;
import org.trancecode.xproc.port.XProcPorts;
import org.trancecode.xproc.step.PipelineStepProcessor;
import org.trancecode.xproc.step.Step;
import org.trancecode.xproc.step.StepProcessor;
import org.trancecode.xproc.step.XProcSteps;
import org.trancecode.xproc.variable.Variable;
/**
* @author Herve Quiroz
*/
public final class PipelineParser
{
private static final Logger LOG = Logger.getLogger(PipelineParser.class);
private final URI baseUri;
private final PipelineContext context;
private final Source source;
private PipelineLibrary library;
private final Map<QName, Step> localLibrary = Maps.newHashMap();
private Step mainPipeline;
private XdmNode rootNode;
public static PipelineLibrary parseLibrary(final PipelineContext context, final Source source)
{
LOG.trace("{@method} source = {}", source.getSystemId());
final PipelineParser parser = new PipelineParser(context, source);
parser.parse();
return parser.getLibrary();
}
public static PipelineLibrary parseLibrary(final PipelineContext context, final Source source,
final PipelineLibrary library)
{
LOG.trace("{@method} source = {}", source.getSystemId());
final PipelineParser parser = new PipelineParser(context, source, library);
parser.parse();
return parser.getLibrary();
}
public static Step parsePipeline(final PipelineContext context, final Source source)
{
LOG.trace("{@method} source = {}", source.getSystemId());
final PipelineParser parser = new PipelineParser(context, source);
parser.parse();
return parser.getPipeline();
}
public static Step parsePipeline(final PipelineContext context, final Source source, final PipelineLibrary library)
{
LOG.trace("{@method} source = {}", source.getSystemId());
final PipelineParser parser = new PipelineParser(context, source, library);
parser.parse();
return parser.getPipeline();
}
private PipelineParser(final PipelineContext context, final Source source)
{
this(context, source, context.getPipelineLibrary());
}
private PipelineParser(final PipelineContext context, final Source source, final PipelineLibrary library)
{
this.context = Preconditions.checkNotNull(context);
this.source = Preconditions.checkNotNull(source);
this.library = Preconditions.checkNotNull(library);
baseUri = URI.create(source.getSystemId());
}
private void parse()
{
try
{
final DocumentBuilder documentBuilder = context.getProcessor().newDocumentBuilder();
documentBuilder.setLineNumbering(true);
final XdmNode pipelineDocument = documentBuilder.build(source);
rootNode = SaxonAxis.childElement(pipelineDocument, Elements.ELEMENTS_ROOT);
parseImports(rootNode);
if (Elements.ELEMENTS_DECLARE_STEP_OR_PIPELINE.contains(rootNode.getNodeName()))
{
mainPipeline = parseDeclareStep(rootNode);
}
else if (rootNode.getNodeName().equals(Elements.LIBRARY))
{
parseDeclareSteps(rootNode);
}
else
{
unsupportedElement(rootNode);
}
}
catch (final SaxonApiException e)
{
throw new PipelineException(e);
}
}
private void declareStep(final Step step)
{
localLibrary.put(step.getType(), step);
}
private void parseDeclareSteps(final XdmNode node)
{
for (final XdmNode stepNode : SaxonAxis.childElements(node, Elements.ELEMENTS_DECLARE_STEP_OR_PIPELINE))
{
parseDeclareStep(stepNode);
}
}
private Step parseDeclareStep(final XdmNode stepNode)
{
final QName type = Saxon.getAttributeAsQName(stepNode, Attributes.TYPE);
LOG.trace("new step type: {}", type);
Step step;
if (context.getStepProcessors().containsKey(type))
{
final StepProcessor stepProcessor = context.getStepProcessor(type);
LOG.trace("stepProcessor = {}", stepProcessor);
step = Step.newStep(stepNode, type, stepProcessor, false);
}
else
{
final String name = getStepName(stepNode);
step = PipelineStepProcessor.newPipeline(type);
step = step.setName(name);
}
step = step.setLocation(getLocation(stepNode));
if (PipelineStepProcessor.isPipeline(step))
{
step = PipelineStepProcessor.addImplicitPorts(step);
}
step = parseStepChildNodes(stepNode, step);
declareStep(step);
return step;
}
private Step parseStepChildNodes(final XdmNode stepNode, final Step step)
{
Step configuredStep = step;
for (final XdmNode node : SaxonAxis.childNodes(stepNode))
{
configuredStep = parseStepChildNode(node, configuredStep);
}
return configuredStep;
}
private Step parseStepChildNode(final XdmNode node, final Step step)
{
if (node.getNodeKind() == XdmNodeKind.ELEMENT)
{
if (node.getNodeName().equals(Elements.IMPORT))
{
parseImport(node);
return step;
}
if (Elements.ELEMENTS_PORTS.contains(node.getNodeName()))
{
final String portName = getPortName(node);
if (step.getPorts().containsKey(portName))
{
return parseWithPort(node, step);
}
else
{
return parseDeclarePort(node, step);
}
}
if (node.getNodeName().equals(Elements.VARIABLE))
{
return parseDeclareVariable(node, step);
}
if (node.getNodeName().equals(Elements.OPTION))
{
return parseOption(node, step);
}
if (node.getNodeName().equals(Elements.WITH_OPTION))
{
return parseWithOption(node, step);
}
if (node.getNodeName().equals(Elements.WITH_PARAM))
{
return parseWithParam(node, step);
}
if (getSupportedStepTypes().contains(node.getNodeName()))
{
return step.addChildStep(parseInstanceStep(node));
}
if (Elements.ELEMENTS_DECLARE_STEP_OR_PIPELINE.contains(node.getNodeName()))
{
parseDeclareStep(node);
return step;
}
if (Elements.ELEMENTS_IGNORED.contains(node.getNodeName()))
{
return step;
}
if (node.getNodeName().equals(Elements.LOG))
{
return parseLog(node, step);
}
throw XProcExceptions.xs0044(node);
}
else if (node.getNodeKind() == XdmNodeKind.ATTRIBUTE)
{
LOG.trace("{} = {}", node.getNodeName(), node.getStringValue());
final QName name = node.getNodeName();
final String value = node.getStringValue();
+ // TODO: it's not very good to test step's type here !
if (name.getNamespaceURI().isEmpty() && !name.equals(Attributes.NAME) && !name.equals(Attributes.TYPE)
- && (!name.equals(Attributes.VERSION) || XProcSteps.XSLT.equals(step.getType())))
+ && (!name.equals(Attributes.VERSION) || XProcSteps.XSLT.equals(step.getType()) ||
+ XProcSteps.HASH.equals(step.getType())))
{
if (!step.hasOptionDeclared(name))
{
throw XProcExceptions.xs0031(getLocation(node), name, step.getType());
}
return step.withOptionValue(name, value, node);
}
}
else if (node.getNodeKind() == XdmNodeKind.TEXT)
{
if (!node.getStringValue().trim().isEmpty())
{
LOG.trace("unexpected text node: {}", node.getStringValue());
}
}
else
{
LOG.warn("child node not supported: {}", node.getNodeKind());
}
return step;
}
private Step parseLog(final XdmNode logNode, final Step step)
{
final String port = logNode.getAttributeValue(Attributes.PORT);
final String href = logNode.getAttributeValue(Attributes.HREF);
LOG.trace("{@method} port = {} ; href = {}", port, href);
if (!step.hasPortDeclared(port) || step.hasLogDeclaredForPort(port))
{
throw XProcExceptions.xs0026(getLocation(logNode), step, port);
}
return step.addLog(port, href);
}
private Step parseWithPort(final XdmNode portNode, final Step step)
{
final String portName = getPortName(portNode);
final Port port = step.getPort(portName);
assert port.isParameter() || port.getType().equals(getPortType(portNode)) : "port = " + port.getType()
+ " ; with-port = " + getPortType(portNode);
final String select = portNode.getAttributeValue(Attributes.SELECT);
LOG.trace("select = {}", select);
final String sequence = portNode.getAttributeValue(Attributes.SEQUENCE);
LOG.trace("sequence = {}", sequence);
final Port configuredPort = port.setSelect(select).setSequence(sequence)
.setPortBindings(parsePortBindings(portNode));
LOG.trace("step {} with port {}", step, port);
return step.withPort(configuredPort);
}
private String getPortName(final XdmNode portNode)
{
if (Elements.ELEMENTS_STANDARD_PORTS.contains(portNode.getNodeName()))
{
return portNode.getAttributeValue(Attributes.PORT);
}
if (portNode.getNodeName().equals(Elements.ITERATION_SOURCE))
{
return XProcPorts.ITERATION_SOURCE;
}
if (portNode.getNodeName().equals(Elements.VIEWPORT_SOURCE))
{
return XProcPorts.VIEWPORT_SOURCE;
}
if (portNode.getNodeName().equals(Elements.XPATH_CONTEXT))
{
return XProcPorts.XPATH_CONTEXT;
}
throw new IllegalStateException(portNode.getNodeName().toString());
}
private Iterable<PortBinding> parsePortBindings(final XdmNode portNode)
{
return Iterables.transform(SaxonAxis.childElements(portNode, Elements.ELEMENTS_PORT_BINDINGS),
new Function<XdmNode, PortBinding>()
{
@Override
public PortBinding apply(final XdmNode node)
{
return parsePortBinding(node);
}
});
}
private void unsupportedElement(final XdmNode node)
{
throw new IllegalStateException(node.getNodeName().toString());
}
private static Location getLocation(final XdmNode node)
{
// TODO cache locations per node (slower at parsing but less memory
// used)
return SaxonLocation.of(node);
}
private Step getDeclaredStep(final QName name)
{
final Step fromLocalLibrary = localLibrary.get(name);
if (fromLocalLibrary != null)
{
return fromLocalLibrary;
}
return library.newStep(name);
}
private Step parseDeclarePort(final XdmNode portNode, final Step step)
{
final String portName;
if (portNode.getNodeName().equals(Elements.XPATH_CONTEXT))
{
portName = XProcPorts.XPATH_CONTEXT;
}
else
{
portName = portNode.getAttributeValue(Attributes.PORT);
}
final Port.Type type = getPortType(portNode);
Port port = Port.newPort(step.getName(), portName, getLocation(portNode), type);
port = port.setPrimary(portNode.getAttributeValue(Attributes.PRIMARY));
port = port.setSequence(portNode.getAttributeValue(Attributes.SEQUENCE));
port = port.setSelect(portNode.getAttributeValue(Attributes.SELECT));
port = port.setPortBindings(parsePortBindings(portNode));
LOG.trace("new port: {}", port);
return step.declarePort(port);
}
private static Type getPortType(final XdmNode node)
{
if (Elements.ELEMENTS_INPUT_PORTS.contains(node.getNodeName()))
{
if ("parameter".equals(node.getAttributeValue(Attributes.KIND)))
{
return Type.PARAMETER;
}
else
{
return Type.INPUT;
}
}
return Type.OUTPUT;
}
private PortBinding parsePortBinding(final XdmNode portBindingNode)
{
if (portBindingNode.getNodeName().equals(Elements.PIPE))
{
final String stepName = portBindingNode.getAttributeValue(Attributes.STEP);
final String portName = portBindingNode.getAttributeValue(Attributes.PORT);
return new PipePortBinding(PortReference.newReference(stepName, portName), getLocation(portBindingNode));
}
if (portBindingNode.getNodeName().equals(Elements.EMPTY))
{
return new EmptyPortBinding(getLocation(portBindingNode));
}
if (portBindingNode.getNodeName().equals(Elements.DOCUMENT))
{
final String href = portBindingNode.getAttributeValue(Attributes.HREF);
return new DocumentPortBinding(href, getLocation(portBindingNode));
}
if (portBindingNode.getNodeName().equals(Elements.INLINE))
{
final XdmNode inlineDocument = Saxon.asDocumentNode(context.getProcessor(),
SaxonAxis.childNodesNoAttributes(portBindingNode));
return new InlinePortBinding(inlineDocument, getLocation(portBindingNode));
}
throw new PipelineException("not supported: %s", portBindingNode.getNodeName());
}
private Step parseOption(final XdmNode node, final Step step)
{
LOG.trace("step = {}", step.getType());
final QName name = new QName(node.getAttributeValue(Attributes.NAME), node);
Variable option = Variable.newOption(name, getLocation(node));
final String select = node.getAttributeValue(Attributes.SELECT);
LOG.trace("name = {} ; select = {}", name, select);
option = option.setSelect(select);
final String required = node.getAttributeValue(Attributes.REQUIRED);
LOG.trace("name = {} ; required = {}", name, required);
if (required != null)
{
option = option.setRequired(Boolean.parseBoolean(required));
}
option = option.setNode(node);
return step.declareVariable(option);
}
private Step parseWithParam(final XdmNode node, final Step step)
{
LOG.trace("step = {}", step.getType());
final QName name = new QName(node.getAttributeValue(Attributes.NAME));
final String select = node.getAttributeValue(Attributes.SELECT);
LOG.trace("name = {} ; select = {}", name, select);
return step.withParam(name, select, null, getLocation(node), node);
}
private Step parseWithOption(final XdmNode node, final Step step)
{
LOG.trace("step = {}", step.getType());
final QName name = new QName(node.getAttributeValue(Attributes.NAME));
final String select = node.getAttributeValue(Attributes.SELECT);
LOG.trace("name = {} ; select = {}", name, select);
return step.withOption(name, select, node);
}
private Step parseDeclareVariable(final XdmNode node, final Step step)
{
final QName name = new QName(node.getAttributeValue(Attributes.NAME), node);
final String select = node.getAttributeValue(Attributes.SELECT);
Variable variable = Variable.newVariable(name);
variable = variable.setLocation(getLocation(node));
variable = variable.setSelect(select);
variable = variable.setRequired(true);
final PortBinding portBinding = Iterables.getOnlyElement(parsePortBindings(node), null);
variable = variable.setPortBinding(portBinding);
variable = variable.setNode(node);
return step.declareVariable(variable);
}
private void parseImports(final XdmNode node)
{
for (final XdmNode importNode : SaxonAxis.childElements(node, Elements.IMPORT))
{
parseImport(importNode);
}
}
private void parseImport(final XdmNode node)
{
final String href = node.getAttributeValue(Attributes.HREF);
assert href != null;
LOG.trace("{@method} href = {}", href);
final URI libraryUri = baseUri.resolve(href);
LOG.trace("libraryUri = {} ; libraries = {}", libraryUri, library.getImportedUris());
if (!library.getImportedUris().contains(libraryUri))
{
final Source librarySource;
try
{
librarySource = context.getProcessor().getUnderlyingConfiguration().getURIResolver()
.resolve(href, source.getSystemId());
}
catch (final TransformerException e)
{
throw XProcExceptions.xs0052(SaxonLocation.of(node), libraryUri);
}
final PipelineLibrary newLibrary = parseLibrary(context, librarySource, getLibrary());
LOG.trace("new steps = {}", newLibrary.getStepTypes());
library = library.importLibrary(newLibrary);
}
else
{
LOG.trace("ignoring import statement (library already imported): {}", libraryUri);
}
}
private Collection<QName> getSupportedStepTypes()
{
return Sets.union(library.getStepTypes(), localLibrary.keySet());
}
private Step parseInstanceStep(final XdmNode node)
{
final String name = getStepName(node);
final QName type = node.getNodeName();
LOG.trace("name = {} ; type = {}", name, type);
final Step declaredStep = getDeclaredStep(type);
Step step = declaredStep.setName(name).setLocation(getLocation(node)).setNode(node);
LOG.trace("new instance step: {}", step);
LOG.trace("step processor: {}", step.getStepProcessor());
step = parseStepChildNodes(node, step);
return step;
}
private String getStepName(final XdmNode node)
{
final String explicitName = node.getAttributeValue(Attributes.NAME);
if (explicitName != null && explicitName.length() > 0)
{
return explicitName;
}
return getImplicitName(node);
}
private String getImplicitName(final XdmNode node)
{
return "!" + getImplicitName(rootNode, node);
}
private String getImplicitName(final XdmNode rootNode, final XdmNode node)
{
if (rootNode == node || node.getParent() == null)
{
return "1";
}
final int index = getNodeIndex(node);
final XdmNode parentNode = node.getParent();
return getImplicitName(rootNode, parentNode) + "." + Integer.toString(index);
}
private int getNodeIndex(final XdmNode node)
{
final XdmNode parentNode = node.getParent();
if (parentNode == null)
{
return 1;
}
final List<XdmNode> childNodes = ImmutableList.copyOf(SaxonAxis.childElements(parentNode, getStepElements()));
assert childNodes.contains(node) : node.getNodeName();
return childNodes.indexOf(node) + 1;
}
private Collection<QName> getStepElements()
{
final Collection<QName> elements = Sets.newHashSet();
elements.addAll(getSupportedStepTypes());
elements.add(Elements.DECLARE_STEP);
elements.add(Elements.LIBRARY);
elements.add(Elements.PIPELINE);
return elements;
}
private PipelineLibrary getLibrary()
{
final Set<URI> uris = ImmutableSet.of();
return new PipelineLibrary(baseUri, localLibrary, uris).importLibrary(library);
}
private Step getPipeline()
{
return mainPipeline;
}
}
| false | true | private Step parseStepChildNode(final XdmNode node, final Step step)
{
if (node.getNodeKind() == XdmNodeKind.ELEMENT)
{
if (node.getNodeName().equals(Elements.IMPORT))
{
parseImport(node);
return step;
}
if (Elements.ELEMENTS_PORTS.contains(node.getNodeName()))
{
final String portName = getPortName(node);
if (step.getPorts().containsKey(portName))
{
return parseWithPort(node, step);
}
else
{
return parseDeclarePort(node, step);
}
}
if (node.getNodeName().equals(Elements.VARIABLE))
{
return parseDeclareVariable(node, step);
}
if (node.getNodeName().equals(Elements.OPTION))
{
return parseOption(node, step);
}
if (node.getNodeName().equals(Elements.WITH_OPTION))
{
return parseWithOption(node, step);
}
if (node.getNodeName().equals(Elements.WITH_PARAM))
{
return parseWithParam(node, step);
}
if (getSupportedStepTypes().contains(node.getNodeName()))
{
return step.addChildStep(parseInstanceStep(node));
}
if (Elements.ELEMENTS_DECLARE_STEP_OR_PIPELINE.contains(node.getNodeName()))
{
parseDeclareStep(node);
return step;
}
if (Elements.ELEMENTS_IGNORED.contains(node.getNodeName()))
{
return step;
}
if (node.getNodeName().equals(Elements.LOG))
{
return parseLog(node, step);
}
throw XProcExceptions.xs0044(node);
}
else if (node.getNodeKind() == XdmNodeKind.ATTRIBUTE)
{
LOG.trace("{} = {}", node.getNodeName(), node.getStringValue());
final QName name = node.getNodeName();
final String value = node.getStringValue();
if (name.getNamespaceURI().isEmpty() && !name.equals(Attributes.NAME) && !name.equals(Attributes.TYPE)
&& (!name.equals(Attributes.VERSION) || XProcSteps.XSLT.equals(step.getType())))
{
if (!step.hasOptionDeclared(name))
{
throw XProcExceptions.xs0031(getLocation(node), name, step.getType());
}
return step.withOptionValue(name, value, node);
}
}
else if (node.getNodeKind() == XdmNodeKind.TEXT)
{
if (!node.getStringValue().trim().isEmpty())
{
LOG.trace("unexpected text node: {}", node.getStringValue());
}
}
else
{
LOG.warn("child node not supported: {}", node.getNodeKind());
}
return step;
}
| private Step parseStepChildNode(final XdmNode node, final Step step)
{
if (node.getNodeKind() == XdmNodeKind.ELEMENT)
{
if (node.getNodeName().equals(Elements.IMPORT))
{
parseImport(node);
return step;
}
if (Elements.ELEMENTS_PORTS.contains(node.getNodeName()))
{
final String portName = getPortName(node);
if (step.getPorts().containsKey(portName))
{
return parseWithPort(node, step);
}
else
{
return parseDeclarePort(node, step);
}
}
if (node.getNodeName().equals(Elements.VARIABLE))
{
return parseDeclareVariable(node, step);
}
if (node.getNodeName().equals(Elements.OPTION))
{
return parseOption(node, step);
}
if (node.getNodeName().equals(Elements.WITH_OPTION))
{
return parseWithOption(node, step);
}
if (node.getNodeName().equals(Elements.WITH_PARAM))
{
return parseWithParam(node, step);
}
if (getSupportedStepTypes().contains(node.getNodeName()))
{
return step.addChildStep(parseInstanceStep(node));
}
if (Elements.ELEMENTS_DECLARE_STEP_OR_PIPELINE.contains(node.getNodeName()))
{
parseDeclareStep(node);
return step;
}
if (Elements.ELEMENTS_IGNORED.contains(node.getNodeName()))
{
return step;
}
if (node.getNodeName().equals(Elements.LOG))
{
return parseLog(node, step);
}
throw XProcExceptions.xs0044(node);
}
else if (node.getNodeKind() == XdmNodeKind.ATTRIBUTE)
{
LOG.trace("{} = {}", node.getNodeName(), node.getStringValue());
final QName name = node.getNodeName();
final String value = node.getStringValue();
// TODO: it's not very good to test step's type here !
if (name.getNamespaceURI().isEmpty() && !name.equals(Attributes.NAME) && !name.equals(Attributes.TYPE)
&& (!name.equals(Attributes.VERSION) || XProcSteps.XSLT.equals(step.getType()) ||
XProcSteps.HASH.equals(step.getType())))
{
if (!step.hasOptionDeclared(name))
{
throw XProcExceptions.xs0031(getLocation(node), name, step.getType());
}
return step.withOptionValue(name, value, node);
}
}
else if (node.getNodeKind() == XdmNodeKind.TEXT)
{
if (!node.getStringValue().trim().isEmpty())
{
LOG.trace("unexpected text node: {}", node.getStringValue());
}
}
else
{
LOG.warn("child node not supported: {}", node.getNodeKind());
}
return step;
}
|
diff --git a/htroot/yacysearch.java b/htroot/yacysearch.java
index f751d6fc3..07ac31451 100644
--- a/htroot/yacysearch.java
+++ b/htroot/yacysearch.java
@@ -1,574 +1,574 @@
// yacysearch.java
// -----------------------
// part of the AnomicHTTPD caching proxy
// (C) by Michael Peter Christen; [email protected]
// first published on http://www.anomic.de
// Frankfurt, Germany, 2004
//
// $LastChangedDate$
// $LastChangedRevision$
// $LastChangedBy$
//
// 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
//
// Using this software in any meaning (reading, learning, copying, compiling,
// running) means that you agree that the Author(s) is (are) not responsible
// for cost, loss of data or any harm that may be caused directly or indirectly
// by usage of this softare or this documentation. The usage of this software
// is on your own risk. The installation and usage (starting/running) of this
// software may allow other people or application to access your computer and
// any attached devices and is highly dependent on the configuration of the
// software which must be done by the user of the software; the author(s) is
// (are) also not responsible for proper configuration and usage of the
// software, even if provoked by documentation provided together with
// the software.
//
// Any changes to this file according to the GPL as documented in the file
// gpl.txt aside this file in the shipment you received can be done to the
// lines that follows this copyright notice here, but changes must not be
// done inside the copyright notive above. A re-distribution must contain
// the intact and unchanged copyright notice.
// Contributions and changes to the program code must be marked as such.
//
// You must compile this file with
// javac -classpath .:../classes yacysearch.java
// if the shell's current path is HTROOT
import java.io.IOException;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URLEncoder;
import java.util.HashMap;
import java.util.Iterator;
import java.util.regex.PatternSyntaxException;
import java.util.TreeSet;
import de.anomic.htmlFilter.htmlFilterImageEntry;
import de.anomic.http.httpHeader;
import de.anomic.index.indexURLEntry;
import de.anomic.kelondro.kelondroBitfield;
import de.anomic.kelondro.kelondroMSetTools;
import de.anomic.kelondro.kelondroNaturalOrder;
import de.anomic.net.URL;
import de.anomic.plasma.plasmaCondenser;
import de.anomic.plasma.plasmaParserDocument;
import de.anomic.plasma.plasmaSearchImages;
import de.anomic.plasma.plasmaSearchPreOrder;
import de.anomic.plasma.plasmaSearchQuery;
import de.anomic.plasma.plasmaSearchRankingProfile;
import de.anomic.plasma.plasmaSearchTimingProfile;
import de.anomic.plasma.plasmaSnippetCache;
import de.anomic.plasma.plasmaSwitchboard;
import de.anomic.plasma.plasmaURL;
import de.anomic.plasma.plasmaSearchResults;
import de.anomic.server.serverCore;
import de.anomic.server.serverDate;
import de.anomic.server.serverObjects;
import de.anomic.server.serverSwitch;
import de.anomic.tools.crypt;
import de.anomic.tools.nxTools;
import de.anomic.yacy.yacyCore;
import de.anomic.yacy.yacyNewsPool;
import de.anomic.yacy.yacyNewsRecord;
import de.anomic.yacy.yacySeed;
public class yacysearch {
public static final int MAX_TOPWORDS = 24;
public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
boolean authenticated = sb.adminAuthenticated(header) >= 2;
int display = (post == null) ? 0 : post.getInt("display", 0);
if ((display == 1) && (!authenticated)) display = 0;
int input = (post == null) ? 2 : post.getInt("input", 2);
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (promoteSearchPageGreeting.length() == 0) promoteSearchPageGreeting = "P2P WEB SEARCH";
// case if no values are requested
final String referer = (String) header.get("Referer");
String querystring = (post == null) ? "" : post.get("search", "").trim();
if ((post == null) || (env == null) || (querystring.length() == 0) || (!searchAllowed)) {
// save referrer
// System.out.println("HEADER=" + header.toString());
if (referer != null) {
URL url;
try { url = new URL(referer); } catch (MalformedURLException e) { url = null; }
if ((url != null) && (serverCore.isNotLocal(url))) {
final HashMap referrerprop = new HashMap();
referrerprop.put("count", "1");
referrerprop.put("clientip", header.get("CLIENTIP"));
referrerprop.put("useragent", header.get("User-Agent"));
referrerprop.put("date", (new serverDate()).toShortString(false));
if (sb.facilityDB != null) try { sb.facilityDB.update("backlinks", referer, referrerprop); } catch (IOException e) {}
}
}
// we create empty entries for template strings
final serverObjects prop = new serverObjects();
prop.put("searchagain", 0);
prop.put("input", input);
prop.put("display", display);
prop.put("input_input", input);
prop.put("input_display", display);
prop.putASIS("input_promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("input_former", "");
prop.put("former", "");
prop.put("input_count", 10);
prop.put("input_resource", "global");
prop.put("input_time", 6);
prop.put("input_urlmaskfilter", ".*");
prop.put("input_prefermaskfilter", "");
prop.put("input_indexof", "off");
prop.put("input_constraint", plasmaSearchQuery.catchall_constraint.exportB64());
prop.put("input_cat", "href");
prop.put("input_depth", "0");
prop.put("input_contentdom", "text");
prop.put("input_contentdomCheckText", 1);
prop.put("input_contentdomCheckAudio", 0);
prop.put("input_contentdomCheckVideo", 0);
prop.put("input_contentdomCheckImage", 0);
prop.put("input_contentdomCheckApp", 0);
prop.put("type", 0);
prop.put("type_excluded", 0);
prop.put("type_combine", 0);
prop.put("type_resultbottomline", 0);
prop.put("type_results", "");
prop.put("num-results", (searchAllowed) ? 0 : 6);
return prop;
}
// collect search attributes
int maxDistance = Integer.MAX_VALUE;
if ((querystring.length() > 2) && (querystring.charAt(0) == '"') && (querystring.charAt(querystring.length() - 1) == '"')) {
querystring = querystring.substring(1, querystring.length() - 1).trim();
maxDistance = 1;
}
if (sb.facilityDB != null) try { sb.facilityDB.update("zeitgeist", querystring, post); } catch (Exception e) {}
int count = Integer.parseInt(post.get("count", "10"));
boolean global = (post == null) ? true : post.get("resource", "global").equals("global");
final boolean indexof = post.get("indexof","").equals("on");
final long searchtime = 1000 * Long.parseLong(post.get("time", "10"));
String urlmask = "";
if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) {
urlmask = ".*";
} else {
urlmask = (post.containsKey("urlmaskfilter")) ? (String) post.get("urlmaskfilter") : ".*";
}
String prefermask = post.get("prefermaskfilter", "");
if ((prefermask.length() > 0) && (prefermask.indexOf(".*") < 0)) prefermask = ".*" + prefermask + ".*";
kelondroBitfield constraint = post.containsKey("constraint") ? new kelondroBitfield(4, post.get("constraint", "______")) : plasmaSearchQuery.catchall_constraint;
if (indexof) {
constraint = new kelondroBitfield();
constraint.set(plasmaCondenser.flag_cat_indexof, true);
}
// SEARCH
final boolean indexDistributeGranted = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true");
final boolean indexReceiveGranted = sb.getConfig("allowReceiveIndex", "true").equals("true");
final boolean offline = yacyCore.seedDB.mySeed.isVirgin();
final boolean clustersearch = sb.isRobinsonMode() &&
(sb.getConfig("cluster.mode", "").equals("privatecluster") ||
sb.getConfig("cluster.mode", "").equals("publiccluster"));
if (offline || !indexDistributeGranted || !indexReceiveGranted) { global = false; }
if (clustersearch) global = true; // switches search on, but search target is limited to cluster nodes
// find search domain
int contentdomCode = plasmaSearchQuery.CONTENTDOM_TEXT;
String contentdomString = post.get("contentdom", "text");
if (contentdomString.equals("text")) contentdomCode = plasmaSearchQuery.CONTENTDOM_TEXT;
if (contentdomString.equals("audio")) contentdomCode = plasmaSearchQuery.CONTENTDOM_AUDIO;
if (contentdomString.equals("video")) contentdomCode = plasmaSearchQuery.CONTENTDOM_VIDEO;
if (contentdomString.equals("image")) contentdomCode = plasmaSearchQuery.CONTENTDOM_IMAGE;
if (contentdomString.equals("app")) contentdomCode = plasmaSearchQuery.CONTENTDOM_APP;
// patch until better search profiles are available
if ((contentdomCode != plasmaSearchQuery.CONTENTDOM_TEXT) && (count <= 10)) count = 30;
serverObjects prop = new serverObjects();
if (post.get("cat", "href").equals("href")) {
final TreeSet[] query = plasmaSearchQuery.cleanQuery(querystring); // converts also umlaute
// filter out stopwords
final TreeSet filtered = kelondroMSetTools.joinConstructive(query[0], plasmaSwitchboard.stopwords);
if (filtered.size() > 0) {
kelondroMSetTools.excludeDestructive(query[0], plasmaSwitchboard.stopwords);
}
// if a minus-button was hit, remove a special reference first
if (post.containsKey("deleteref")) {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// delete the index entry locally
final String delHash = post.get("deleteref", ""); // urlhash
sb.wordIndex.removeWordReferences(query[0], delHash);
// make new news message with negative voting
HashMap map = new HashMap();
map.put("urlhash", delHash);
map.put("vote", "negative");
map.put("refid", "");
yacyCore.newsPool.publishMyNews(yacyNewsRecord.newRecord(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map));
}
// if aplus-button was hit, create new voting message
if (post.containsKey("recommendref")) {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
final String recommendHash = post.get("recommendref", ""); // urlhash
indexURLEntry urlentry = sb.wordIndex.loadedURL.load(recommendHash, null);
if (urlentry != null) {
indexURLEntry.Components comp = urlentry.comp();
plasmaParserDocument document;
document = sb.snippetCache.retrieveDocument(comp.url(), true, 5000, true);
if (document != null) {
// create a news message
HashMap map = new HashMap();
map.put("url", comp.url().toNormalform().replace(',', '|'));
map.put("title", comp.title().replace(',', ' '));
map.put("description", ((document == null) ? comp.title() : document.getTitle()).replace(',', ' '));
map.put("author", ((document == null) ? "" : document.getAuthor()));
map.put("tags", ((document == null) ? "" : document.getKeywords(' ')));
- yacyCore.newsPool.publishMyNews(new yacyNewsRecord(yacyNewsPool.CATEGORY_SURFTIPP_ADD, map));
+ yacyCore.newsPool.publishMyNews(yacyNewsRecord.newRecord(yacyNewsPool.CATEGORY_SURFTIPP_ADD, map));
document.close();
}
}
}
// prepare search properties
final boolean yacyonline = ((yacyCore.seedDB != null) && (yacyCore.seedDB.mySeed != null) && (yacyCore.seedDB.mySeed.getPublicAddress() != null));
final boolean samesearch = env.getConfig("last-search", "").equals(querystring + contentdomString);
final boolean globalsearch = (global) && (yacyonline) && (!samesearch);
// do the search
TreeSet queryHashes = plasmaCondenser.words2hashes(query[0]);
plasmaSearchQuery thisSearch = new plasmaSearchQuery(
querystring,
queryHashes,
plasmaCondenser.words2hashes(query[1]),
maxDistance,
prefermask,
contentdomCode,
count,
searchtime,
urlmask,
(clustersearch && globalsearch) ? plasmaSearchQuery.SEARCHDOM_CLUSTERALL :
((globalsearch) ? plasmaSearchQuery.SEARCHDOM_GLOBALDHT : plasmaSearchQuery.SEARCHDOM_LOCAL),
"",
20,
constraint);
plasmaSearchRankingProfile ranking = (sb.getConfig("rankingProfile", "").length() == 0) ? new plasmaSearchRankingProfile(contentdomString) : new plasmaSearchRankingProfile("", crypt.simpleDecode(sb.getConfig("rankingProfile", ""), null));
plasmaSearchTimingProfile localTiming = new plasmaSearchTimingProfile(4 * thisSearch.maximumTime / 10, thisSearch.wantedResults);
plasmaSearchTimingProfile remoteTiming = new plasmaSearchTimingProfile(6 * thisSearch.maximumTime / 10, thisSearch.wantedResults);
plasmaSearchResults results = new plasmaSearchResults();
String wrongregex = null;
try{
results = sb.searchFromLocal(thisSearch, ranking, localTiming, remoteTiming, true, (String) header.get("CLIENTIP"));
}
catch(PatternSyntaxException e){
wrongregex = e.getPattern();
}
//prop=sb.searchFromLocal(thisSearch, ranking, localTiming, remoteTiming, true, (String) header.get("CLIENTIP"));
prop=new serverObjects();
//prop.put("references", 0);
URL wordURL=null;
prop.put("num-results_totalcount", results.getTotalcount());
prop.put("num-results_filteredcount", results.getFilteredcount());
prop.put("num-results_orderedcount", results.getOrderedcount());
prop.put("num-results_linkcount", results.getLinkcount());
prop.put("type_results", 0);
if(results.numResults()!=0){
//we've got results
prop.put("num-results_totalcount", results.getTotalcount());
prop.put("num-results_filteredcount", results.getFilteredcount());
prop.put("num-results_orderedcount", Integer.toString(results.getOrderedcount())); //why toString?
prop.put("num-results_globalresults", results.getGlobalresults());
for(int i=0;i<results.numResults();i++){
plasmaSearchResults.searchResult result=results.getResult(i);
prop.put("type_results_" + i + "_authorized_recommend", (yacyCore.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.getUrl()) == null) ? 1 : 0);
//prop.put("type_results_" + i + "_authorized_recommend_deletelink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&deleteref=" + result.getUrlhash() + "&urlmaskfilter=.*");
//prop.put("type_results_" + i + "_authorized_recommend_recommendlink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&recommendref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_recommend_deletelink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&deleteref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_recommend_recommendlink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&recommendref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_urlhash", result.getUrlhash());
prop.put("type_results_" + i + "_description", result.getUrlentry().comp().title());
prop.put("type_results_" + i + "_url", result.getUrl());
try{
URL url=new URL(result.getUrl());
int port=url.getPort();
//TODO: parse <link rel="favicon" /> ...
- prop.put("type_results_" + i + "_favicon", url.getProtocol()+"://"+url.getHost()+((port!=-1)?String.valueOf(port)+":":"")+"/favicon.ico");
+ prop.put("type_results_" + i + "_favicon", url.getProtocol() + "://" + url.getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico");
}catch(MalformedURLException e){}
prop.put("type_results_" + i + "_urlhash", result.getUrlhash());
prop.put("type_results_" + i + "_urlhexhash", yacySeed.b64Hash2hexHash(result.getUrlhash()));
prop.put("type_results_" + i + "_urlname", nxTools.shortenURLString(result.getUrlname(), 120));
prop.put("type_results_" + i + "_date", plasmaSwitchboard.dateString(result.getUrlentry().moddate()));
prop.put("type_results_" + i + "_ybr", plasmaSearchPreOrder.ybr(result.getUrlentry().hash()));
prop.put("type_results_" + i + "_size", Long.toString(result.getUrlentry().size()));
try {
prop.put("type_results_" + i + "_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (UnsupportedEncodingException e) {}
prop.put("type_results_" + i + "_former", results.getFormerSearch());
prop.put("type_results_" + i + "_rankingprops", result.getUrlentry().word().toPropertyForm() + ", domLengthEstimated=" + plasmaURL.domLengthEstimation(result.getUrlhash()) +
((plasmaURL.probablyRootURL(result.getUrlhash())) ? ", probablyRootURL" : "") +
(((wordURL = plasmaURL.probablyWordURL(result.getUrlhash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform() : ""));
// adding snippet if available
if (result.hasSnippet()) {
prop.put("type_results_" + i + "_snippet", 1);
prop.putASIS("type_results_" + i + "_snippet_text", result.getSnippet().getLineMarked(results.getQuery().queryHashes));//FIXME: the ASIS should not be needed, if there is no html in .java
} else {
if (post.containsKey("fetchSnippet")) {
/* fetch the snippet now */
try {
// snippet fetch timeout
int textsnippet_timeout = Integer.parseInt(env.getConfig("timeout_media", "10000"));
// boolean line_end_with_punctuation
boolean pre = post.get("pre", "false").equals("true");
// if 'remove' is set to true, then RWI references to URLs that do not have the snippet are removed
boolean remove = post.get("remove", "false").equals("true");
URL resultURL = new URL(result.getUrl());
plasmaSnippetCache.TextSnippet snippet = sb.snippetCache.retrieveTextSnippet(
resultURL,
queryHashes,
true,
pre,
260,
textsnippet_timeout
);
if (snippet.getErrorCode() < 11) {
// no problems occurred
//prop.put("text", (snippet.exists()) ? snippet.getLineMarked(queryHashes) : "unknown");
prop.putASIS("type_results_" + i + "_snippet_text", (snippet.exists()) ? snippet.getLineMarked(queryHashes) : "unknown");
} else {
// problems with snippet fetch
prop.put("type_results_" + i + "_snippet_text", (remove) ? sb.snippetCache.failConsequences(snippet, queryHashes) : snippet.getError());
}
prop.put("type_results_" + i + "_snippet", 1);
} catch (MalformedURLException e) {
prop.put("type_results_" + i + "_snippet", 0);
prop.put("type_results_" + i + "_snippet_text", "");
}
} else {
/* no snippet available (will be fetched later via ajax) */
prop.put("type_results_" + i + "_snippet", 0);
prop.put("type_results_" + i + "_snippet_text", "");
}
}
prop.put("type_results", results.numResults());
prop.put("references", results.getReferences());
prop.put("num-results_linkcount", Integer.toString(results.numResults()));
}
}
// remember the last search expression
env.setConfig("last-search", querystring + contentdomString);
// process result of search
prop.put("type_resultbottomline", 0);
if (filtered.size() > 0) {
prop.put("excluded", 1);
prop.put("excluded_stopwords", filtered.toString());
} else {
prop.put("excluded", 0);
}
if (prop == null || prop.size() == 0) {
if (post.get("search", "").length() < 3) {
prop.put("num-results", 2); // no results - at least 3 chars
} else {
prop.put("num-results", 1); // no results
}
} else {
final int totalcount = prop.getInt("num-results_totalcount", 0);
if (totalcount >= 10) {
final Object[] references = (Object[]) prop.get( "references", new String[0]);
prop.put("num-results", 5);
int hintcount = references.length;
if (hintcount > 0) {
prop.put("type_combine", 1);
// get the topwords
final TreeSet topwords = new TreeSet(kelondroNaturalOrder.naturalOrder);
String tmp = "";
for (int i = 0; i < hintcount; i++) {
tmp = (String) references[i];
if (tmp.matches("[a-z]+")) {
topwords.add(tmp);
// } else {
// topwords.add("(" + tmp + ")");
}
}
// filter out the badwords
final TreeSet filteredtopwords = kelondroMSetTools.joinConstructive(topwords, plasmaSwitchboard.badwords);
if (filteredtopwords.size() > 0) {
kelondroMSetTools.excludeDestructive(topwords, plasmaSwitchboard.badwords);
}
//avoid stopwords being topwords
if (env.getConfig("filterOutStopwordsFromTopwords", "true").equals("true")) {
if ((plasmaSwitchboard.stopwords != null) && (plasmaSwitchboard.stopwords.size() > 0)) {
kelondroMSetTools.excludeDestructive(topwords, plasmaSwitchboard.stopwords);
}
}
String word;
hintcount = 0;
final Iterator iter = topwords.iterator();
while (iter.hasNext()) {
word = (String) iter.next();
if (word != null) {
prop.put("type_combine_words_" + hintcount + "_word", word);
prop.put("type_combine_words_" + hintcount + "_newsearch", post.get("search", "").replace(' ', '+') + "+" + word);
prop.put("type_combine_words_" + hintcount + "_count", count);
prop.put("type_combine_words_" + hintcount + "_resource", ((global) ? "global" : "local"));
prop.put("type_combine_words_" + hintcount + "_time", (searchtime / 1000));
}
prop.put("type_combine_words", hintcount);
if (hintcount++ > MAX_TOPWORDS) {
break;
}
}
}
} else {
if (wrongregex != null) {
prop.put("num-results_wrong_regex", wrongregex);
prop.put("num-results", 4);
}
else if (totalcount == 0) {
prop.put("num-results", 3); // long
}
else {
prop.put("num-results", 5);
}
}
}
if (wrongregex != null) {
prop.put("type_resultbottomline", 0);
}
else if (yacyonline) {
if (global) {
prop.put("type_resultbottomline", 1);
prop.put("type_resultbottomline_globalresults", prop.get("num-results_globalresults", "0"));
} else {
prop.put("type_resultbottomline", 0);
}
} else {
if (global) {
prop.put("type_resultbottomline", 3);
} else {
prop.put("type_resultbottomline", 0);
}
}
prop.put("type", (thisSearch.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) ? 0 : ((thisSearch.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) ? 2 : 1));
if (prop.getInt("type", 0) == 1) prop.put("type_mediatype", contentdomString);
prop.put("input_cat", "href");
prop.put("input_depth", "0");
// adding some additional properties needed for the rss feed
String hostName = (String) header.get("Host", "localhost");
if (hostName.indexOf(":") == -1) hostName += ":" + serverCore.getPortNr(env.getConfig("port", "8080"));
prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif");
}
if (post.get("cat", "href").equals("image")) {
int depth = post.getInt("depth", 0);
int columns = post.getInt("columns", 6);
URL url = null;
try {url = new URL(post.get("url", ""));} catch (MalformedURLException e) {}
plasmaSearchImages si = new plasmaSearchImages(sb.snippetCache, 6000, url, depth);
Iterator i = si.entries();
htmlFilterImageEntry ie;
int line = 0;
while (i.hasNext()) {
int col = 0;
for (col = 0; col < columns; col++) {
if (!i.hasNext()) break;
ie = (htmlFilterImageEntry) i.next();
String urls = ie.url().toString();
String name = "";
int p = urls.lastIndexOf('/');
if (p > 0) name = urls.substring(p + 1);
prop.put("type_results_" + line + "_line_" + col + "_url", urls);
prop.put("type_results_" + line + "_line_" + col + "_name", name);
}
prop.put("type_results_" + line + "_line", col);
line++;
}
prop.put("type_results", line);
prop.put("type", 3); // set type of result: image list
prop.put("input_cat", "href");
prop.put("input_depth", depth);
}
// if user is not authenticated, he may not vote for URLs
int linkcount = Integer.parseInt(prop.get("num-results_linkcount", "0"));
for (int i=0; i<linkcount; i++)
prop.put("type_results_" + i + "_authorized", (authenticated) ? 1 : 0);
prop.put("searchagain", (global) ? 1 : 0);
prop.put("input", input);
prop.put("display", display);
prop.put("input_input", input);
prop.put("input_display", display);
prop.putASIS("input_promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("input_former", post.get("search", ""));
prop.put("former", post.get("search", ""));
prop.put("input_count", count);
prop.put("input_resource", (global) ? "global" : "local");
prop.put("input_time", searchtime / 1000);
prop.put("input_urlmaskfilter", urlmask);
prop.put("input_prefermaskfilter", prefermask);
prop.put("input_indexof", (indexof) ? "on" : "off");
prop.put("input_constraint", constraint.exportB64());
prop.put("input_contentdom", contentdomString);
prop.put("input_contentdomCheckText", (contentdomCode == plasmaSearchQuery.CONTENTDOM_TEXT) ? 1 : 0);
prop.put("input_contentdomCheckAudio", (contentdomCode == plasmaSearchQuery.CONTENTDOM_AUDIO) ? 1 : 0);
prop.put("input_contentdomCheckVideo", (contentdomCode == plasmaSearchQuery.CONTENTDOM_VIDEO) ? 1 : 0);
prop.put("input_contentdomCheckImage", (contentdomCode == plasmaSearchQuery.CONTENTDOM_IMAGE) ? 1 : 0);
prop.put("input_contentdomCheckApp", (contentdomCode == plasmaSearchQuery.CONTENTDOM_APP) ? 1 : 0);
prop.put("type_former", post.get("search", "")); //the query-string used to get the snippets
// return rewrite properties
return prop;
}
}
| false | true | public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
boolean authenticated = sb.adminAuthenticated(header) >= 2;
int display = (post == null) ? 0 : post.getInt("display", 0);
if ((display == 1) && (!authenticated)) display = 0;
int input = (post == null) ? 2 : post.getInt("input", 2);
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (promoteSearchPageGreeting.length() == 0) promoteSearchPageGreeting = "P2P WEB SEARCH";
// case if no values are requested
final String referer = (String) header.get("Referer");
String querystring = (post == null) ? "" : post.get("search", "").trim();
if ((post == null) || (env == null) || (querystring.length() == 0) || (!searchAllowed)) {
// save referrer
// System.out.println("HEADER=" + header.toString());
if (referer != null) {
URL url;
try { url = new URL(referer); } catch (MalformedURLException e) { url = null; }
if ((url != null) && (serverCore.isNotLocal(url))) {
final HashMap referrerprop = new HashMap();
referrerprop.put("count", "1");
referrerprop.put("clientip", header.get("CLIENTIP"));
referrerprop.put("useragent", header.get("User-Agent"));
referrerprop.put("date", (new serverDate()).toShortString(false));
if (sb.facilityDB != null) try { sb.facilityDB.update("backlinks", referer, referrerprop); } catch (IOException e) {}
}
}
// we create empty entries for template strings
final serverObjects prop = new serverObjects();
prop.put("searchagain", 0);
prop.put("input", input);
prop.put("display", display);
prop.put("input_input", input);
prop.put("input_display", display);
prop.putASIS("input_promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("input_former", "");
prop.put("former", "");
prop.put("input_count", 10);
prop.put("input_resource", "global");
prop.put("input_time", 6);
prop.put("input_urlmaskfilter", ".*");
prop.put("input_prefermaskfilter", "");
prop.put("input_indexof", "off");
prop.put("input_constraint", plasmaSearchQuery.catchall_constraint.exportB64());
prop.put("input_cat", "href");
prop.put("input_depth", "0");
prop.put("input_contentdom", "text");
prop.put("input_contentdomCheckText", 1);
prop.put("input_contentdomCheckAudio", 0);
prop.put("input_contentdomCheckVideo", 0);
prop.put("input_contentdomCheckImage", 0);
prop.put("input_contentdomCheckApp", 0);
prop.put("type", 0);
prop.put("type_excluded", 0);
prop.put("type_combine", 0);
prop.put("type_resultbottomline", 0);
prop.put("type_results", "");
prop.put("num-results", (searchAllowed) ? 0 : 6);
return prop;
}
// collect search attributes
int maxDistance = Integer.MAX_VALUE;
if ((querystring.length() > 2) && (querystring.charAt(0) == '"') && (querystring.charAt(querystring.length() - 1) == '"')) {
querystring = querystring.substring(1, querystring.length() - 1).trim();
maxDistance = 1;
}
if (sb.facilityDB != null) try { sb.facilityDB.update("zeitgeist", querystring, post); } catch (Exception e) {}
int count = Integer.parseInt(post.get("count", "10"));
boolean global = (post == null) ? true : post.get("resource", "global").equals("global");
final boolean indexof = post.get("indexof","").equals("on");
final long searchtime = 1000 * Long.parseLong(post.get("time", "10"));
String urlmask = "";
if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) {
urlmask = ".*";
} else {
urlmask = (post.containsKey("urlmaskfilter")) ? (String) post.get("urlmaskfilter") : ".*";
}
String prefermask = post.get("prefermaskfilter", "");
if ((prefermask.length() > 0) && (prefermask.indexOf(".*") < 0)) prefermask = ".*" + prefermask + ".*";
kelondroBitfield constraint = post.containsKey("constraint") ? new kelondroBitfield(4, post.get("constraint", "______")) : plasmaSearchQuery.catchall_constraint;
if (indexof) {
constraint = new kelondroBitfield();
constraint.set(plasmaCondenser.flag_cat_indexof, true);
}
// SEARCH
final boolean indexDistributeGranted = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true");
final boolean indexReceiveGranted = sb.getConfig("allowReceiveIndex", "true").equals("true");
final boolean offline = yacyCore.seedDB.mySeed.isVirgin();
final boolean clustersearch = sb.isRobinsonMode() &&
(sb.getConfig("cluster.mode", "").equals("privatecluster") ||
sb.getConfig("cluster.mode", "").equals("publiccluster"));
if (offline || !indexDistributeGranted || !indexReceiveGranted) { global = false; }
if (clustersearch) global = true; // switches search on, but search target is limited to cluster nodes
// find search domain
int contentdomCode = plasmaSearchQuery.CONTENTDOM_TEXT;
String contentdomString = post.get("contentdom", "text");
if (contentdomString.equals("text")) contentdomCode = plasmaSearchQuery.CONTENTDOM_TEXT;
if (contentdomString.equals("audio")) contentdomCode = plasmaSearchQuery.CONTENTDOM_AUDIO;
if (contentdomString.equals("video")) contentdomCode = plasmaSearchQuery.CONTENTDOM_VIDEO;
if (contentdomString.equals("image")) contentdomCode = plasmaSearchQuery.CONTENTDOM_IMAGE;
if (contentdomString.equals("app")) contentdomCode = plasmaSearchQuery.CONTENTDOM_APP;
// patch until better search profiles are available
if ((contentdomCode != plasmaSearchQuery.CONTENTDOM_TEXT) && (count <= 10)) count = 30;
serverObjects prop = new serverObjects();
if (post.get("cat", "href").equals("href")) {
final TreeSet[] query = plasmaSearchQuery.cleanQuery(querystring); // converts also umlaute
// filter out stopwords
final TreeSet filtered = kelondroMSetTools.joinConstructive(query[0], plasmaSwitchboard.stopwords);
if (filtered.size() > 0) {
kelondroMSetTools.excludeDestructive(query[0], plasmaSwitchboard.stopwords);
}
// if a minus-button was hit, remove a special reference first
if (post.containsKey("deleteref")) {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// delete the index entry locally
final String delHash = post.get("deleteref", ""); // urlhash
sb.wordIndex.removeWordReferences(query[0], delHash);
// make new news message with negative voting
HashMap map = new HashMap();
map.put("urlhash", delHash);
map.put("vote", "negative");
map.put("refid", "");
yacyCore.newsPool.publishMyNews(yacyNewsRecord.newRecord(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map));
}
// if aplus-button was hit, create new voting message
if (post.containsKey("recommendref")) {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
final String recommendHash = post.get("recommendref", ""); // urlhash
indexURLEntry urlentry = sb.wordIndex.loadedURL.load(recommendHash, null);
if (urlentry != null) {
indexURLEntry.Components comp = urlentry.comp();
plasmaParserDocument document;
document = sb.snippetCache.retrieveDocument(comp.url(), true, 5000, true);
if (document != null) {
// create a news message
HashMap map = new HashMap();
map.put("url", comp.url().toNormalform().replace(',', '|'));
map.put("title", comp.title().replace(',', ' '));
map.put("description", ((document == null) ? comp.title() : document.getTitle()).replace(',', ' '));
map.put("author", ((document == null) ? "" : document.getAuthor()));
map.put("tags", ((document == null) ? "" : document.getKeywords(' ')));
yacyCore.newsPool.publishMyNews(new yacyNewsRecord(yacyNewsPool.CATEGORY_SURFTIPP_ADD, map));
document.close();
}
}
}
// prepare search properties
final boolean yacyonline = ((yacyCore.seedDB != null) && (yacyCore.seedDB.mySeed != null) && (yacyCore.seedDB.mySeed.getPublicAddress() != null));
final boolean samesearch = env.getConfig("last-search", "").equals(querystring + contentdomString);
final boolean globalsearch = (global) && (yacyonline) && (!samesearch);
// do the search
TreeSet queryHashes = plasmaCondenser.words2hashes(query[0]);
plasmaSearchQuery thisSearch = new plasmaSearchQuery(
querystring,
queryHashes,
plasmaCondenser.words2hashes(query[1]),
maxDistance,
prefermask,
contentdomCode,
count,
searchtime,
urlmask,
(clustersearch && globalsearch) ? plasmaSearchQuery.SEARCHDOM_CLUSTERALL :
((globalsearch) ? plasmaSearchQuery.SEARCHDOM_GLOBALDHT : plasmaSearchQuery.SEARCHDOM_LOCAL),
"",
20,
constraint);
plasmaSearchRankingProfile ranking = (sb.getConfig("rankingProfile", "").length() == 0) ? new plasmaSearchRankingProfile(contentdomString) : new plasmaSearchRankingProfile("", crypt.simpleDecode(sb.getConfig("rankingProfile", ""), null));
plasmaSearchTimingProfile localTiming = new plasmaSearchTimingProfile(4 * thisSearch.maximumTime / 10, thisSearch.wantedResults);
plasmaSearchTimingProfile remoteTiming = new plasmaSearchTimingProfile(6 * thisSearch.maximumTime / 10, thisSearch.wantedResults);
plasmaSearchResults results = new plasmaSearchResults();
String wrongregex = null;
try{
results = sb.searchFromLocal(thisSearch, ranking, localTiming, remoteTiming, true, (String) header.get("CLIENTIP"));
}
catch(PatternSyntaxException e){
wrongregex = e.getPattern();
}
//prop=sb.searchFromLocal(thisSearch, ranking, localTiming, remoteTiming, true, (String) header.get("CLIENTIP"));
prop=new serverObjects();
//prop.put("references", 0);
URL wordURL=null;
prop.put("num-results_totalcount", results.getTotalcount());
prop.put("num-results_filteredcount", results.getFilteredcount());
prop.put("num-results_orderedcount", results.getOrderedcount());
prop.put("num-results_linkcount", results.getLinkcount());
prop.put("type_results", 0);
if(results.numResults()!=0){
//we've got results
prop.put("num-results_totalcount", results.getTotalcount());
prop.put("num-results_filteredcount", results.getFilteredcount());
prop.put("num-results_orderedcount", Integer.toString(results.getOrderedcount())); //why toString?
prop.put("num-results_globalresults", results.getGlobalresults());
for(int i=0;i<results.numResults();i++){
plasmaSearchResults.searchResult result=results.getResult(i);
prop.put("type_results_" + i + "_authorized_recommend", (yacyCore.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.getUrl()) == null) ? 1 : 0);
//prop.put("type_results_" + i + "_authorized_recommend_deletelink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&deleteref=" + result.getUrlhash() + "&urlmaskfilter=.*");
//prop.put("type_results_" + i + "_authorized_recommend_recommendlink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&recommendref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_recommend_deletelink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&deleteref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_recommend_recommendlink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&recommendref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_urlhash", result.getUrlhash());
prop.put("type_results_" + i + "_description", result.getUrlentry().comp().title());
prop.put("type_results_" + i + "_url", result.getUrl());
try{
URL url=new URL(result.getUrl());
int port=url.getPort();
//TODO: parse <link rel="favicon" /> ...
prop.put("type_results_" + i + "_favicon", url.getProtocol()+"://"+url.getHost()+((port!=-1)?String.valueOf(port)+":":"")+"/favicon.ico");
}catch(MalformedURLException e){}
prop.put("type_results_" + i + "_urlhash", result.getUrlhash());
prop.put("type_results_" + i + "_urlhexhash", yacySeed.b64Hash2hexHash(result.getUrlhash()));
prop.put("type_results_" + i + "_urlname", nxTools.shortenURLString(result.getUrlname(), 120));
prop.put("type_results_" + i + "_date", plasmaSwitchboard.dateString(result.getUrlentry().moddate()));
prop.put("type_results_" + i + "_ybr", plasmaSearchPreOrder.ybr(result.getUrlentry().hash()));
prop.put("type_results_" + i + "_size", Long.toString(result.getUrlentry().size()));
try {
prop.put("type_results_" + i + "_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (UnsupportedEncodingException e) {}
prop.put("type_results_" + i + "_former", results.getFormerSearch());
prop.put("type_results_" + i + "_rankingprops", result.getUrlentry().word().toPropertyForm() + ", domLengthEstimated=" + plasmaURL.domLengthEstimation(result.getUrlhash()) +
((plasmaURL.probablyRootURL(result.getUrlhash())) ? ", probablyRootURL" : "") +
(((wordURL = plasmaURL.probablyWordURL(result.getUrlhash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform() : ""));
// adding snippet if available
if (result.hasSnippet()) {
prop.put("type_results_" + i + "_snippet", 1);
prop.putASIS("type_results_" + i + "_snippet_text", result.getSnippet().getLineMarked(results.getQuery().queryHashes));//FIXME: the ASIS should not be needed, if there is no html in .java
} else {
if (post.containsKey("fetchSnippet")) {
/* fetch the snippet now */
try {
// snippet fetch timeout
int textsnippet_timeout = Integer.parseInt(env.getConfig("timeout_media", "10000"));
// boolean line_end_with_punctuation
boolean pre = post.get("pre", "false").equals("true");
// if 'remove' is set to true, then RWI references to URLs that do not have the snippet are removed
boolean remove = post.get("remove", "false").equals("true");
URL resultURL = new URL(result.getUrl());
plasmaSnippetCache.TextSnippet snippet = sb.snippetCache.retrieveTextSnippet(
resultURL,
queryHashes,
true,
pre,
260,
textsnippet_timeout
);
if (snippet.getErrorCode() < 11) {
// no problems occurred
//prop.put("text", (snippet.exists()) ? snippet.getLineMarked(queryHashes) : "unknown");
prop.putASIS("type_results_" + i + "_snippet_text", (snippet.exists()) ? snippet.getLineMarked(queryHashes) : "unknown");
} else {
// problems with snippet fetch
prop.put("type_results_" + i + "_snippet_text", (remove) ? sb.snippetCache.failConsequences(snippet, queryHashes) : snippet.getError());
}
prop.put("type_results_" + i + "_snippet", 1);
} catch (MalformedURLException e) {
prop.put("type_results_" + i + "_snippet", 0);
prop.put("type_results_" + i + "_snippet_text", "");
}
} else {
/* no snippet available (will be fetched later via ajax) */
prop.put("type_results_" + i + "_snippet", 0);
prop.put("type_results_" + i + "_snippet_text", "");
}
}
prop.put("type_results", results.numResults());
prop.put("references", results.getReferences());
prop.put("num-results_linkcount", Integer.toString(results.numResults()));
}
}
// remember the last search expression
env.setConfig("last-search", querystring + contentdomString);
// process result of search
prop.put("type_resultbottomline", 0);
if (filtered.size() > 0) {
prop.put("excluded", 1);
prop.put("excluded_stopwords", filtered.toString());
} else {
prop.put("excluded", 0);
}
if (prop == null || prop.size() == 0) {
if (post.get("search", "").length() < 3) {
prop.put("num-results", 2); // no results - at least 3 chars
} else {
prop.put("num-results", 1); // no results
}
} else {
final int totalcount = prop.getInt("num-results_totalcount", 0);
if (totalcount >= 10) {
final Object[] references = (Object[]) prop.get( "references", new String[0]);
prop.put("num-results", 5);
int hintcount = references.length;
if (hintcount > 0) {
prop.put("type_combine", 1);
// get the topwords
final TreeSet topwords = new TreeSet(kelondroNaturalOrder.naturalOrder);
String tmp = "";
for (int i = 0; i < hintcount; i++) {
tmp = (String) references[i];
if (tmp.matches("[a-z]+")) {
topwords.add(tmp);
// } else {
// topwords.add("(" + tmp + ")");
}
}
// filter out the badwords
final TreeSet filteredtopwords = kelondroMSetTools.joinConstructive(topwords, plasmaSwitchboard.badwords);
if (filteredtopwords.size() > 0) {
kelondroMSetTools.excludeDestructive(topwords, plasmaSwitchboard.badwords);
}
//avoid stopwords being topwords
if (env.getConfig("filterOutStopwordsFromTopwords", "true").equals("true")) {
if ((plasmaSwitchboard.stopwords != null) && (plasmaSwitchboard.stopwords.size() > 0)) {
kelondroMSetTools.excludeDestructive(topwords, plasmaSwitchboard.stopwords);
}
}
String word;
hintcount = 0;
final Iterator iter = topwords.iterator();
while (iter.hasNext()) {
word = (String) iter.next();
if (word != null) {
prop.put("type_combine_words_" + hintcount + "_word", word);
prop.put("type_combine_words_" + hintcount + "_newsearch", post.get("search", "").replace(' ', '+') + "+" + word);
prop.put("type_combine_words_" + hintcount + "_count", count);
prop.put("type_combine_words_" + hintcount + "_resource", ((global) ? "global" : "local"));
prop.put("type_combine_words_" + hintcount + "_time", (searchtime / 1000));
}
prop.put("type_combine_words", hintcount);
if (hintcount++ > MAX_TOPWORDS) {
break;
}
}
}
} else {
if (wrongregex != null) {
prop.put("num-results_wrong_regex", wrongregex);
prop.put("num-results", 4);
}
else if (totalcount == 0) {
prop.put("num-results", 3); // long
}
else {
prop.put("num-results", 5);
}
}
}
if (wrongregex != null) {
prop.put("type_resultbottomline", 0);
}
else if (yacyonline) {
if (global) {
prop.put("type_resultbottomline", 1);
prop.put("type_resultbottomline_globalresults", prop.get("num-results_globalresults", "0"));
} else {
prop.put("type_resultbottomline", 0);
}
} else {
if (global) {
prop.put("type_resultbottomline", 3);
} else {
prop.put("type_resultbottomline", 0);
}
}
prop.put("type", (thisSearch.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) ? 0 : ((thisSearch.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) ? 2 : 1));
if (prop.getInt("type", 0) == 1) prop.put("type_mediatype", contentdomString);
prop.put("input_cat", "href");
prop.put("input_depth", "0");
// adding some additional properties needed for the rss feed
String hostName = (String) header.get("Host", "localhost");
if (hostName.indexOf(":") == -1) hostName += ":" + serverCore.getPortNr(env.getConfig("port", "8080"));
prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif");
}
if (post.get("cat", "href").equals("image")) {
int depth = post.getInt("depth", 0);
int columns = post.getInt("columns", 6);
URL url = null;
try {url = new URL(post.get("url", ""));} catch (MalformedURLException e) {}
plasmaSearchImages si = new plasmaSearchImages(sb.snippetCache, 6000, url, depth);
Iterator i = si.entries();
htmlFilterImageEntry ie;
int line = 0;
while (i.hasNext()) {
int col = 0;
for (col = 0; col < columns; col++) {
if (!i.hasNext()) break;
ie = (htmlFilterImageEntry) i.next();
String urls = ie.url().toString();
String name = "";
int p = urls.lastIndexOf('/');
if (p > 0) name = urls.substring(p + 1);
prop.put("type_results_" + line + "_line_" + col + "_url", urls);
prop.put("type_results_" + line + "_line_" + col + "_name", name);
}
prop.put("type_results_" + line + "_line", col);
line++;
}
prop.put("type_results", line);
prop.put("type", 3); // set type of result: image list
prop.put("input_cat", "href");
prop.put("input_depth", depth);
}
// if user is not authenticated, he may not vote for URLs
int linkcount = Integer.parseInt(prop.get("num-results_linkcount", "0"));
for (int i=0; i<linkcount; i++)
prop.put("type_results_" + i + "_authorized", (authenticated) ? 1 : 0);
prop.put("searchagain", (global) ? 1 : 0);
prop.put("input", input);
prop.put("display", display);
prop.put("input_input", input);
prop.put("input_display", display);
prop.putASIS("input_promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("input_former", post.get("search", ""));
prop.put("former", post.get("search", ""));
prop.put("input_count", count);
prop.put("input_resource", (global) ? "global" : "local");
prop.put("input_time", searchtime / 1000);
prop.put("input_urlmaskfilter", urlmask);
prop.put("input_prefermaskfilter", prefermask);
prop.put("input_indexof", (indexof) ? "on" : "off");
prop.put("input_constraint", constraint.exportB64());
prop.put("input_contentdom", contentdomString);
prop.put("input_contentdomCheckText", (contentdomCode == plasmaSearchQuery.CONTENTDOM_TEXT) ? 1 : 0);
prop.put("input_contentdomCheckAudio", (contentdomCode == plasmaSearchQuery.CONTENTDOM_AUDIO) ? 1 : 0);
prop.put("input_contentdomCheckVideo", (contentdomCode == plasmaSearchQuery.CONTENTDOM_VIDEO) ? 1 : 0);
prop.put("input_contentdomCheckImage", (contentdomCode == plasmaSearchQuery.CONTENTDOM_IMAGE) ? 1 : 0);
prop.put("input_contentdomCheckApp", (contentdomCode == plasmaSearchQuery.CONTENTDOM_APP) ? 1 : 0);
prop.put("type_former", post.get("search", "")); //the query-string used to get the snippets
// return rewrite properties
return prop;
}
| public static serverObjects respond(httpHeader header, serverObjects post, serverSwitch env) {
final plasmaSwitchboard sb = (plasmaSwitchboard) env;
boolean searchAllowed = sb.getConfigBool("publicSearchpage", true) || sb.verifyAuthentication(header, false);
boolean authenticated = sb.adminAuthenticated(header) >= 2;
int display = (post == null) ? 0 : post.getInt("display", 0);
if ((display == 1) && (!authenticated)) display = 0;
int input = (post == null) ? 2 : post.getInt("input", 2);
String promoteSearchPageGreeting = env.getConfig("promoteSearchPageGreeting", "");
if (promoteSearchPageGreeting.length() == 0) promoteSearchPageGreeting = "P2P WEB SEARCH";
// case if no values are requested
final String referer = (String) header.get("Referer");
String querystring = (post == null) ? "" : post.get("search", "").trim();
if ((post == null) || (env == null) || (querystring.length() == 0) || (!searchAllowed)) {
// save referrer
// System.out.println("HEADER=" + header.toString());
if (referer != null) {
URL url;
try { url = new URL(referer); } catch (MalformedURLException e) { url = null; }
if ((url != null) && (serverCore.isNotLocal(url))) {
final HashMap referrerprop = new HashMap();
referrerprop.put("count", "1");
referrerprop.put("clientip", header.get("CLIENTIP"));
referrerprop.put("useragent", header.get("User-Agent"));
referrerprop.put("date", (new serverDate()).toShortString(false));
if (sb.facilityDB != null) try { sb.facilityDB.update("backlinks", referer, referrerprop); } catch (IOException e) {}
}
}
// we create empty entries for template strings
final serverObjects prop = new serverObjects();
prop.put("searchagain", 0);
prop.put("input", input);
prop.put("display", display);
prop.put("input_input", input);
prop.put("input_display", display);
prop.putASIS("input_promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("input_former", "");
prop.put("former", "");
prop.put("input_count", 10);
prop.put("input_resource", "global");
prop.put("input_time", 6);
prop.put("input_urlmaskfilter", ".*");
prop.put("input_prefermaskfilter", "");
prop.put("input_indexof", "off");
prop.put("input_constraint", plasmaSearchQuery.catchall_constraint.exportB64());
prop.put("input_cat", "href");
prop.put("input_depth", "0");
prop.put("input_contentdom", "text");
prop.put("input_contentdomCheckText", 1);
prop.put("input_contentdomCheckAudio", 0);
prop.put("input_contentdomCheckVideo", 0);
prop.put("input_contentdomCheckImage", 0);
prop.put("input_contentdomCheckApp", 0);
prop.put("type", 0);
prop.put("type_excluded", 0);
prop.put("type_combine", 0);
prop.put("type_resultbottomline", 0);
prop.put("type_results", "");
prop.put("num-results", (searchAllowed) ? 0 : 6);
return prop;
}
// collect search attributes
int maxDistance = Integer.MAX_VALUE;
if ((querystring.length() > 2) && (querystring.charAt(0) == '"') && (querystring.charAt(querystring.length() - 1) == '"')) {
querystring = querystring.substring(1, querystring.length() - 1).trim();
maxDistance = 1;
}
if (sb.facilityDB != null) try { sb.facilityDB.update("zeitgeist", querystring, post); } catch (Exception e) {}
int count = Integer.parseInt(post.get("count", "10"));
boolean global = (post == null) ? true : post.get("resource", "global").equals("global");
final boolean indexof = post.get("indexof","").equals("on");
final long searchtime = 1000 * Long.parseLong(post.get("time", "10"));
String urlmask = "";
if (post.containsKey("urlmask") && post.get("urlmask").equals("no")) {
urlmask = ".*";
} else {
urlmask = (post.containsKey("urlmaskfilter")) ? (String) post.get("urlmaskfilter") : ".*";
}
String prefermask = post.get("prefermaskfilter", "");
if ((prefermask.length() > 0) && (prefermask.indexOf(".*") < 0)) prefermask = ".*" + prefermask + ".*";
kelondroBitfield constraint = post.containsKey("constraint") ? new kelondroBitfield(4, post.get("constraint", "______")) : plasmaSearchQuery.catchall_constraint;
if (indexof) {
constraint = new kelondroBitfield();
constraint.set(plasmaCondenser.flag_cat_indexof, true);
}
// SEARCH
final boolean indexDistributeGranted = sb.getConfig(plasmaSwitchboard.INDEX_DIST_ALLOW, "true").equals("true");
final boolean indexReceiveGranted = sb.getConfig("allowReceiveIndex", "true").equals("true");
final boolean offline = yacyCore.seedDB.mySeed.isVirgin();
final boolean clustersearch = sb.isRobinsonMode() &&
(sb.getConfig("cluster.mode", "").equals("privatecluster") ||
sb.getConfig("cluster.mode", "").equals("publiccluster"));
if (offline || !indexDistributeGranted || !indexReceiveGranted) { global = false; }
if (clustersearch) global = true; // switches search on, but search target is limited to cluster nodes
// find search domain
int contentdomCode = plasmaSearchQuery.CONTENTDOM_TEXT;
String contentdomString = post.get("contentdom", "text");
if (contentdomString.equals("text")) contentdomCode = plasmaSearchQuery.CONTENTDOM_TEXT;
if (contentdomString.equals("audio")) contentdomCode = plasmaSearchQuery.CONTENTDOM_AUDIO;
if (contentdomString.equals("video")) contentdomCode = plasmaSearchQuery.CONTENTDOM_VIDEO;
if (contentdomString.equals("image")) contentdomCode = plasmaSearchQuery.CONTENTDOM_IMAGE;
if (contentdomString.equals("app")) contentdomCode = plasmaSearchQuery.CONTENTDOM_APP;
// patch until better search profiles are available
if ((contentdomCode != plasmaSearchQuery.CONTENTDOM_TEXT) && (count <= 10)) count = 30;
serverObjects prop = new serverObjects();
if (post.get("cat", "href").equals("href")) {
final TreeSet[] query = plasmaSearchQuery.cleanQuery(querystring); // converts also umlaute
// filter out stopwords
final TreeSet filtered = kelondroMSetTools.joinConstructive(query[0], plasmaSwitchboard.stopwords);
if (filtered.size() > 0) {
kelondroMSetTools.excludeDestructive(query[0], plasmaSwitchboard.stopwords);
}
// if a minus-button was hit, remove a special reference first
if (post.containsKey("deleteref")) {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
// delete the index entry locally
final String delHash = post.get("deleteref", ""); // urlhash
sb.wordIndex.removeWordReferences(query[0], delHash);
// make new news message with negative voting
HashMap map = new HashMap();
map.put("urlhash", delHash);
map.put("vote", "negative");
map.put("refid", "");
yacyCore.newsPool.publishMyNews(yacyNewsRecord.newRecord(yacyNewsPool.CATEGORY_SURFTIPP_VOTE_ADD, map));
}
// if aplus-button was hit, create new voting message
if (post.containsKey("recommendref")) {
if (!sb.verifyAuthentication(header, true)) {
prop.put("AUTHENTICATE", "admin log-in"); // force log-in
return prop;
}
final String recommendHash = post.get("recommendref", ""); // urlhash
indexURLEntry urlentry = sb.wordIndex.loadedURL.load(recommendHash, null);
if (urlentry != null) {
indexURLEntry.Components comp = urlentry.comp();
plasmaParserDocument document;
document = sb.snippetCache.retrieveDocument(comp.url(), true, 5000, true);
if (document != null) {
// create a news message
HashMap map = new HashMap();
map.put("url", comp.url().toNormalform().replace(',', '|'));
map.put("title", comp.title().replace(',', ' '));
map.put("description", ((document == null) ? comp.title() : document.getTitle()).replace(',', ' '));
map.put("author", ((document == null) ? "" : document.getAuthor()));
map.put("tags", ((document == null) ? "" : document.getKeywords(' ')));
yacyCore.newsPool.publishMyNews(yacyNewsRecord.newRecord(yacyNewsPool.CATEGORY_SURFTIPP_ADD, map));
document.close();
}
}
}
// prepare search properties
final boolean yacyonline = ((yacyCore.seedDB != null) && (yacyCore.seedDB.mySeed != null) && (yacyCore.seedDB.mySeed.getPublicAddress() != null));
final boolean samesearch = env.getConfig("last-search", "").equals(querystring + contentdomString);
final boolean globalsearch = (global) && (yacyonline) && (!samesearch);
// do the search
TreeSet queryHashes = plasmaCondenser.words2hashes(query[0]);
plasmaSearchQuery thisSearch = new plasmaSearchQuery(
querystring,
queryHashes,
plasmaCondenser.words2hashes(query[1]),
maxDistance,
prefermask,
contentdomCode,
count,
searchtime,
urlmask,
(clustersearch && globalsearch) ? plasmaSearchQuery.SEARCHDOM_CLUSTERALL :
((globalsearch) ? plasmaSearchQuery.SEARCHDOM_GLOBALDHT : plasmaSearchQuery.SEARCHDOM_LOCAL),
"",
20,
constraint);
plasmaSearchRankingProfile ranking = (sb.getConfig("rankingProfile", "").length() == 0) ? new plasmaSearchRankingProfile(contentdomString) : new plasmaSearchRankingProfile("", crypt.simpleDecode(sb.getConfig("rankingProfile", ""), null));
plasmaSearchTimingProfile localTiming = new plasmaSearchTimingProfile(4 * thisSearch.maximumTime / 10, thisSearch.wantedResults);
plasmaSearchTimingProfile remoteTiming = new plasmaSearchTimingProfile(6 * thisSearch.maximumTime / 10, thisSearch.wantedResults);
plasmaSearchResults results = new plasmaSearchResults();
String wrongregex = null;
try{
results = sb.searchFromLocal(thisSearch, ranking, localTiming, remoteTiming, true, (String) header.get("CLIENTIP"));
}
catch(PatternSyntaxException e){
wrongregex = e.getPattern();
}
//prop=sb.searchFromLocal(thisSearch, ranking, localTiming, remoteTiming, true, (String) header.get("CLIENTIP"));
prop=new serverObjects();
//prop.put("references", 0);
URL wordURL=null;
prop.put("num-results_totalcount", results.getTotalcount());
prop.put("num-results_filteredcount", results.getFilteredcount());
prop.put("num-results_orderedcount", results.getOrderedcount());
prop.put("num-results_linkcount", results.getLinkcount());
prop.put("type_results", 0);
if(results.numResults()!=0){
//we've got results
prop.put("num-results_totalcount", results.getTotalcount());
prop.put("num-results_filteredcount", results.getFilteredcount());
prop.put("num-results_orderedcount", Integer.toString(results.getOrderedcount())); //why toString?
prop.put("num-results_globalresults", results.getGlobalresults());
for(int i=0;i<results.numResults();i++){
plasmaSearchResults.searchResult result=results.getResult(i);
prop.put("type_results_" + i + "_authorized_recommend", (yacyCore.newsPool.getSpecific(yacyNewsPool.OUTGOING_DB, yacyNewsPool.CATEGORY_SURFTIPP_ADD, "url", result.getUrl()) == null) ? 1 : 0);
//prop.put("type_results_" + i + "_authorized_recommend_deletelink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&deleteref=" + result.getUrlhash() + "&urlmaskfilter=.*");
//prop.put("type_results_" + i + "_authorized_recommend_recommendlink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&recommendref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_recommend_deletelink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&deleteref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_recommend_recommendlink", "/yacysearch.html?search=" + results.getFormerSearch() + "&Enter=Search&count=" + results.getQuery().wantedResults + "&order=" + crypt.simpleEncode(results.getRanking().toExternalString()) + "&resource=local&time=3&recommendref=" + result.getUrlhash() + "&urlmaskfilter=.*");
prop.put("type_results_" + i + "_authorized_urlhash", result.getUrlhash());
prop.put("type_results_" + i + "_description", result.getUrlentry().comp().title());
prop.put("type_results_" + i + "_url", result.getUrl());
try{
URL url=new URL(result.getUrl());
int port=url.getPort();
//TODO: parse <link rel="favicon" /> ...
prop.put("type_results_" + i + "_favicon", url.getProtocol() + "://" + url.getHost() + ((port != -1) ? (":" + String.valueOf(port)) : "") + "/favicon.ico");
}catch(MalformedURLException e){}
prop.put("type_results_" + i + "_urlhash", result.getUrlhash());
prop.put("type_results_" + i + "_urlhexhash", yacySeed.b64Hash2hexHash(result.getUrlhash()));
prop.put("type_results_" + i + "_urlname", nxTools.shortenURLString(result.getUrlname(), 120));
prop.put("type_results_" + i + "_date", plasmaSwitchboard.dateString(result.getUrlentry().moddate()));
prop.put("type_results_" + i + "_ybr", plasmaSearchPreOrder.ybr(result.getUrlentry().hash()));
prop.put("type_results_" + i + "_size", Long.toString(result.getUrlentry().size()));
try {
prop.put("type_results_" + i + "_words", URLEncoder.encode(query[0].toString(),"UTF-8"));
} catch (UnsupportedEncodingException e) {}
prop.put("type_results_" + i + "_former", results.getFormerSearch());
prop.put("type_results_" + i + "_rankingprops", result.getUrlentry().word().toPropertyForm() + ", domLengthEstimated=" + plasmaURL.domLengthEstimation(result.getUrlhash()) +
((plasmaURL.probablyRootURL(result.getUrlhash())) ? ", probablyRootURL" : "") +
(((wordURL = plasmaURL.probablyWordURL(result.getUrlhash(), query[0])) != null) ? ", probablyWordURL=" + wordURL.toNormalform() : ""));
// adding snippet if available
if (result.hasSnippet()) {
prop.put("type_results_" + i + "_snippet", 1);
prop.putASIS("type_results_" + i + "_snippet_text", result.getSnippet().getLineMarked(results.getQuery().queryHashes));//FIXME: the ASIS should not be needed, if there is no html in .java
} else {
if (post.containsKey("fetchSnippet")) {
/* fetch the snippet now */
try {
// snippet fetch timeout
int textsnippet_timeout = Integer.parseInt(env.getConfig("timeout_media", "10000"));
// boolean line_end_with_punctuation
boolean pre = post.get("pre", "false").equals("true");
// if 'remove' is set to true, then RWI references to URLs that do not have the snippet are removed
boolean remove = post.get("remove", "false").equals("true");
URL resultURL = new URL(result.getUrl());
plasmaSnippetCache.TextSnippet snippet = sb.snippetCache.retrieveTextSnippet(
resultURL,
queryHashes,
true,
pre,
260,
textsnippet_timeout
);
if (snippet.getErrorCode() < 11) {
// no problems occurred
//prop.put("text", (snippet.exists()) ? snippet.getLineMarked(queryHashes) : "unknown");
prop.putASIS("type_results_" + i + "_snippet_text", (snippet.exists()) ? snippet.getLineMarked(queryHashes) : "unknown");
} else {
// problems with snippet fetch
prop.put("type_results_" + i + "_snippet_text", (remove) ? sb.snippetCache.failConsequences(snippet, queryHashes) : snippet.getError());
}
prop.put("type_results_" + i + "_snippet", 1);
} catch (MalformedURLException e) {
prop.put("type_results_" + i + "_snippet", 0);
prop.put("type_results_" + i + "_snippet_text", "");
}
} else {
/* no snippet available (will be fetched later via ajax) */
prop.put("type_results_" + i + "_snippet", 0);
prop.put("type_results_" + i + "_snippet_text", "");
}
}
prop.put("type_results", results.numResults());
prop.put("references", results.getReferences());
prop.put("num-results_linkcount", Integer.toString(results.numResults()));
}
}
// remember the last search expression
env.setConfig("last-search", querystring + contentdomString);
// process result of search
prop.put("type_resultbottomline", 0);
if (filtered.size() > 0) {
prop.put("excluded", 1);
prop.put("excluded_stopwords", filtered.toString());
} else {
prop.put("excluded", 0);
}
if (prop == null || prop.size() == 0) {
if (post.get("search", "").length() < 3) {
prop.put("num-results", 2); // no results - at least 3 chars
} else {
prop.put("num-results", 1); // no results
}
} else {
final int totalcount = prop.getInt("num-results_totalcount", 0);
if (totalcount >= 10) {
final Object[] references = (Object[]) prop.get( "references", new String[0]);
prop.put("num-results", 5);
int hintcount = references.length;
if (hintcount > 0) {
prop.put("type_combine", 1);
// get the topwords
final TreeSet topwords = new TreeSet(kelondroNaturalOrder.naturalOrder);
String tmp = "";
for (int i = 0; i < hintcount; i++) {
tmp = (String) references[i];
if (tmp.matches("[a-z]+")) {
topwords.add(tmp);
// } else {
// topwords.add("(" + tmp + ")");
}
}
// filter out the badwords
final TreeSet filteredtopwords = kelondroMSetTools.joinConstructive(topwords, plasmaSwitchboard.badwords);
if (filteredtopwords.size() > 0) {
kelondroMSetTools.excludeDestructive(topwords, plasmaSwitchboard.badwords);
}
//avoid stopwords being topwords
if (env.getConfig("filterOutStopwordsFromTopwords", "true").equals("true")) {
if ((plasmaSwitchboard.stopwords != null) && (plasmaSwitchboard.stopwords.size() > 0)) {
kelondroMSetTools.excludeDestructive(topwords, plasmaSwitchboard.stopwords);
}
}
String word;
hintcount = 0;
final Iterator iter = topwords.iterator();
while (iter.hasNext()) {
word = (String) iter.next();
if (word != null) {
prop.put("type_combine_words_" + hintcount + "_word", word);
prop.put("type_combine_words_" + hintcount + "_newsearch", post.get("search", "").replace(' ', '+') + "+" + word);
prop.put("type_combine_words_" + hintcount + "_count", count);
prop.put("type_combine_words_" + hintcount + "_resource", ((global) ? "global" : "local"));
prop.put("type_combine_words_" + hintcount + "_time", (searchtime / 1000));
}
prop.put("type_combine_words", hintcount);
if (hintcount++ > MAX_TOPWORDS) {
break;
}
}
}
} else {
if (wrongregex != null) {
prop.put("num-results_wrong_regex", wrongregex);
prop.put("num-results", 4);
}
else if (totalcount == 0) {
prop.put("num-results", 3); // long
}
else {
prop.put("num-results", 5);
}
}
}
if (wrongregex != null) {
prop.put("type_resultbottomline", 0);
}
else if (yacyonline) {
if (global) {
prop.put("type_resultbottomline", 1);
prop.put("type_resultbottomline_globalresults", prop.get("num-results_globalresults", "0"));
} else {
prop.put("type_resultbottomline", 0);
}
} else {
if (global) {
prop.put("type_resultbottomline", 3);
} else {
prop.put("type_resultbottomline", 0);
}
}
prop.put("type", (thisSearch.contentdom == plasmaSearchQuery.CONTENTDOM_TEXT) ? 0 : ((thisSearch.contentdom == plasmaSearchQuery.CONTENTDOM_IMAGE) ? 2 : 1));
if (prop.getInt("type", 0) == 1) prop.put("type_mediatype", contentdomString);
prop.put("input_cat", "href");
prop.put("input_depth", "0");
// adding some additional properties needed for the rss feed
String hostName = (String) header.get("Host", "localhost");
if (hostName.indexOf(":") == -1) hostName += ":" + serverCore.getPortNr(env.getConfig("port", "8080"));
prop.put("rssYacyImageURL", "http://" + hostName + "/env/grafics/yacy.gif");
}
if (post.get("cat", "href").equals("image")) {
int depth = post.getInt("depth", 0);
int columns = post.getInt("columns", 6);
URL url = null;
try {url = new URL(post.get("url", ""));} catch (MalformedURLException e) {}
plasmaSearchImages si = new plasmaSearchImages(sb.snippetCache, 6000, url, depth);
Iterator i = si.entries();
htmlFilterImageEntry ie;
int line = 0;
while (i.hasNext()) {
int col = 0;
for (col = 0; col < columns; col++) {
if (!i.hasNext()) break;
ie = (htmlFilterImageEntry) i.next();
String urls = ie.url().toString();
String name = "";
int p = urls.lastIndexOf('/');
if (p > 0) name = urls.substring(p + 1);
prop.put("type_results_" + line + "_line_" + col + "_url", urls);
prop.put("type_results_" + line + "_line_" + col + "_name", name);
}
prop.put("type_results_" + line + "_line", col);
line++;
}
prop.put("type_results", line);
prop.put("type", 3); // set type of result: image list
prop.put("input_cat", "href");
prop.put("input_depth", depth);
}
// if user is not authenticated, he may not vote for URLs
int linkcount = Integer.parseInt(prop.get("num-results_linkcount", "0"));
for (int i=0; i<linkcount; i++)
prop.put("type_results_" + i + "_authorized", (authenticated) ? 1 : 0);
prop.put("searchagain", (global) ? 1 : 0);
prop.put("input", input);
prop.put("display", display);
prop.put("input_input", input);
prop.put("input_display", display);
prop.putASIS("input_promoteSearchPageGreeting", promoteSearchPageGreeting);
prop.put("input_former", post.get("search", ""));
prop.put("former", post.get("search", ""));
prop.put("input_count", count);
prop.put("input_resource", (global) ? "global" : "local");
prop.put("input_time", searchtime / 1000);
prop.put("input_urlmaskfilter", urlmask);
prop.put("input_prefermaskfilter", prefermask);
prop.put("input_indexof", (indexof) ? "on" : "off");
prop.put("input_constraint", constraint.exportB64());
prop.put("input_contentdom", contentdomString);
prop.put("input_contentdomCheckText", (contentdomCode == plasmaSearchQuery.CONTENTDOM_TEXT) ? 1 : 0);
prop.put("input_contentdomCheckAudio", (contentdomCode == plasmaSearchQuery.CONTENTDOM_AUDIO) ? 1 : 0);
prop.put("input_contentdomCheckVideo", (contentdomCode == plasmaSearchQuery.CONTENTDOM_VIDEO) ? 1 : 0);
prop.put("input_contentdomCheckImage", (contentdomCode == plasmaSearchQuery.CONTENTDOM_IMAGE) ? 1 : 0);
prop.put("input_contentdomCheckApp", (contentdomCode == plasmaSearchQuery.CONTENTDOM_APP) ? 1 : 0);
prop.put("type_former", post.get("search", "")); //the query-string used to get the snippets
// return rewrite properties
return prop;
}
|
diff --git a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
index 2c9b6cf4..540c0365 100644
--- a/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
+++ b/packages/SystemUI/src/com/android/systemui/statusbar/phone/NotificationPanelView.java
@@ -1,286 +1,295 @@
/*
* Copyright (C) 2012 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.systemui.statusbar.phone;
import android.content.Context;
import android.content.ContentResolver;
import android.content.res.Resources;
import android.graphics.Canvas;
import android.graphics.drawable.Drawable;
import android.provider.Settings;
import android.util.AttributeSet;
import android.util.Slog;
import android.view.MotionEvent;
import android.view.View;
import android.database.ContentObserver;
import android.net.Uri;
import android.os.Handler;
import com.android.systemui.R;
import com.android.systemui.statusbar.GestureRecorder;
public class NotificationPanelView extends PanelView {
private static final float STATUS_BAR_SETTINGS_LEFT_PERCENTAGE = 0.8f;
private static final float STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE = 0.2f;
//Final Variables for Notification Bar Swipe action - Switch between Notifications & Quick Settings
private static final float STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE = 0.05f;
private static final float STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE = 0.025f;
private static final float STATUS_BAR_SWIPE_MOVE_PERCENTAGE = 0.2f;
Drawable mHandleBar;
int mHandleBarHeight;
View mHandleView;
int mFingers;
PhoneStatusBar mStatusBar;
boolean mOkToFlip;
//Variables for Notification Bar Swipe action - Switch between Notifications & Quick Settings
float mGestureStartX;
float mGestureStartY;
float mFlipOffset;
float mSwipeDirection;
boolean mTrackingSwipe;
boolean mSwipeTriggered;
boolean mFastToggleEnabled;
int mFastTogglePos;
ContentObserver mEnableObserver;
ContentObserver mChangeSideObserver;
Handler mHandler = new Handler();
public NotificationPanelView(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setStatusBar(PhoneStatusBar bar) {
mStatusBar = bar;
}
@Override
protected void onFinishInflate() {
super.onFinishInflate();
Resources resources = getContext().getResources();
mHandleBar = resources.getDrawable(R.drawable.status_bar_close);
mHandleBarHeight = resources.getDimensionPixelSize(R.dimen.close_handle_height);
mHandleView = findViewById(R.id.handle);
setContentDescription(resources.getString(
R.string.accessibility_desc_notification_shade));
final ContentResolver resolver = getContext().getContentResolver();
mEnableObserver = new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange) {
mFastToggleEnabled = Settings.System.getBoolean(resolver,
Settings.System.FAST_TOGGLE, false);
}
};
mChangeSideObserver = new ContentObserver(mHandler) {
@Override
public void onChange(boolean selfChange) {
mFastTogglePos = Settings.System.getInt(resolver,
Settings.System.CHOOSE_FASTTOGGLE_SIDE, 1);
}
};
// Initialization
mFastToggleEnabled = Settings.System.getBoolean(resolver,
Settings.System.FAST_TOGGLE, false);
mFastTogglePos = Settings.System.getInt(resolver,
Settings.System.CHOOSE_FASTTOGGLE_SIDE, 1);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.FAST_TOGGLE),
true, mEnableObserver);
resolver.registerContentObserver(
Settings.System.getUriFor(Settings.System.CHOOSE_FASTTOGGLE_SIDE),
true, mChangeSideObserver);
}
@Override
public void fling(float vel, boolean always) {
GestureRecorder gr =
((PhoneStatusBarView) mBar).mBar.getGestureRecorder();
if (gr != null) {
gr.tag(
"fling " + ((vel > 0) ? "open" : "closed"),
"notifications,v=" + vel);
}
super.fling(vel, always);
}
// We draw the handle ourselves so that it's
// always glued to the bottom of the window.
@Override
protected void onLayout(boolean changed, int left, int top, int right, int bottom) {
super.onLayout(changed, left, top, right, bottom);
if (changed) {
final int pl = getPaddingLeft();
final int pr = getPaddingRight();
mHandleBar.setBounds(pl, 0, getWidth() - pr, (int) mHandleBarHeight);
}
}
@Override
public void draw(Canvas canvas) {
super.draw(canvas);
final int off = (int) (getHeight() - mHandleBarHeight - getPaddingBottom());
canvas.translate(0, off);
mHandleBar.setState(mHandleView.getDrawableState());
mHandleBar.draw(canvas);
canvas.translate(0, -off);
}
@Override
public boolean onTouchEvent(MotionEvent event) {
boolean shouldRecycleEvent = false;
if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT
&& mStatusBar.mHasFlipSettings) {
- boolean shouldFlip = false;
+ boolean flip = false;
boolean swipeFlipJustFinished = false;
boolean swipeFlipJustStarted = false;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mGestureStartX = event.getX(0);
mGestureStartY = event.getY(0);
mTrackingSwipe = isFullyExpanded() &&
// Pointer is at the handle portion of the view?
mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom();
mOkToFlip = getExpandedHeight() == 0;
+ if (event.getX(0) > getWidth() * (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE) &&
+ Settings.System.getInt(getContext().getContentResolver(),
+ Settings.System.QS_QUICK_PULLDOWN, 0) == 1) {
+ flip = true;
+ } else if (event.getX(0) < getWidth() * (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE) &&
+ Settings.System.getInt(getContext().getContentResolver(),
+ Settings.System.QS_QUICK_PULLDOWN, 0) == 2) {
+ flip = true;
+ }
if (mFastTogglePos == 1) {
if ((event.getX(0) > getWidth()
* (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE)
&& mFastToggleEnabled)
&& !mFastToggleEnabled) {
- shouldFlip = true;
+ flip = true;
}
} else if (mFastTogglePos == 2) {
if ((event.getX(0) < getWidth()
* (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE)
&& mFastToggleEnabled)
&& !mFastToggleEnabled) {
- shouldFlip = true;
+ flip = true;
}
}
break;
case MotionEvent.ACTION_MOVE:
final float deltaX = Math.abs(event.getX(0) - mGestureStartX);
final float deltaY = Math.abs(event.getY(0) - mGestureStartY);
final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE;
final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE;
if (mTrackingSwipe && deltaY > maxDeltaY) {
mTrackingSwipe = false;
}
if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) {
// The value below can be used to adjust deltaX to always increase,
// if the user keeps swiping in the same direction as she started the
// gesture. If she, however, moves her finger the other way, deltaX will
// decrease.
//
// This allows for an horizontal swipe, in any direction, to always flip
// the views.
mSwipeDirection = event.getX(0) < mGestureStartX ? -1f : 1f;
if (mStatusBar.isShowingSettings()) {
mFlipOffset = 1f;
// in this case, however, we need deltaX to decrease
mSwipeDirection = -mSwipeDirection;
} else {
mFlipOffset = -1f;
}
mGestureStartX = event.getX(0);
mTrackingSwipe = false;
mSwipeTriggered = true;
swipeFlipJustStarted = true;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
- shouldFlip = true;
+ flip = true;
break;
case MotionEvent.ACTION_UP:
swipeFlipJustFinished = mSwipeTriggered;
mSwipeTriggered = false;
mTrackingSwipe = false;
break;
}
- if(mOkToFlip && shouldFlip) {
+ if (mOkToFlip && flip) {
float miny = event.getY(0);
float maxy = miny;
for (int i=1; i<event.getPointerCount(); i++) {
final float y = event.getY(i);
if (y < miny) miny = y;
if (y > maxy) maxy = y;
}
if (maxy - miny < mHandleBarHeight) {
if (getMeasuredHeight() < mHandleBarHeight) {
mStatusBar.switchToSettings();
} else {
// Do not flip if the drag event started within the top bar
if (MotionEvent.ACTION_DOWN == event.getActionMasked() && event.getY(0) < mHandleBarHeight ) {
mStatusBar.switchToSettings();
} else {
mStatusBar.flipToSettings();
}
}
mOkToFlip = false;
}
} else if (mSwipeTriggered) {
final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection;
mStatusBar.partialFlip(mFlipOffset +
deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE));
if (!swipeFlipJustStarted) {
return true; // Consume the event.
}
} else if (swipeFlipJustFinished) {
mStatusBar.completePartialFlip();
}
if (swipeFlipJustStarted || swipeFlipJustFinished) {
// Made up event: finger at the middle bottom of the view.
MotionEvent original = event;
event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(),
original.getAction(), getWidth()/2, getHeight(),
original.getPressure(0), original.getSize(0), original.getMetaState(),
original.getXPrecision(), original.getYPrecision(), original.getDeviceId(),
original.getEdgeFlags());
// The following two lines looks better than the chunk of code above, but,
// nevertheless, doesn't work. The view is not pinned down, and may close,
// just after the gesture is finished.
//
// event = MotionEvent.obtainNoHistory(original);
// event.setLocation(getWidth()/2, getHeight());
shouldRecycleEvent = true;
}
}
final boolean result = mHandleView.dispatchTouchEvent(event);
if (shouldRecycleEvent) {
event.recycle();
}
return result;
}
}
| false | true | public boolean onTouchEvent(MotionEvent event) {
boolean shouldRecycleEvent = false;
if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT
&& mStatusBar.mHasFlipSettings) {
boolean shouldFlip = false;
boolean swipeFlipJustFinished = false;
boolean swipeFlipJustStarted = false;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mGestureStartX = event.getX(0);
mGestureStartY = event.getY(0);
mTrackingSwipe = isFullyExpanded() &&
// Pointer is at the handle portion of the view?
mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom();
mOkToFlip = getExpandedHeight() == 0;
if (mFastTogglePos == 1) {
if ((event.getX(0) > getWidth()
* (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE)
&& mFastToggleEnabled)
&& !mFastToggleEnabled) {
shouldFlip = true;
}
} else if (mFastTogglePos == 2) {
if ((event.getX(0) < getWidth()
* (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE)
&& mFastToggleEnabled)
&& !mFastToggleEnabled) {
shouldFlip = true;
}
}
break;
case MotionEvent.ACTION_MOVE:
final float deltaX = Math.abs(event.getX(0) - mGestureStartX);
final float deltaY = Math.abs(event.getY(0) - mGestureStartY);
final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE;
final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE;
if (mTrackingSwipe && deltaY > maxDeltaY) {
mTrackingSwipe = false;
}
if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) {
// The value below can be used to adjust deltaX to always increase,
// if the user keeps swiping in the same direction as she started the
// gesture. If she, however, moves her finger the other way, deltaX will
// decrease.
//
// This allows for an horizontal swipe, in any direction, to always flip
// the views.
mSwipeDirection = event.getX(0) < mGestureStartX ? -1f : 1f;
if (mStatusBar.isShowingSettings()) {
mFlipOffset = 1f;
// in this case, however, we need deltaX to decrease
mSwipeDirection = -mSwipeDirection;
} else {
mFlipOffset = -1f;
}
mGestureStartX = event.getX(0);
mTrackingSwipe = false;
mSwipeTriggered = true;
swipeFlipJustStarted = true;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
shouldFlip = true;
break;
case MotionEvent.ACTION_UP:
swipeFlipJustFinished = mSwipeTriggered;
mSwipeTriggered = false;
mTrackingSwipe = false;
break;
}
if(mOkToFlip && shouldFlip) {
float miny = event.getY(0);
float maxy = miny;
for (int i=1; i<event.getPointerCount(); i++) {
final float y = event.getY(i);
if (y < miny) miny = y;
if (y > maxy) maxy = y;
}
if (maxy - miny < mHandleBarHeight) {
if (getMeasuredHeight() < mHandleBarHeight) {
mStatusBar.switchToSettings();
} else {
// Do not flip if the drag event started within the top bar
if (MotionEvent.ACTION_DOWN == event.getActionMasked() && event.getY(0) < mHandleBarHeight ) {
mStatusBar.switchToSettings();
} else {
mStatusBar.flipToSettings();
}
}
mOkToFlip = false;
}
} else if (mSwipeTriggered) {
final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection;
mStatusBar.partialFlip(mFlipOffset +
deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE));
if (!swipeFlipJustStarted) {
return true; // Consume the event.
}
} else if (swipeFlipJustFinished) {
mStatusBar.completePartialFlip();
}
if (swipeFlipJustStarted || swipeFlipJustFinished) {
// Made up event: finger at the middle bottom of the view.
MotionEvent original = event;
event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(),
original.getAction(), getWidth()/2, getHeight(),
original.getPressure(0), original.getSize(0), original.getMetaState(),
original.getXPrecision(), original.getYPrecision(), original.getDeviceId(),
original.getEdgeFlags());
// The following two lines looks better than the chunk of code above, but,
// nevertheless, doesn't work. The view is not pinned down, and may close,
// just after the gesture is finished.
//
// event = MotionEvent.obtainNoHistory(original);
// event.setLocation(getWidth()/2, getHeight());
shouldRecycleEvent = true;
}
}
final boolean result = mHandleView.dispatchTouchEvent(event);
if (shouldRecycleEvent) {
event.recycle();
}
return result;
}
| public boolean onTouchEvent(MotionEvent event) {
boolean shouldRecycleEvent = false;
if (PhoneStatusBar.SETTINGS_DRAG_SHORTCUT
&& mStatusBar.mHasFlipSettings) {
boolean flip = false;
boolean swipeFlipJustFinished = false;
boolean swipeFlipJustStarted = false;
switch (event.getActionMasked()) {
case MotionEvent.ACTION_DOWN:
mGestureStartX = event.getX(0);
mGestureStartY = event.getY(0);
mTrackingSwipe = isFullyExpanded() &&
// Pointer is at the handle portion of the view?
mGestureStartY > getHeight() - mHandleBarHeight - getPaddingBottom();
mOkToFlip = getExpandedHeight() == 0;
if (event.getX(0) > getWidth() * (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE) &&
Settings.System.getInt(getContext().getContentResolver(),
Settings.System.QS_QUICK_PULLDOWN, 0) == 1) {
flip = true;
} else if (event.getX(0) < getWidth() * (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE) &&
Settings.System.getInt(getContext().getContentResolver(),
Settings.System.QS_QUICK_PULLDOWN, 0) == 2) {
flip = true;
}
if (mFastTogglePos == 1) {
if ((event.getX(0) > getWidth()
* (1.0f - STATUS_BAR_SETTINGS_RIGHT_PERCENTAGE)
&& mFastToggleEnabled)
&& !mFastToggleEnabled) {
flip = true;
}
} else if (mFastTogglePos == 2) {
if ((event.getX(0) < getWidth()
* (1.0f - STATUS_BAR_SETTINGS_LEFT_PERCENTAGE)
&& mFastToggleEnabled)
&& !mFastToggleEnabled) {
flip = true;
}
}
break;
case MotionEvent.ACTION_MOVE:
final float deltaX = Math.abs(event.getX(0) - mGestureStartX);
final float deltaY = Math.abs(event.getY(0) - mGestureStartY);
final float maxDeltaY = getHeight() * STATUS_BAR_SWIPE_VERTICAL_MAX_PERCENTAGE;
final float minDeltaX = getWidth() * STATUS_BAR_SWIPE_TRIGGER_PERCENTAGE;
if (mTrackingSwipe && deltaY > maxDeltaY) {
mTrackingSwipe = false;
}
if (mTrackingSwipe && deltaX > deltaY && deltaX > minDeltaX) {
// The value below can be used to adjust deltaX to always increase,
// if the user keeps swiping in the same direction as she started the
// gesture. If she, however, moves her finger the other way, deltaX will
// decrease.
//
// This allows for an horizontal swipe, in any direction, to always flip
// the views.
mSwipeDirection = event.getX(0) < mGestureStartX ? -1f : 1f;
if (mStatusBar.isShowingSettings()) {
mFlipOffset = 1f;
// in this case, however, we need deltaX to decrease
mSwipeDirection = -mSwipeDirection;
} else {
mFlipOffset = -1f;
}
mGestureStartX = event.getX(0);
mTrackingSwipe = false;
mSwipeTriggered = true;
swipeFlipJustStarted = true;
}
break;
case MotionEvent.ACTION_POINTER_DOWN:
flip = true;
break;
case MotionEvent.ACTION_UP:
swipeFlipJustFinished = mSwipeTriggered;
mSwipeTriggered = false;
mTrackingSwipe = false;
break;
}
if (mOkToFlip && flip) {
float miny = event.getY(0);
float maxy = miny;
for (int i=1; i<event.getPointerCount(); i++) {
final float y = event.getY(i);
if (y < miny) miny = y;
if (y > maxy) maxy = y;
}
if (maxy - miny < mHandleBarHeight) {
if (getMeasuredHeight() < mHandleBarHeight) {
mStatusBar.switchToSettings();
} else {
// Do not flip if the drag event started within the top bar
if (MotionEvent.ACTION_DOWN == event.getActionMasked() && event.getY(0) < mHandleBarHeight ) {
mStatusBar.switchToSettings();
} else {
mStatusBar.flipToSettings();
}
}
mOkToFlip = false;
}
} else if (mSwipeTriggered) {
final float deltaX = (event.getX(0) - mGestureStartX) * mSwipeDirection;
mStatusBar.partialFlip(mFlipOffset +
deltaX / (getWidth() * STATUS_BAR_SWIPE_MOVE_PERCENTAGE));
if (!swipeFlipJustStarted) {
return true; // Consume the event.
}
} else if (swipeFlipJustFinished) {
mStatusBar.completePartialFlip();
}
if (swipeFlipJustStarted || swipeFlipJustFinished) {
// Made up event: finger at the middle bottom of the view.
MotionEvent original = event;
event = MotionEvent.obtain(original.getDownTime(), original.getEventTime(),
original.getAction(), getWidth()/2, getHeight(),
original.getPressure(0), original.getSize(0), original.getMetaState(),
original.getXPrecision(), original.getYPrecision(), original.getDeviceId(),
original.getEdgeFlags());
// The following two lines looks better than the chunk of code above, but,
// nevertheless, doesn't work. The view is not pinned down, and may close,
// just after the gesture is finished.
//
// event = MotionEvent.obtainNoHistory(original);
// event.setLocation(getWidth()/2, getHeight());
shouldRecycleEvent = true;
}
}
final boolean result = mHandleView.dispatchTouchEvent(event);
if (shouldRecycleEvent) {
event.recycle();
}
return result;
}
|
diff --git a/codegenerator/src/main/java/org/jboss/jca/codegenerator/xml/IronjacamarXmlGen.java b/codegenerator/src/main/java/org/jboss/jca/codegenerator/xml/IronjacamarXmlGen.java
index 8fbd4aa48..02aeedd00 100644
--- a/codegenerator/src/main/java/org/jboss/jca/codegenerator/xml/IronjacamarXmlGen.java
+++ b/codegenerator/src/main/java/org/jboss/jca/codegenerator/xml/IronjacamarXmlGen.java
@@ -1,157 +1,157 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2010, Red Hat Middleware LLC, and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.jca.codegenerator.xml;
import org.jboss.jca.codegenerator.ConfigPropType;
import org.jboss.jca.codegenerator.Definition;
import org.jboss.jca.codegenerator.SimpleTemplate;
import org.jboss.jca.codegenerator.Template;
import org.jboss.jca.codegenerator.Utils;
import java.io.IOException;
import java.io.Writer;
import java.net.URL;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* A IvyXmlGen.
*
* @author Jeff Zhang
* @version $Revision: $
*/
public class IronjacamarXmlGen extends AbstractXmlGen
{
@Override
public void writeXmlBody(Definition def, Writer out) throws IOException
{
out.write("<!--");
writeEol(out);
writeheader(def, out);
out.write("-->");
writeEol(out);
writeEol(out);
URL buildFile = IronjacamarXmlGen.class.getResource("/ironjacamar.xml.template");
String buildString = Utils.readFileIntoString(buildFile);
StringBuilder strRaProps = new StringBuilder();
List<ConfigPropType> raPropsList = def.getRaConfigProps();
if (def.isUseRa())
getPropsString(strRaProps, raPropsList, 2);
StringBuilder strMcf = new StringBuilder();
strMcf.append(" <connection-definitions>\n");
for (int num = 0; num < def.getMcfDefs().size(); num++)
{
strMcf.append(" <connection-definition class-name=\"");
strMcf.append(def.getRaPackage());
strMcf.append(".");
strMcf.append(def.getMcfDefs().get(num).getMcfClass());
strMcf.append("\" ");
if (def.getMcfDefs().get(num).isUseCciConnection())
{
strMcf.append("jndi-name=\"java:/eis/");
strMcf.append(def.getMcfDefs().get(num).getCciConnFactoryClass());
strMcf.append("\" ");
strMcf.append("pool-name=\"" + def.getMcfDefs().get(num).getCciConnFactoryClass());
}
else
{
strMcf.append("jndi-name=\"java:/eis/");
strMcf.append(def.getMcfDefs().get(num).getCfInterfaceClass());
strMcf.append("\" ");
strMcf.append("pool-name=\"" + def.getMcfDefs().get(num).getCfInterfaceClass());
}
strMcf.append("\">\n");
StringBuilder strMcfProps = new StringBuilder();
List<ConfigPropType> mcfPropsList = def.getMcfDefs().get(num).getMcfConfigProps();
getPropsString(strMcfProps, mcfPropsList, 6);
strMcf.append(strMcfProps.toString());
if (def.getSupportTransaction().endsWith("XATransaction"))
{
- strMcf.append(" <recover>\n");
+ strMcf.append(" <recovery>\n");
strMcf.append(" <recover-credential>\n");
strMcf.append(" <user-name>user</user-name>\n");
strMcf.append(" <password>password</password>\n");
strMcf.append(" </recover-credential>\n");
- strMcf.append(" </recover> )\n");
+ strMcf.append(" </recovery>\n");
}
strMcf.append(" </connection-definition>\n");
}
strMcf.append(" </connection-definitions>\n");
StringBuilder strAo = new StringBuilder();
if (def.isGenAdminObject())
{
strAo.append(" <admin-objects>\n");
for (int i = 0; i < def.getAdminObjects().size(); i++)
{
strAo.append(" <admin-object class-name=\"");
strAo.append(def.getRaPackage());
strAo.append(".");
strAo.append(def.getAdminObjects().get(i).getAdminObjectClass());
strAo.append("\" jndi-name=\"java:/eis/ao/");
strAo.append(def.getAdminObjects().get(i).getAdminObjectInterface());
strAo.append("\">\n");
getPropsString(strAo, def.getAdminObjects().get(i).getAoConfigProps(), 6);
strAo.append(" </admin-object>\n");
}
strAo.append(" </admin-objects>\n");
}
Map<String, String> map = new HashMap<String, String>();
map.put("ra.props", strRaProps.toString());
map.put("transaction", def.getSupportTransaction());
map.put("mcfs", strMcf.toString());
map.put("adminobjects", strAo.toString());
Template template = new SimpleTemplate(buildString);
template.process(map, out);
}
/**
* generate properties String
*
* @param strProps
* @param propsList
* @param indent
*/
private void getPropsString(StringBuilder strProps, List<ConfigPropType> propsList, int indent)
{
for (ConfigPropType props : propsList)
{
for (int i = 0; i < indent; i++)
strProps.append(" ");
strProps.append("<config-property name=\"");
strProps.append(props.getName());
strProps.append("\">");
strProps.append(props.getValue());
strProps.append("</config-property>");
strProps.append("\n");
}
}
}
| false | true | public void writeXmlBody(Definition def, Writer out) throws IOException
{
out.write("<!--");
writeEol(out);
writeheader(def, out);
out.write("-->");
writeEol(out);
writeEol(out);
URL buildFile = IronjacamarXmlGen.class.getResource("/ironjacamar.xml.template");
String buildString = Utils.readFileIntoString(buildFile);
StringBuilder strRaProps = new StringBuilder();
List<ConfigPropType> raPropsList = def.getRaConfigProps();
if (def.isUseRa())
getPropsString(strRaProps, raPropsList, 2);
StringBuilder strMcf = new StringBuilder();
strMcf.append(" <connection-definitions>\n");
for (int num = 0; num < def.getMcfDefs().size(); num++)
{
strMcf.append(" <connection-definition class-name=\"");
strMcf.append(def.getRaPackage());
strMcf.append(".");
strMcf.append(def.getMcfDefs().get(num).getMcfClass());
strMcf.append("\" ");
if (def.getMcfDefs().get(num).isUseCciConnection())
{
strMcf.append("jndi-name=\"java:/eis/");
strMcf.append(def.getMcfDefs().get(num).getCciConnFactoryClass());
strMcf.append("\" ");
strMcf.append("pool-name=\"" + def.getMcfDefs().get(num).getCciConnFactoryClass());
}
else
{
strMcf.append("jndi-name=\"java:/eis/");
strMcf.append(def.getMcfDefs().get(num).getCfInterfaceClass());
strMcf.append("\" ");
strMcf.append("pool-name=\"" + def.getMcfDefs().get(num).getCfInterfaceClass());
}
strMcf.append("\">\n");
StringBuilder strMcfProps = new StringBuilder();
List<ConfigPropType> mcfPropsList = def.getMcfDefs().get(num).getMcfConfigProps();
getPropsString(strMcfProps, mcfPropsList, 6);
strMcf.append(strMcfProps.toString());
if (def.getSupportTransaction().endsWith("XATransaction"))
{
strMcf.append(" <recover>\n");
strMcf.append(" <recover-credential>\n");
strMcf.append(" <user-name>user</user-name>\n");
strMcf.append(" <password>password</password>\n");
strMcf.append(" </recover-credential>\n");
strMcf.append(" </recover> )\n");
}
strMcf.append(" </connection-definition>\n");
}
strMcf.append(" </connection-definitions>\n");
StringBuilder strAo = new StringBuilder();
if (def.isGenAdminObject())
{
strAo.append(" <admin-objects>\n");
for (int i = 0; i < def.getAdminObjects().size(); i++)
{
strAo.append(" <admin-object class-name=\"");
strAo.append(def.getRaPackage());
strAo.append(".");
strAo.append(def.getAdminObjects().get(i).getAdminObjectClass());
strAo.append("\" jndi-name=\"java:/eis/ao/");
strAo.append(def.getAdminObjects().get(i).getAdminObjectInterface());
strAo.append("\">\n");
getPropsString(strAo, def.getAdminObjects().get(i).getAoConfigProps(), 6);
strAo.append(" </admin-object>\n");
}
strAo.append(" </admin-objects>\n");
}
Map<String, String> map = new HashMap<String, String>();
map.put("ra.props", strRaProps.toString());
map.put("transaction", def.getSupportTransaction());
map.put("mcfs", strMcf.toString());
map.put("adminobjects", strAo.toString());
Template template = new SimpleTemplate(buildString);
template.process(map, out);
}
| public void writeXmlBody(Definition def, Writer out) throws IOException
{
out.write("<!--");
writeEol(out);
writeheader(def, out);
out.write("-->");
writeEol(out);
writeEol(out);
URL buildFile = IronjacamarXmlGen.class.getResource("/ironjacamar.xml.template");
String buildString = Utils.readFileIntoString(buildFile);
StringBuilder strRaProps = new StringBuilder();
List<ConfigPropType> raPropsList = def.getRaConfigProps();
if (def.isUseRa())
getPropsString(strRaProps, raPropsList, 2);
StringBuilder strMcf = new StringBuilder();
strMcf.append(" <connection-definitions>\n");
for (int num = 0; num < def.getMcfDefs().size(); num++)
{
strMcf.append(" <connection-definition class-name=\"");
strMcf.append(def.getRaPackage());
strMcf.append(".");
strMcf.append(def.getMcfDefs().get(num).getMcfClass());
strMcf.append("\" ");
if (def.getMcfDefs().get(num).isUseCciConnection())
{
strMcf.append("jndi-name=\"java:/eis/");
strMcf.append(def.getMcfDefs().get(num).getCciConnFactoryClass());
strMcf.append("\" ");
strMcf.append("pool-name=\"" + def.getMcfDefs().get(num).getCciConnFactoryClass());
}
else
{
strMcf.append("jndi-name=\"java:/eis/");
strMcf.append(def.getMcfDefs().get(num).getCfInterfaceClass());
strMcf.append("\" ");
strMcf.append("pool-name=\"" + def.getMcfDefs().get(num).getCfInterfaceClass());
}
strMcf.append("\">\n");
StringBuilder strMcfProps = new StringBuilder();
List<ConfigPropType> mcfPropsList = def.getMcfDefs().get(num).getMcfConfigProps();
getPropsString(strMcfProps, mcfPropsList, 6);
strMcf.append(strMcfProps.toString());
if (def.getSupportTransaction().endsWith("XATransaction"))
{
strMcf.append(" <recovery>\n");
strMcf.append(" <recover-credential>\n");
strMcf.append(" <user-name>user</user-name>\n");
strMcf.append(" <password>password</password>\n");
strMcf.append(" </recover-credential>\n");
strMcf.append(" </recovery>\n");
}
strMcf.append(" </connection-definition>\n");
}
strMcf.append(" </connection-definitions>\n");
StringBuilder strAo = new StringBuilder();
if (def.isGenAdminObject())
{
strAo.append(" <admin-objects>\n");
for (int i = 0; i < def.getAdminObjects().size(); i++)
{
strAo.append(" <admin-object class-name=\"");
strAo.append(def.getRaPackage());
strAo.append(".");
strAo.append(def.getAdminObjects().get(i).getAdminObjectClass());
strAo.append("\" jndi-name=\"java:/eis/ao/");
strAo.append(def.getAdminObjects().get(i).getAdminObjectInterface());
strAo.append("\">\n");
getPropsString(strAo, def.getAdminObjects().get(i).getAoConfigProps(), 6);
strAo.append(" </admin-object>\n");
}
strAo.append(" </admin-objects>\n");
}
Map<String, String> map = new HashMap<String, String>();
map.put("ra.props", strRaProps.toString());
map.put("transaction", def.getSupportTransaction());
map.put("mcfs", strMcf.toString());
map.put("adminobjects", strAo.toString());
Template template = new SimpleTemplate(buildString);
template.process(map, out);
}
|
diff --git a/src/org/es/butler/MainActivity.java b/src/org/es/butler/MainActivity.java
index 991012e..90ae1de 100644
--- a/src/org/es/butler/MainActivity.java
+++ b/src/org/es/butler/MainActivity.java
@@ -1,204 +1,204 @@
package org.es.butler;
import android.app.Activity;
import android.os.Bundle;
import android.speech.tts.TextToSpeech;
import android.speech.tts.TextToSpeech.OnInitListener;
import android.text.format.Time;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import org.es.api.AgendaApi;
import org.es.api.WeatherApi;
import org.es.api.factory.AgendaApiFactory;
import org.es.api.factory.WeatherApiFactory;
import org.es.butler.logic.impl.AgendaLogic;
import org.es.butler.logic.impl.TimeLogic;
import org.es.butler.logic.impl.WeatherLogic;
import org.es.butler.pojo.AgendaEvent;
import org.es.butler.pojo.WeatherData;
import java.util.List;
import java.util.Locale;
/**
* Created by Cyril Leroux on 17/06/13.
*/
public class MainActivity extends Activity implements OnInitListener, OnClickListener {
private static final String TAG = "ButlerActivity";
private TextToSpeech mTTS;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mTTS = new TextToSpeech(getApplicationContext(), this);
((Button) findViewById(R.id.btn_daily_speech)).setOnClickListener(this);
}
@Override
protected void onDestroy() {
if (mTTS != null) {
mTTS.stop();
mTTS.shutdown();
mTTS = null;
}
super.onDestroy();
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
@Override
public void onInit(int status) {
if (status != TextToSpeech.SUCCESS) {
Log.e(TAG, "TTS initialization failed");
return;
}
int result = TextToSpeech.LANG_MISSING_DATA;
if (mTTS.isLanguageAvailable(Locale.UK) == TextToSpeech.LANG_AVAILABLE) {
result = mTTS.setLanguage(Locale.UK);
} else {
result = mTTS.setLanguage(Locale.US);
}
if (result == TextToSpeech.LANG_MISSING_DATA || result == TextToSpeech.LANG_NOT_SUPPORTED) {
Log.e(TAG, "This Language is not supported");
}
}
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.btn_daily_speech:
dailySpeech(true);
break;
default:
break;
}
}
/**
* Say the daily speech
*
* @param force Forces the speech even if the {@link #cancelDailySpeech()} trigger returns true.
*/
private void dailySpeech(boolean force) {
if (cancelDailySpeech() && !force) {
return;
}
WeatherApi weatherApi = WeatherApiFactory.getWeatherAPI();
WeatherData weatherData = weatherApi.checkWeather();
AgendaApi agendaApi = AgendaApiFactory.getAgendaApi();
- List<AgendaEvent> todayEvents = agendaApi.checkTodayEvents();
- List<AgendaEvent> upcomingEvents = agendaApi.checkUpcomingEvent();
+ List<AgendaEvent> todayEvents = agendaApi.checkTodayEvents(getApplicationContext());
+ List<AgendaEvent> upcomingEvents = agendaApi.checkUpcomingEvent(getApplicationContext());
Time now = new Time();
now.setToNow();
TimeLogic time = new TimeLogic(now);
sayHello(time);
sayTime(time);
WeatherLogic weather = new WeatherLogic(weatherData);
sayWeather(weather);
AgendaLogic agendaLogicToday = new AgendaLogic(todayEvents);
AgendaLogic agendaLogicUpcoming = new AgendaLogic(upcomingEvents);
sayTodayEvents(agendaLogicToday);
sayUpcomingEvents(agendaLogicUpcoming);
}
private boolean cancelDailySpeech() {
// TODO implement the conditions to cancel daily speech
return false;
}
/**
* Say hello out loud.
* The spoken text depends on the time of day.
*
* @param time The time defining the spoken text.
*/
private void sayHello(final TimeLogic time) {
String text = null;
if (time.isMorning()) {
text = getString(R.string.good_morning);
} else if (time.isAfternoon()) {
text = getString(R.string.good_afternoon);
} else if (time.isEvening()) {
text = getString(R.string.good_evening);
} else if (time.isNight()) {
text = getString(R.string.good_night);
} else {
Log.e(TAG, "Unexpected Time value : " + time.getTime().format("HH:mm:ss"));
}
mTTS.speak(text, TextToSpeech.QUEUE_FLUSH, null);
}
/**
* Say the time out loud.
*
* @param time the time to speak out loud.
*/
private void sayTime(final TimeLogic time) {
mTTS.setSpeechRate(0.9f);
final String text = time.getPronunciation(getApplicationContext());
if (text == null || text.isEmpty()) {
Log.e(TAG, "sayTime(), couldn't get pronunciation.");
}
mTTS.speak(text, TextToSpeech.QUEUE_ADD, null);
mTTS.setSpeechRate(1f);
}
private void sayWeather(final WeatherLogic weather) {
final String text = weather.getPronunciation(getApplicationContext());
if (text == null || text.isEmpty()) {
Log.e(TAG, "sayWeather(), couldn't get pronunciation.");
}
mTTS.speak(text, TextToSpeech.QUEUE_ADD, null);
}
private void sayTodayEvents(final AgendaLogic logic) {
final String text = logic.getPronunciation(getApplicationContext());
if (text == null || text.isEmpty()) {
Log.e(TAG, "sayTodayEvents(), couldn't get pronunciation.");
}
mTTS.speak(text, TextToSpeech.QUEUE_ADD, null);
}
private void sayUpcomingEvents(final AgendaLogic logic) {
final String text = logic.getPronunciation(getApplicationContext());
if (text == null || text.isEmpty()) {
Log.e(TAG, "sayUpcomingEvents(), couldn't get pronunciation.");
}
mTTS.speak(text, TextToSpeech.QUEUE_ADD, null);
}
}
| true | true | private void dailySpeech(boolean force) {
if (cancelDailySpeech() && !force) {
return;
}
WeatherApi weatherApi = WeatherApiFactory.getWeatherAPI();
WeatherData weatherData = weatherApi.checkWeather();
AgendaApi agendaApi = AgendaApiFactory.getAgendaApi();
List<AgendaEvent> todayEvents = agendaApi.checkTodayEvents();
List<AgendaEvent> upcomingEvents = agendaApi.checkUpcomingEvent();
Time now = new Time();
now.setToNow();
TimeLogic time = new TimeLogic(now);
sayHello(time);
sayTime(time);
WeatherLogic weather = new WeatherLogic(weatherData);
sayWeather(weather);
AgendaLogic agendaLogicToday = new AgendaLogic(todayEvents);
AgendaLogic agendaLogicUpcoming = new AgendaLogic(upcomingEvents);
sayTodayEvents(agendaLogicToday);
sayUpcomingEvents(agendaLogicUpcoming);
}
| private void dailySpeech(boolean force) {
if (cancelDailySpeech() && !force) {
return;
}
WeatherApi weatherApi = WeatherApiFactory.getWeatherAPI();
WeatherData weatherData = weatherApi.checkWeather();
AgendaApi agendaApi = AgendaApiFactory.getAgendaApi();
List<AgendaEvent> todayEvents = agendaApi.checkTodayEvents(getApplicationContext());
List<AgendaEvent> upcomingEvents = agendaApi.checkUpcomingEvent(getApplicationContext());
Time now = new Time();
now.setToNow();
TimeLogic time = new TimeLogic(now);
sayHello(time);
sayTime(time);
WeatherLogic weather = new WeatherLogic(weatherData);
sayWeather(weather);
AgendaLogic agendaLogicToday = new AgendaLogic(todayEvents);
AgendaLogic agendaLogicUpcoming = new AgendaLogic(upcomingEvents);
sayTodayEvents(agendaLogicToday);
sayUpcomingEvents(agendaLogicUpcoming);
}
|
diff --git a/src/main/java/com/j256/simplejmx/common/ObjectNameUtil.java b/src/main/java/com/j256/simplejmx/common/ObjectNameUtil.java
index bfd7a36..966d2c9 100644
--- a/src/main/java/com/j256/simplejmx/common/ObjectNameUtil.java
+++ b/src/main/java/com/j256/simplejmx/common/ObjectNameUtil.java
@@ -1,209 +1,211 @@
package com.j256.simplejmx.common;
import javax.management.ObjectName;
/**
* Utility class that creates {@link ObjectName} objects from various arguments.
*
* @author graywatson
*/
public class ObjectNameUtil {
private ObjectNameUtil() {
// only for static methods
}
/**
* Constructs an object-name from a jmx-resource and a self naming object.
*
* @param jmxResource
* Annotation from the class for which we are creating our ObjectName. It may be null.
* @param selfNamingObj
* Object that implements the self-naming interface.
*/
public static ObjectName makeObjectName(JmxResource jmxResource, JmxSelfNaming selfNamingObj) {
String domainName = selfNamingObj.getJmxDomainName();
if (domainName == null) {
if (jmxResource != null) {
domainName = jmxResource.domainName();
}
if (isEmpty(domainName)) {
throw new IllegalArgumentException(
"Could not create ObjectName because domain name not specified in getJmxDomainName() nor @JmxResource");
}
}
String beanName = selfNamingObj.getJmxNameOfObject();
if (beanName == null) {
if (jmxResource != null) {
beanName = getBeanName(jmxResource);
}
if (isEmpty(beanName)) {
beanName = selfNamingObj.getClass().getSimpleName();
}
}
String[] jmxResourceFolders = null;
if (jmxResource != null) {
jmxResourceFolders = jmxResource.folderNames();
}
return makeObjectName(domainName, beanName, selfNamingObj.getJmxFolderNames(), jmxResourceFolders);
}
/**
* Constructs an object-name from a self naming object only.
*
* @param selfNamingObj
* Object that implements the self-naming interface.
*/
public static ObjectName makeObjectName(JmxSelfNaming selfNamingObj) {
JmxResource jmxResource = selfNamingObj.getClass().getAnnotation(JmxResource.class);
return makeObjectName(jmxResource, selfNamingObj);
}
/**
* Constructs an object-name from a jmx-resource and a object which is not self-naming.
*
* @param jmxResource
* Annotation from the class for which we are creating our ObjectName.
* @param obj
* Object for which we are creating our ObjectName
*/
public static ObjectName makeObjectName(JmxResource jmxResource, Object obj) {
String domainName = jmxResource.domainName();
if (isEmpty(domainName)) {
throw new IllegalArgumentException(
"Could not create ObjectName because domain name not specified in @JmxResource");
}
String beanName = getBeanName(jmxResource);
if (beanName == null) {
beanName = obj.getClass().getSimpleName();
}
return makeObjectName(domainName, beanName, null, jmxResource.folderNames());
}
/**
* Constructs an object-name from a domain-name, object-name, and folder-name strings.
*
* @param domainName
* This is the top level folder name for the beans.
* @param beanName
* This is the bean name in the lowest folder level.
* @param folderNameStrings
* These can be used to setup folders inside of the top folder. Each of the entries in the array can
* either be in "value" or "name=value" format.
*/
public static ObjectName makeObjectName(String domainName, String beanName, String[] folderNameStrings) {
return makeObjectName(domainName, beanName, null, folderNameStrings);
}
/**
* Constructs an object-name from a domain-name and object-name.
*
* @param domainName
* This corresponds to the {@link JmxResource#domainName()} and is the top level folder name for the
* beans.
* @param beanName
* This corresponds to the {@link JmxResource#beanName()} and is the bean name in the lowest folder
* level.
*/
public static ObjectName makeObjectName(String domainName, String beanName) {
return makeObjectName(domainName, beanName, null, null);
}
/**
* Constructs an object-name from an object that is detected either having the {@link JmxResource} annotation or
* implementing {@link JmxSelfNaming}.
*
* @param obj
* Object for which we are creating our ObjectName
*/
public static ObjectName makeObjectName(Object obj) {
JmxResource jmxResource = obj.getClass().getAnnotation(JmxResource.class);
if (obj instanceof JmxSelfNaming) {
return makeObjectName(jmxResource, (JmxSelfNaming) obj);
} else {
if (jmxResource == null) {
throw new IllegalArgumentException(
"Registered class must either implement JmxSelfNaming or have JmxResource annotation");
}
return makeObjectName(jmxResource, obj);
}
}
private static ObjectName makeObjectName(String domainName, String beanName, JmxFolderName[] folderNames,
String[] folderNameStrings) {
// j256:00=clients,name=Foo
StringBuilder sb = new StringBuilder();
sb.append(domainName);
sb.append(':');
boolean first = true;
int prefixC = 0;
+ /*
+ * Self-naming takes precedence over the @JmxResource folder-name strings.
+ */
if (folderNames != null) {
for (JmxFolderName folderName : folderNames) {
if (first) {
first = false;
} else {
sb.append(',');
}
String fieldName = folderName.getField();
if (fieldName == null) {
appendNumericalPrefix(sb, prefixC++);
} else {
sb.append(fieldName);
}
sb.append('=');
sb.append(folderName.getValue());
}
- }
- if (folderNameStrings != null) {
+ } else if (folderNameStrings != null) {
for (String folderNameString : folderNameStrings) {
if (first) {
first = false;
} else {
sb.append(',');
}
// if we have no = then prepend a number
if (folderNameString.indexOf('=') == -1) {
appendNumericalPrefix(sb, prefixC++);
sb.append('=');
}
sb.append(folderNameString);
}
}
if (!first) {
sb.append(',');
}
sb.append("name=");
sb.append(beanName);
String objectNameString = sb.toString();
try {
return new ObjectName(objectNameString);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid ObjectName generated: " + objectNameString, e);
}
}
private static void appendNumericalPrefix(StringBuilder sb, int prefixC) {
if (prefixC < 10) {
sb.append('0');
}
sb.append(prefixC);
}
private static String getBeanName(JmxResource jmxResource) {
String beanName = jmxResource.beanName();
if (!isEmpty(beanName)) {
return beanName;
}
@SuppressWarnings("deprecation")
String deprecatedName = jmxResource.objectName();
if (isEmpty(deprecatedName)) {
return null;
} else {
return deprecatedName;
}
}
private static boolean isEmpty(String str) {
return (str == null || str.length() == 0);
}
}
| false | true | private static ObjectName makeObjectName(String domainName, String beanName, JmxFolderName[] folderNames,
String[] folderNameStrings) {
// j256:00=clients,name=Foo
StringBuilder sb = new StringBuilder();
sb.append(domainName);
sb.append(':');
boolean first = true;
int prefixC = 0;
if (folderNames != null) {
for (JmxFolderName folderName : folderNames) {
if (first) {
first = false;
} else {
sb.append(',');
}
String fieldName = folderName.getField();
if (fieldName == null) {
appendNumericalPrefix(sb, prefixC++);
} else {
sb.append(fieldName);
}
sb.append('=');
sb.append(folderName.getValue());
}
}
if (folderNameStrings != null) {
for (String folderNameString : folderNameStrings) {
if (first) {
first = false;
} else {
sb.append(',');
}
// if we have no = then prepend a number
if (folderNameString.indexOf('=') == -1) {
appendNumericalPrefix(sb, prefixC++);
sb.append('=');
}
sb.append(folderNameString);
}
}
if (!first) {
sb.append(',');
}
sb.append("name=");
sb.append(beanName);
String objectNameString = sb.toString();
try {
return new ObjectName(objectNameString);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid ObjectName generated: " + objectNameString, e);
}
}
| private static ObjectName makeObjectName(String domainName, String beanName, JmxFolderName[] folderNames,
String[] folderNameStrings) {
// j256:00=clients,name=Foo
StringBuilder sb = new StringBuilder();
sb.append(domainName);
sb.append(':');
boolean first = true;
int prefixC = 0;
/*
* Self-naming takes precedence over the @JmxResource folder-name strings.
*/
if (folderNames != null) {
for (JmxFolderName folderName : folderNames) {
if (first) {
first = false;
} else {
sb.append(',');
}
String fieldName = folderName.getField();
if (fieldName == null) {
appendNumericalPrefix(sb, prefixC++);
} else {
sb.append(fieldName);
}
sb.append('=');
sb.append(folderName.getValue());
}
} else if (folderNameStrings != null) {
for (String folderNameString : folderNameStrings) {
if (first) {
first = false;
} else {
sb.append(',');
}
// if we have no = then prepend a number
if (folderNameString.indexOf('=') == -1) {
appendNumericalPrefix(sb, prefixC++);
sb.append('=');
}
sb.append(folderNameString);
}
}
if (!first) {
sb.append(',');
}
sb.append("name=");
sb.append(beanName);
String objectNameString = sb.toString();
try {
return new ObjectName(objectNameString);
} catch (Exception e) {
throw new IllegalArgumentException("Invalid ObjectName generated: " + objectNameString, e);
}
}
|
diff --git a/tool/src/java/org/sakaiproject/poll/tool/producers/PollVoteProducer.java b/tool/src/java/org/sakaiproject/poll/tool/producers/PollVoteProducer.java
index 0adda3a..aa3197c 100644
--- a/tool/src/java/org/sakaiproject/poll/tool/producers/PollVoteProducer.java
+++ b/tool/src/java/org/sakaiproject/poll/tool/producers/PollVoteProducer.java
@@ -1,261 +1,261 @@
/**********************************************************************************
* $URL: $
* $Id: $
***********************************************************************************
*
* Copyright (c) 2006,2007 The Sakai Foundation.
*
* Licensed under the Educational Community License, Version 1.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.opensource.org/licenses/ecl1.php
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
**********************************************************************************/
package org.sakaiproject.poll.tool.producers;
import org.sakaiproject.tool.api.ToolManager;
import org.sakaiproject.user.api.UserDirectoryService;
import org.sakaiproject.poll.logic.PollListManager;
import org.sakaiproject.poll.logic.PollVoteManager;
import org.sakaiproject.poll.model.Option;
import org.sakaiproject.poll.model.Poll;
import uk.org.ponder.messageutil.MessageLocator;
import uk.org.ponder.rsf.components.UIContainer;
import uk.org.ponder.rsf.components.UIOutput;
import uk.org.ponder.rsf.components.UICommand;
import uk.org.ponder.rsf.components.UIInternalLink;
import uk.org.ponder.rsf.view.ComponentChecker;
import uk.org.ponder.rsf.view.ViewComponentProducer;
import uk.org.ponder.rsf.viewstate.ViewParameters;
import uk.org.ponder.localeutil.LocaleGetter;
import uk.org.ponder.rsf.viewstate.EntityCentredViewParameters;
import uk.org.ponder.rsf.viewstate.SimpleViewParameters;
import uk.org.ponder.rsf.viewstate.ViewParamsReporter;
import uk.org.ponder.beanutil.BeanGetter;
import uk.org.ponder.beanutil.entity.EntityID;
import uk.org.ponder.rsf.components.UIELBinding;
import uk.org.ponder.rsf.components.UIMessage;
import uk.org.ponder.rsf.components.UISelect;
import uk.org.ponder.rsf.components.UISelectChoice;
import uk.org.ponder.rsf.components.UISelectLabel;
import uk.org.ponder.rsf.components.UIForm;
import uk.org.ponder.rsf.components.UIBranchContainer;
import uk.org.ponder.rsf.components.UIOutputMany;
import uk.org.ponder.rsf.components.UIVerbatim;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCase;
import uk.org.ponder.rsf.flow.jsfnav.NavigationCaseReporter;
import uk.org.ponder.messageutil.TargettedMessageList;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
public class PollVoteProducer implements ViewComponentProducer,ViewParamsReporter,NavigationCaseReporter {
public static final String VIEW_ID = "voteQuestion";
private BeanGetter rbg;
private UserDirectoryService userDirectoryService;
private PollListManager pollListManager;
private ToolManager toolManager;
private MessageLocator messageLocator;
private LocaleGetter localegetter;
private TargettedMessageList tml;
private PollVoteManager pollVoteManager;
private static Log m_log = LogFactory.getLog(PollVoteProducer.class);
public String getViewID() {
// TODO Auto-generated method stub
return VIEW_ID;
}
public void setPollVoteManager(PollVoteManager pvm){
this.pollVoteManager = pvm;
}
public void setMessageLocator(MessageLocator messageLocator) {
this.messageLocator = messageLocator;
}
public void setUserDirectoryService(UserDirectoryService userDirectoryService) {
this.userDirectoryService = userDirectoryService;
}
public void setPollListManager(PollListManager pollListManager) {
this.pollListManager = pollListManager;
}
public void setToolManager(ToolManager toolManager) {
this.toolManager = toolManager;
}
public void setLocaleGetter(LocaleGetter localegetter) {
this.localegetter = localegetter;
}
public void setTargettedMessageList(TargettedMessageList tml) {
this.tml = tml;
}
public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
if (tml.size() > 0) {
for (int i = 0; i < tml.size(); i ++ ) {
UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:");
String output;
if (tml.messageAt(i).args != null ) {
output = messageLocator.getMessage(tml.messageAt(i).acquireMessageCode(),tml.messageAt(i).args[0]);
} else {
output = messageLocator.getMessage(tml.messageAt(i).acquireMessageCode());
}
UIOutput.make(errorRow,"error", output);
}
}
UIOutput.make(tofill, "poll-vote-title", messageLocator.getMessage("poll_vote_title"));
try {
EntityCentredViewParameters ecvp = (EntityCentredViewParameters) viewparams;
//m_log.info(ecvp.toPathInfo());
//m_log.info(ecvp.getELPath());
//hack but this needs to work
String strId = ecvp.getELPath().substring(ecvp.getELPath().indexOf(".") + 1);
m_log.debug("got id of " + strId);
Poll poll = pollListManager.getPollById(new Long(strId));
m_log.debug("got poll " + poll.getText());
//check if they can vote
if (poll.getLimitVoting() && pollVoteManager.userHasVoted(poll.getPollId())) {
m_log.warn("This user has already voted!");
UIOutput.make(tofill, "hasErrors",messageLocator.getMessage("vote_hasvoted"));
return;
}
UIOutput.make(tofill,"poll-text",poll.getText());
if (poll.getDetails() != null)
{
UIVerbatim.make(tofill,"poll-description",poll.getDetails());
}
m_log.debug("this poll has " + poll.getPollOptions().size()+ " options");
UIForm voteForm = UIForm.make(tofill,"options-form","");
List pollOptions = poll.getPollOptions();
//build the options + label lists
String[] values= new String[pollOptions.size()];
for (int i = 0;i <pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
values[i]= po.getId().toString();
}
String[] labels = new String[pollOptions.size()];
for (int i = 0;i< pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
if (po.getOptionText() != null ) {
labels[i]= po.getOptionText();
} else {
m_log.warn("Option text is null!");
labels[i]="null option!";
}
}
//we need to deside is this a single or multiple?
//poll.getMaxOptions()
boolean isMultiple = false;
if (poll.getMaxOptions()>1)
isMultiple = true;
UISelect radio;
if (isMultiple)
radio = UISelect.makeMultiple(voteForm,"optionform",values,"#{voteCollection.optionsSelected}",new String[] {});
else
radio = UISelect.make(voteForm,"optionform",values,"#{voteCollection.option}",new String());
radio.optionnames = UIOutputMany.make(labels);
String selectID = radio.getFullID();
for (int i = 0;i < pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
m_log.debug("got option " + po.getOptionText() + " with id of " + po.getId());
UIBranchContainer radioRow = UIBranchContainer.make(voteForm,
isMultiple ? "option:select"
: "option:radio"
,Integer.toString(i));
UISelectChoice.make(radioRow,"option-radio",selectID,i);
UISelectLabel.make(radioRow,"option-label",selectID,i);
//UIOutput.make(radioRow,"option-label",labels[i]);
}
//bind some parameters
voteForm.parameters.add(new UIELBinding("#{voteCollection.pollId}", poll.getPollId()));
UICommand sub = UICommand.make(voteForm, "submit-new-vote",messageLocator.getMessage("vote_vote"),
"#{pollToolBean.processActionVote}");
sub.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "sub"));
UICommand cancel = UICommand.make(voteForm, "cancel",messageLocator.getMessage("vote_cancel"),"#{pollToolBean.cancel}");
cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel"));
- UIInternalLink.make(voteForm, "reset", "vote_reset");
+ UIOutput.make(voteForm, "reset", messageLocator.getMessage("vote_reset"));
}
catch (Exception e)
{
m_log.error("Error: " + e);
e.printStackTrace();
}
}
public void setELEvaluator(BeanGetter rbg) {
this.rbg = rbg;
}
public ViewParameters getViewParameters() {
return new EntityCentredViewParameters(VIEW_ID, new EntityID("Poll", null));
}
public List reportNavigationCases() {
List togo = new ArrayList(); // Always navigate back to this view.
//togo.add(new NavigationCase(null, new SimpleViewParameters(VIEW_ID)));
togo.add(new NavigationCase("Error", new SimpleViewParameters(VIEW_ID)));
togo.add(new NavigationCase("Success", new SimpleViewParameters(
ConfirmProducer.VIEW_ID)));
togo.add(new NavigationCase("cancel", new SimpleViewParameters(PollToolProducer.VIEW_ID)));
return togo;
}
}
| true | true | public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
if (tml.size() > 0) {
for (int i = 0; i < tml.size(); i ++ ) {
UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:");
String output;
if (tml.messageAt(i).args != null ) {
output = messageLocator.getMessage(tml.messageAt(i).acquireMessageCode(),tml.messageAt(i).args[0]);
} else {
output = messageLocator.getMessage(tml.messageAt(i).acquireMessageCode());
}
UIOutput.make(errorRow,"error", output);
}
}
UIOutput.make(tofill, "poll-vote-title", messageLocator.getMessage("poll_vote_title"));
try {
EntityCentredViewParameters ecvp = (EntityCentredViewParameters) viewparams;
//m_log.info(ecvp.toPathInfo());
//m_log.info(ecvp.getELPath());
//hack but this needs to work
String strId = ecvp.getELPath().substring(ecvp.getELPath().indexOf(".") + 1);
m_log.debug("got id of " + strId);
Poll poll = pollListManager.getPollById(new Long(strId));
m_log.debug("got poll " + poll.getText());
//check if they can vote
if (poll.getLimitVoting() && pollVoteManager.userHasVoted(poll.getPollId())) {
m_log.warn("This user has already voted!");
UIOutput.make(tofill, "hasErrors",messageLocator.getMessage("vote_hasvoted"));
return;
}
UIOutput.make(tofill,"poll-text",poll.getText());
if (poll.getDetails() != null)
{
UIVerbatim.make(tofill,"poll-description",poll.getDetails());
}
m_log.debug("this poll has " + poll.getPollOptions().size()+ " options");
UIForm voteForm = UIForm.make(tofill,"options-form","");
List pollOptions = poll.getPollOptions();
//build the options + label lists
String[] values= new String[pollOptions.size()];
for (int i = 0;i <pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
values[i]= po.getId().toString();
}
String[] labels = new String[pollOptions.size()];
for (int i = 0;i< pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
if (po.getOptionText() != null ) {
labels[i]= po.getOptionText();
} else {
m_log.warn("Option text is null!");
labels[i]="null option!";
}
}
//we need to deside is this a single or multiple?
//poll.getMaxOptions()
boolean isMultiple = false;
if (poll.getMaxOptions()>1)
isMultiple = true;
UISelect radio;
if (isMultiple)
radio = UISelect.makeMultiple(voteForm,"optionform",values,"#{voteCollection.optionsSelected}",new String[] {});
else
radio = UISelect.make(voteForm,"optionform",values,"#{voteCollection.option}",new String());
radio.optionnames = UIOutputMany.make(labels);
String selectID = radio.getFullID();
for (int i = 0;i < pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
m_log.debug("got option " + po.getOptionText() + " with id of " + po.getId());
UIBranchContainer radioRow = UIBranchContainer.make(voteForm,
isMultiple ? "option:select"
: "option:radio"
,Integer.toString(i));
UISelectChoice.make(radioRow,"option-radio",selectID,i);
UISelectLabel.make(radioRow,"option-label",selectID,i);
//UIOutput.make(radioRow,"option-label",labels[i]);
}
//bind some parameters
voteForm.parameters.add(new UIELBinding("#{voteCollection.pollId}", poll.getPollId()));
UICommand sub = UICommand.make(voteForm, "submit-new-vote",messageLocator.getMessage("vote_vote"),
"#{pollToolBean.processActionVote}");
sub.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "sub"));
UICommand cancel = UICommand.make(voteForm, "cancel",messageLocator.getMessage("vote_cancel"),"#{pollToolBean.cancel}");
cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel"));
UIInternalLink.make(voteForm, "reset", "vote_reset");
}
catch (Exception e)
{
m_log.error("Error: " + e);
e.printStackTrace();
}
}
| public void fillComponents(UIContainer tofill, ViewParameters viewparams, ComponentChecker checker) {
if (tml.size() > 0) {
for (int i = 0; i < tml.size(); i ++ ) {
UIBranchContainer errorRow = UIBranchContainer.make(tofill,"error-row:");
String output;
if (tml.messageAt(i).args != null ) {
output = messageLocator.getMessage(tml.messageAt(i).acquireMessageCode(),tml.messageAt(i).args[0]);
} else {
output = messageLocator.getMessage(tml.messageAt(i).acquireMessageCode());
}
UIOutput.make(errorRow,"error", output);
}
}
UIOutput.make(tofill, "poll-vote-title", messageLocator.getMessage("poll_vote_title"));
try {
EntityCentredViewParameters ecvp = (EntityCentredViewParameters) viewparams;
//m_log.info(ecvp.toPathInfo());
//m_log.info(ecvp.getELPath());
//hack but this needs to work
String strId = ecvp.getELPath().substring(ecvp.getELPath().indexOf(".") + 1);
m_log.debug("got id of " + strId);
Poll poll = pollListManager.getPollById(new Long(strId));
m_log.debug("got poll " + poll.getText());
//check if they can vote
if (poll.getLimitVoting() && pollVoteManager.userHasVoted(poll.getPollId())) {
m_log.warn("This user has already voted!");
UIOutput.make(tofill, "hasErrors",messageLocator.getMessage("vote_hasvoted"));
return;
}
UIOutput.make(tofill,"poll-text",poll.getText());
if (poll.getDetails() != null)
{
UIVerbatim.make(tofill,"poll-description",poll.getDetails());
}
m_log.debug("this poll has " + poll.getPollOptions().size()+ " options");
UIForm voteForm = UIForm.make(tofill,"options-form","");
List pollOptions = poll.getPollOptions();
//build the options + label lists
String[] values= new String[pollOptions.size()];
for (int i = 0;i <pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
values[i]= po.getId().toString();
}
String[] labels = new String[pollOptions.size()];
for (int i = 0;i< pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
if (po.getOptionText() != null ) {
labels[i]= po.getOptionText();
} else {
m_log.warn("Option text is null!");
labels[i]="null option!";
}
}
//we need to deside is this a single or multiple?
//poll.getMaxOptions()
boolean isMultiple = false;
if (poll.getMaxOptions()>1)
isMultiple = true;
UISelect radio;
if (isMultiple)
radio = UISelect.makeMultiple(voteForm,"optionform",values,"#{voteCollection.optionsSelected}",new String[] {});
else
radio = UISelect.make(voteForm,"optionform",values,"#{voteCollection.option}",new String());
radio.optionnames = UIOutputMany.make(labels);
String selectID = radio.getFullID();
for (int i = 0;i < pollOptions.size(); i++ ) {
Option po = (Option)pollOptions.get(i);
m_log.debug("got option " + po.getOptionText() + " with id of " + po.getId());
UIBranchContainer radioRow = UIBranchContainer.make(voteForm,
isMultiple ? "option:select"
: "option:radio"
,Integer.toString(i));
UISelectChoice.make(radioRow,"option-radio",selectID,i);
UISelectLabel.make(radioRow,"option-label",selectID,i);
//UIOutput.make(radioRow,"option-label",labels[i]);
}
//bind some parameters
voteForm.parameters.add(new UIELBinding("#{voteCollection.pollId}", poll.getPollId()));
UICommand sub = UICommand.make(voteForm, "submit-new-vote",messageLocator.getMessage("vote_vote"),
"#{pollToolBean.processActionVote}");
sub.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "sub"));
UICommand cancel = UICommand.make(voteForm, "cancel",messageLocator.getMessage("vote_cancel"),"#{pollToolBean.cancel}");
cancel.parameters.add(new UIELBinding("#{voteCollection.submissionStatus}", "cancel"));
UIOutput.make(voteForm, "reset", messageLocator.getMessage("vote_reset"));
}
catch (Exception e)
{
m_log.error("Error: " + e);
e.printStackTrace();
}
}
|
diff --git a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
index f98af922..4b90b9bc 100644
--- a/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
+++ b/xmlimplsrc/org/mozilla/javascript/xmlimpl/XMLList.java
@@ -1,821 +1,824 @@
/* -*- Mode: java; tab-width: 8; indent-tabs-mode: nil; c-basic-offset: 4 -*-
*
* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1/GPL 2.0
*
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Rhino code, released
* May 6, 1999.
*
* The Initial Developer of the Original Code is
* Netscape Communications Corporation.
* Portions created by the Initial Developer are Copyright (C) 1997-2000
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Ethan Hugg
* Terry Lucas
* Milen Nankov
* David P. Caldwell <[email protected]>
*
* Alternatively, the contents of this file may be used under the terms of
* the GNU General Public License Version 2 or later (the "GPL"), in which
* case the provisions of the GPL are applicable instead of those above. If
* you wish to allow use of your version of this file only under the terms of
* the GPL and not to allow others to use your version of this file under the
* MPL, indicate your decision by deleting the provisions above and replacing
* them with the notice and other provisions required by the GPL. If you do
* not delete the provisions above, a recipient may use your version of this
* file under either the MPL or the GPL.
*
* ***** END LICENSE BLOCK ***** */
package org.mozilla.javascript.xmlimpl;
import org.mozilla.javascript.*;
import org.mozilla.javascript.xml.*;
import java.util.ArrayList;
class XMLList extends XMLObjectImpl implements Function {
static final long serialVersionUID = -4543618751670781135L;
private XmlNode.InternalList _annos;
private XMLObjectImpl targetObject = null;
private XmlNode.QName targetProperty = null;
XMLList(XMLLibImpl lib, Scriptable scope, XMLObject prototype) {
super(lib, scope, prototype);
_annos = new XmlNode.InternalList();
}
/* TODO Will probably end up unnecessary as we move things around */
XmlNode.InternalList getNodeList() {
return _annos;
}
// TODO Should be XMLObjectImpl, XMLName?
void setTargets(XMLObjectImpl object, XmlNode.QName property) {
targetObject = object;
targetProperty = property;
}
/* TODO: original author marked this as deprecated */
private XML getXmlFromAnnotation(int index) {
return getXML(_annos, index);
}
@Override
XML getXML() {
if (length() == 1) return getXmlFromAnnotation(0);
return null;
}
private void internalRemoveFromList(int index) {
_annos.remove(index);
}
void replace(int index, XML xml) {
if (index < length()) {
XmlNode.InternalList newAnnoList = new XmlNode.InternalList();
newAnnoList.add(_annos, 0, index);
newAnnoList.add(xml);
newAnnoList.add(_annos, index+1, length());
_annos = newAnnoList;
}
}
private void insert(int index, XML xml) {
if (index < length()) {
XmlNode.InternalList newAnnoList = new XmlNode.InternalList();
newAnnoList.add(_annos, 0, index);
newAnnoList.add(xml);
newAnnoList.add(_annos, index, length());
_annos = newAnnoList;
}
}
//
//
// methods overriding ScriptableObject
//
//
@Override
public String getClassName() {
return "XMLList";
}
//
//
// methods overriding IdScriptableObject
//
//
@Override
public Object get(int index, Scriptable start) {
//Log("get index: " + index);
if (index >= 0 && index < length()) {
return getXmlFromAnnotation(index);
} else {
return Scriptable.NOT_FOUND;
}
}
@Override
boolean hasXMLProperty(XMLName xmlName) {
boolean result = false;
// Has now should return true if the property would have results > 0 or
// if it's a method name
String name = xmlName.localName();
if ((getPropertyList(xmlName).length() > 0) ||
(getMethod(name) != NOT_FOUND)) {
result = true;
}
return result;
}
@Override
public boolean has(int index, Scriptable start) {
return 0 <= index && index < length();
}
@Override
void putXMLProperty(XMLName xmlName, Object value) {
//Log("put property: " + name);
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (length() > 1) {
throw ScriptRuntime.typeError(
"Assignment to lists with more than one item is not supported");
} else if (length() == 0) {
// Secret sauce for super-expandos.
// We set an element here, and then add ourselves to our target.
if (targetObject != null && targetProperty != null &&
targetProperty.getLocalName() != null &&
targetProperty.getLocalName().length() > 0)
{
// Add an empty element with our targetProperty name and
// then set it.
XML xmlValue = newTextElementXML(null, targetProperty, null);
addToList(xmlValue);
if(xmlName.isAttributeName()) {
setAttribute(xmlName, value);
} else {
XML xml = item(0);
xml.putXMLProperty(xmlName, value);
// Update the list with the new item at location 0.
replace(0, item(0));
}
// Now add us to our parent
XMLName name2 = XMLName.formProperty(
targetProperty.getNamespace().getUri(),
targetProperty.getLocalName());
targetObject.putXMLProperty(name2, this);
} else {
throw ScriptRuntime.typeError(
"Assignment to empty XMLList without targets not supported");
}
} else if(xmlName.isAttributeName()) {
setAttribute(xmlName, value);
} else {
XML xml = item(0);
xml.putXMLProperty(xmlName, value);
// Update the list with the new item at location 0.
replace(0, item(0));
if (targetObject != null && targetProperty != null &&
targetProperty.getLocalName() != null)
{
// Now add us to our parent
XMLName name2 = XMLName.formProperty(
targetProperty.getNamespace().getUri(),
targetProperty.getLocalName());
targetObject.putXMLProperty(name2, this);
}
}
}
@Override
Object getXMLProperty(XMLName name) {
return getPropertyList(name);
}
private void replaceNode(XML xml, XML with) {
xml.replaceWith(with);
}
@Override
public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
+ if (xmlValue == null) {
+ xmlValue = item(0).copy();
+ }
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
private XML getXML(XmlNode.InternalList _annos, int index) {
if (index >= 0 && index < length()) {
return xmlFromNode(_annos.item(index));
} else {
return null;
}
}
@Override
void deleteXMLProperty(XMLName name) {
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
if (xml.isElement()) {
xml.deleteXMLProperty(name);
}
}
}
@Override
public void delete(int index) {
if (index >= 0 && index < length()) {
XML xml = getXmlFromAnnotation(index);
xml.remove();
internalRemoveFromList(index);
}
}
@Override
public Object[] getIds() {
Object enumObjs[];
if (isPrototype()) {
enumObjs = new Object[0];
} else {
enumObjs = new Object[length()];
for (int i = 0; i < enumObjs.length; i++) {
enumObjs[i] = Integer.valueOf(i);
}
}
return enumObjs;
}
public Object[] getIdsForDebug() {
return getIds();
}
// XMLList will remove will delete all items in the list (a set delete) this differs from the XMLList delete operator.
void remove() {
int nLen = length();
for (int i = nLen - 1; i >= 0; i--) {
XML xml = getXmlFromAnnotation(i);
if (xml != null) {
xml.remove();
internalRemoveFromList(i);
}
}
}
XML item(int index) {
return _annos != null
? getXmlFromAnnotation(index) : createEmptyXML();
}
private void setAttribute(XMLName xmlName, Object value) {
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
xml.setAttribute(xmlName, value);
}
}
void addToList(Object toAdd) {
_annos.addToList(toAdd);
}
//
//
// Methods from section 12.4.4 in the spec
//
//
@Override
XMLList child(int index) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).child(index));
}
return result;
}
@Override
XMLList child(XMLName xmlName) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).child(xmlName));
}
return result;
}
@Override
void addMatches(XMLList rv, XMLName name) {
for (int i=0; i<length(); i++) {
getXmlFromAnnotation(i).addMatches(rv, name);
}
}
@Override
XMLList children() {
ArrayList<XML> list = new ArrayList<XML>();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
if (xml != null) {
XMLList childList = xml.children();
int cChildren = childList.length();
for (int j = 0; j < cChildren; j++) {
list.add(childList.item(j));
}
}
}
XMLList allChildren = newXMLList();
int sz = list.size();
for (int i = 0; i < sz; i++) {
allChildren.addToList(list.get(i));
}
return allChildren;
}
@Override
XMLList comments() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.comments());
}
return result;
}
@Override
XMLList elements(XMLName name) {
XMLList rv = newXMLList();
for (int i=0; i<length(); i++) {
XML xml = getXmlFromAnnotation(i);
rv.addToList(xml.elements(name));
}
return rv;
}
@Override
boolean contains(Object xml) {
boolean result = false;
for (int i = 0; i < length(); i++) {
XML member = getXmlFromAnnotation(i);
if (member.equivalentXml(xml)) {
result = true;
break;
}
}
return result;
}
@Override
XMLObjectImpl copy() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.copy());
}
return result;
}
@Override
boolean hasOwnProperty(XMLName xmlName) {
if (isPrototype()) {
String property = xmlName.localName();
return (findPrototypeId(property) != 0);
} else {
return (getPropertyList(xmlName).length() > 0);
}
}
@Override
boolean hasComplexContent() {
boolean complexContent;
int length = length();
if (length == 0) {
complexContent = false;
} else if (length == 1) {
complexContent = getXmlFromAnnotation(0).hasComplexContent();
} else {
complexContent = false;
for (int i = 0; i < length; i++) {
XML nextElement = getXmlFromAnnotation(i);
if (nextElement.isElement()) {
complexContent = true;
break;
}
}
}
return complexContent;
}
@Override
boolean hasSimpleContent() {
if (length() == 0) {
return true;
} else if (length() == 1) {
return getXmlFromAnnotation(0).hasSimpleContent();
} else {
for (int i=0; i<length(); i++) {
XML nextElement = getXmlFromAnnotation(i);
if (nextElement.isElement()) {
return false;
}
}
return true;
}
}
@Override
int length() {
int result = 0;
if (_annos != null) {
result = _annos.length();
}
return result;
}
@Override
void normalize() {
for (int i = 0; i < length(); i++) {
getXmlFromAnnotation(i).normalize();
}
}
/**
* If list is empty, return undefined, if elements have different parents return undefined,
* If they all have the same parent, return that parent
*/
@Override
Object parent() {
if (length() == 0) return Undefined.instance;
XML candidateParent = null;
for (int i = 0; i < length(); i++) {
Object currParent = getXmlFromAnnotation(i).parent();
if (!(currParent instanceof XML)) return Undefined.instance;
XML xml = (XML)currParent;
if (i == 0) {
// Set the first for the rest to compare to.
candidateParent = xml;
} else {
if (candidateParent.is(xml)) {
// keep looking
} else {
return Undefined.instance;
}
}
}
return candidateParent;
}
@Override
XMLList processingInstructions(XMLName xmlName) {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
XML xml = getXmlFromAnnotation(i);
result.addToList(xml.processingInstructions(xmlName));
}
return result;
}
@Override
boolean propertyIsEnumerable(Object name) {
long index;
if (name instanceof Integer) {
index = ((Integer)name).intValue();
} else if (name instanceof Number) {
double x = ((Number)name).doubleValue();
index = (long)x;
if (index != x) {
return false;
}
if (index == 0 && 1.0 / x < 0) {
// Negative 0
return false;
}
} else {
String s = ScriptRuntime.toString(name);
index = ScriptRuntime.testUint32String(s);
}
return (0 <= index && index < length());
}
@Override
XMLList text() {
XMLList result = newXMLList();
for (int i = 0; i < length(); i++) {
result.addToList(getXmlFromAnnotation(i).text());
}
return result;
}
@Override
public String toString() {
// ECMA357 10.1.2
if (hasSimpleContent()) {
StringBuffer sb = new StringBuffer();
for(int i = 0; i < length(); i++) {
XML next = getXmlFromAnnotation(i);
if (next.isComment() || next.isProcessingInstruction()) {
// do nothing
} else {
sb.append(next.toString());
}
}
return sb.toString();
} else {
return toXMLString();
}
}
@Override
String toSource(int indent) {
return toXMLString();
}
@Override
String toXMLString() {
// See ECMA 10.2.1
StringBuffer sb = new StringBuffer();
for (int i=0; i<length(); i++) {
if (getProcessor().isPrettyPrinting() && i != 0) {
sb.append('\n');
}
sb.append(getXmlFromAnnotation(i).toXMLString());
}
return sb.toString();
}
@Override
Object valueOf() {
return this;
}
//
// Other public Functions from XMLObject
//
@Override
boolean equivalentXml(Object target) {
boolean result = false;
// Zero length list should equate to undefined
if (target instanceof Undefined && length() == 0) {
result = true;
} else if (length() == 1) {
result = getXmlFromAnnotation(0).equivalentXml(target);
} else if (target instanceof XMLList) {
XMLList otherList = (XMLList) target;
if (otherList.length() == length()) {
result = true;
for (int i = 0; i < length(); i++) {
if (!getXmlFromAnnotation(i).equivalentXml(otherList.getXmlFromAnnotation(i))) {
result = false;
break;
}
}
}
}
return result;
}
private XMLList getPropertyList(XMLName name) {
XMLList propertyList = newXMLList();
XmlNode.QName qname = null;
if (!name.isDescendants() && !name.isAttributeName()) {
// Only set the targetProperty if this is a regular child get
// and not a descendant or attribute get
qname = name.toQname();
}
propertyList.setTargets(this, qname);
for (int i = 0; i < length(); i++) {
propertyList.addToList(
getXmlFromAnnotation(i).getPropertyList(name));
}
return propertyList;
}
private Object applyOrCall(boolean isApply,
Context cx, Scriptable scope,
Scriptable thisObj, Object[] args) {
String methodName = isApply ? "apply" : "call";
if(!(thisObj instanceof XMLList) ||
((XMLList)thisObj).targetProperty == null)
throw ScriptRuntime.typeError1("msg.isnt.function",
methodName);
return ScriptRuntime.applyOrCall(isApply, cx, scope, thisObj, args);
}
@Override
protected Object jsConstructor(Context cx, boolean inNewExpr,
Object[] args)
{
if (args.length == 0) {
return newXMLList();
} else {
Object arg0 = args[0];
if (!inNewExpr && arg0 instanceof XMLList) {
// XMLList(XMLList) returns the same object.
return arg0;
}
return newXMLListFrom(arg0);
}
}
/**
* See ECMA 357, 11_2_2_1, Semantics, 3_e.
*/
@Override
public Scriptable getExtraMethodSource(Context cx) {
if (length() == 1) {
return getXmlFromAnnotation(0);
}
return null;
}
public Object call(Context cx, Scriptable scope, Scriptable thisObj,
Object[] args) {
// This XMLList is being called as a Function.
// Let's find the real Function object.
if(targetProperty == null)
throw ScriptRuntime.notFunctionError(this);
String methodName = targetProperty.getLocalName();
boolean isApply = methodName.equals("apply");
if(isApply || methodName.equals("call"))
return applyOrCall(isApply, cx, scope, thisObj, args);
Callable method = ScriptRuntime.getElemFunctionAndThis(
this, methodName, cx);
// Call lastStoredScriptable to clear stored thisObj
// but ignore the result as the method should use the supplied
// thisObj, not one from redirected call
ScriptRuntime.lastStoredScriptable(cx);
return method.call(cx, scope, thisObj, args);
}
public Scriptable construct(Context cx, Scriptable scope, Object[] args) {
throw ScriptRuntime.typeError1("msg.not.ctor", "XMLList");
}
}
| true | true | public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
| public void put(int index, Scriptable start, Object value) {
Object parent = Undefined.instance;
// Convert text into XML if needed.
XMLObject xmlValue;
// Special-case checks for undefined and null
if (value == null) {
value = "null";
} else if (value instanceof Undefined) {
value = "undefined";
}
if (value instanceof XMLObject) {
xmlValue = (XMLObject) value;
} else {
if (targetProperty == null) {
xmlValue = newXMLFromJs(value.toString());
} else {
// Note that later in the code, we will use this as an argument to replace(int,value)
// So we will be "replacing" this element with itself
// There may well be a better way to do this
// TODO Find a way to refactor this whole method and simplify it
xmlValue = item(index);
if (xmlValue == null) {
xmlValue = item(0).copy();
}
((XML)xmlValue).setChildren(value);
}
}
// Find the parent
if (index < length()) {
parent = item(index).parent();
} else {
// Appending
parent = parent();
}
if (parent instanceof XML) {
// found parent, alter doc
XML xmlParent = (XML) parent;
if (index < length()) {
// We're replacing the the node.
XML xmlNode = getXmlFromAnnotation(index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
int lastIndexAdded = xmlNode.childIndex();
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
xmlParent.insertChildAfter(xmlParent.getXmlChild(lastIndexAdded), list.item(i));
lastIndexAdded++;
insert(index + i, list.item(i));
}
}
}
} else {
// Appending
xmlParent.appendChild(xmlValue);
addToList(xmlParent.getXmlChild(index));
}
} else {
// Don't all have same parent, no underlying doc to alter
if (index < length()) {
XML xmlNode = getXML(_annos, index);
if (xmlValue instanceof XML) {
replaceNode(xmlNode, (XML) xmlValue);
replace(index, xmlNode);
} else if (xmlValue instanceof XMLList) {
// Replace the first one, and add the rest on the list.
XMLList list = (XMLList) xmlValue;
if (list.length() > 0) {
replaceNode(xmlNode, list.item(0));
replace(index, list.item(0));
for (int i = 1; i < list.length(); i++) {
insert(index + i, list.item(i));
}
}
}
} else {
addToList(xmlValue);
}
}
}
|
diff --git a/src/main/java/mia/recommender/ch02/EvaluatorIntro.java b/src/main/java/mia/recommender/ch02/EvaluatorIntro.java
index fcc53e8..f5a4641 100644
--- a/src/main/java/mia/recommender/ch02/EvaluatorIntro.java
+++ b/src/main/java/mia/recommender/ch02/EvaluatorIntro.java
@@ -1,41 +1,41 @@
package mia.recommender.ch02;
import org.apache.mahout.cf.taste.common.TasteException;
import org.apache.mahout.cf.taste.eval.RecommenderBuilder;
import org.apache.mahout.cf.taste.eval.RecommenderEvaluator;
import org.apache.mahout.cf.taste.impl.eval.AverageAbsoluteDifferenceRecommenderEvaluator;
import org.apache.mahout.cf.taste.impl.model.file.FileDataModel;
import org.apache.mahout.cf.taste.impl.neighborhood.NearestNUserNeighborhood;
import org.apache.mahout.cf.taste.impl.recommender.GenericUserBasedRecommender;
import org.apache.mahout.cf.taste.impl.similarity.PearsonCorrelationSimilarity;
import org.apache.mahout.cf.taste.model.DataModel;
import org.apache.mahout.cf.taste.neighborhood.UserNeighborhood;
import org.apache.mahout.cf.taste.recommender.Recommender;
import org.apache.mahout.cf.taste.similarity.UserSimilarity;
import org.apache.mahout.common.RandomUtils;
import java.io.File;
class EvaluatorIntro {
private EvaluatorIntro() {
}
- public static void x(String[] args) throws Exception {
+ public static void main(String[] args) throws Exception {
RandomUtils.useTestSeed();
DataModel model = new FileDataModel(new File("data/intro.csv"));
RecommenderEvaluator evaluator = new AverageAbsoluteDifferenceRecommenderEvaluator();
// Build the same recommender for testing that we did last time:
RecommenderBuilder recommenderBuilder = new RecommenderBuilder() {
public Recommender buildRecommender(DataModel model) throws TasteException {
UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
UserNeighborhood neighborhood = new NearestNUserNeighborhood(2, similarity, model);
return new GenericUserBasedRecommender(model, neighborhood, similarity);
}
};
// Use 70% of the data to train; test using the other 30%.
double score = evaluator.evaluate(recommenderBuilder, null, model, 0.7, 1.0);
System.out.println(score);
}
}
| true | true | public static void x(String[] args) throws Exception {
RandomUtils.useTestSeed();
DataModel model = new FileDataModel(new File("data/intro.csv"));
RecommenderEvaluator evaluator = new AverageAbsoluteDifferenceRecommenderEvaluator();
// Build the same recommender for testing that we did last time:
RecommenderBuilder recommenderBuilder = new RecommenderBuilder() {
public Recommender buildRecommender(DataModel model) throws TasteException {
UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
UserNeighborhood neighborhood = new NearestNUserNeighborhood(2, similarity, model);
return new GenericUserBasedRecommender(model, neighborhood, similarity);
}
};
// Use 70% of the data to train; test using the other 30%.
double score = evaluator.evaluate(recommenderBuilder, null, model, 0.7, 1.0);
System.out.println(score);
}
| public static void main(String[] args) throws Exception {
RandomUtils.useTestSeed();
DataModel model = new FileDataModel(new File("data/intro.csv"));
RecommenderEvaluator evaluator = new AverageAbsoluteDifferenceRecommenderEvaluator();
// Build the same recommender for testing that we did last time:
RecommenderBuilder recommenderBuilder = new RecommenderBuilder() {
public Recommender buildRecommender(DataModel model) throws TasteException {
UserSimilarity similarity = new PearsonCorrelationSimilarity(model);
UserNeighborhood neighborhood = new NearestNUserNeighborhood(2, similarity, model);
return new GenericUserBasedRecommender(model, neighborhood, similarity);
}
};
// Use 70% of the data to train; test using the other 30%.
double score = evaluator.evaluate(recommenderBuilder, null, model, 0.7, 1.0);
System.out.println(score);
}
|
diff --git a/revolt/src/org/riotfamily/revolt/support/ScriptBuilder.java b/revolt/src/org/riotfamily/revolt/support/ScriptBuilder.java
index 54616b372..9f3ee9d85 100644
--- a/revolt/src/org/riotfamily/revolt/support/ScriptBuilder.java
+++ b/revolt/src/org/riotfamily/revolt/support/ScriptBuilder.java
@@ -1,98 +1,98 @@
/* ***** BEGIN LICENSE BLOCK *****
* Version: MPL 1.1
* The contents of this file are subject to the Mozilla Public License Version
* 1.1 (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.mozilla.org/MPL/
*
* Software distributed under the License is distributed on an "AS IS" basis,
* WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License
* for the specific language governing rights and limitations under the
* License.
*
* The Original Code is Riot.
*
* The Initial Developer of the Original Code is
* Neteye GmbH.
* Portions created by the Initial Developer are Copyright (C) 2007
* the Initial Developer. All Rights Reserved.
*
* Contributor(s):
* Felix Gnass [fgnass at neteye dot de]
*
* ***** END LICENSE BLOCK ***** */
package org.riotfamily.revolt.support;
import java.util.Iterator;
import org.riotfamily.revolt.Dialect;
import org.riotfamily.revolt.Script;
import org.riotfamily.revolt.definition.Database;
import org.riotfamily.revolt.definition.ForeignKey;
import org.riotfamily.revolt.definition.Index;
import org.riotfamily.revolt.definition.Table;
import org.riotfamily.revolt.definition.UniqueConstraint;
/**
* @author Felix Gnass [fgnass at neteye dot de]
* @since 6.4
*/
public class ScriptBuilder {
private Database model;
private Dialect dialect;
private Script script;
public ScriptBuilder(Database model, Dialect dialect) {
this.model = model;
this.dialect = dialect;
}
public Script buildScript() {
script = new Script();
Iterator it = model.getSequences().iterator();
while (it.hasNext()) {
String sequence = (String) it.next();
- dialect.createAutoIncrementSequence(sequence);
+ script.append(dialect.createAutoIncrementSequence(sequence));
}
it = model.getTables().iterator();
while (it.hasNext()) {
Table table = (Table) it.next();
script.append(dialect.createTable(table));
createIndices(table);
createUniqueConstraints(table);
}
it = model.getTables().iterator();
while (it.hasNext()) {
Table table = (Table) it.next();
createForeignKeys(table);
}
return script;
}
private void createIndices(Table table) {
Iterator it = table.getIndices().iterator();
while (it.hasNext()) {
Index index = (Index) it.next();
script.append(dialect.createIndex(table.getName(), index));
}
}
private void createUniqueConstraints(Table table) {
Iterator it = table.getUniqueConstraints().iterator();
while (it.hasNext()) {
UniqueConstraint constraint = (UniqueConstraint) it.next();
script.append(dialect.addUniqueConstraint(table.getName(), constraint));
}
}
private void createForeignKeys(Table table) {
Iterator it = table.getForeignKeys().iterator();
while (it.hasNext()) {
ForeignKey fk = (ForeignKey) it.next();
script.append(dialect.addForeignKey(table.getName(), fk));
}
}
}
| true | true | public Script buildScript() {
script = new Script();
Iterator it = model.getSequences().iterator();
while (it.hasNext()) {
String sequence = (String) it.next();
dialect.createAutoIncrementSequence(sequence);
}
it = model.getTables().iterator();
while (it.hasNext()) {
Table table = (Table) it.next();
script.append(dialect.createTable(table));
createIndices(table);
createUniqueConstraints(table);
}
it = model.getTables().iterator();
while (it.hasNext()) {
Table table = (Table) it.next();
createForeignKeys(table);
}
return script;
}
| public Script buildScript() {
script = new Script();
Iterator it = model.getSequences().iterator();
while (it.hasNext()) {
String sequence = (String) it.next();
script.append(dialect.createAutoIncrementSequence(sequence));
}
it = model.getTables().iterator();
while (it.hasNext()) {
Table table = (Table) it.next();
script.append(dialect.createTable(table));
createIndices(table);
createUniqueConstraints(table);
}
it = model.getTables().iterator();
while (it.hasNext()) {
Table table = (Table) it.next();
createForeignKeys(table);
}
return script;
}
|
diff --git a/server/base/src/main/java/org/apache/accumulo/server/Accumulo.java b/server/base/src/main/java/org/apache/accumulo/server/Accumulo.java
index 57c4e2a56..bcde1509d 100644
--- a/server/base/src/main/java/org/apache/accumulo/server/Accumulo.java
+++ b/server/base/src/main/java/org/apache/accumulo/server/Accumulo.java
@@ -1,264 +1,264 @@
/*
* 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.accumulo.server;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.Map.Entry;
import java.util.TreeMap;
import org.apache.accumulo.core.Constants;
import org.apache.accumulo.core.conf.Property;
import org.apache.accumulo.core.trace.DistributedTrace;
import org.apache.accumulo.core.util.UtilWaitThread;
import org.apache.accumulo.core.util.Version;
import org.apache.accumulo.core.zookeeper.ZooUtil;
import org.apache.accumulo.server.client.HdfsZooInstance;
import org.apache.accumulo.server.conf.ServerConfiguration;
import org.apache.accumulo.server.fs.VolumeManager;
import org.apache.accumulo.server.util.time.SimpleTimer;
import org.apache.accumulo.server.zookeeper.ZooReaderWriter;
import org.apache.hadoop.fs.FileStatus;
import org.apache.hadoop.fs.Path;
import org.apache.log4j.LogManager;
import org.apache.log4j.Logger;
import org.apache.log4j.helpers.FileWatchdog;
import org.apache.log4j.helpers.LogLog;
import org.apache.log4j.xml.DOMConfigurator;
import org.apache.zookeeper.KeeperException;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;
public class Accumulo {
private static final Logger log = Logger.getLogger(Accumulo.class);
public static synchronized void updateAccumuloVersion(VolumeManager fs) {
try {
if (getAccumuloPersistentVersion(fs) == ServerConstants.PREV_DATA_VERSION) {
fs.create(new Path(ServerConstants.getDataVersionLocation() + "/" + ServerConstants.DATA_VERSION));
fs.delete(new Path(ServerConstants.getDataVersionLocation() + "/" + ServerConstants.PREV_DATA_VERSION));
}
} catch (IOException e) {
throw new RuntimeException("Unable to set accumulo version: an error occurred.", e);
}
}
public static synchronized int getAccumuloPersistentVersion(VolumeManager fs) {
int dataVersion;
try {
FileStatus[] files = fs.getDefaultVolume().listStatus(ServerConstants.getDataVersionLocation());
if (files == null || files.length == 0) {
dataVersion = -1; // assume it is 0.5 or earlier
} else {
dataVersion = Integer.parseInt(files[0].getPath().getName());
}
return dataVersion;
} catch (IOException e) {
throw new RuntimeException("Unable to read accumulo version: an error occurred.", e);
}
}
public static void enableTracing(String address, String application) {
try {
DistributedTrace.enable(HdfsZooInstance.getInstance(), ZooReaderWriter.getInstance(), application, address);
} catch (Exception ex) {
log.error("creating remote sink for trace spans", ex);
}
}
private static class LogMonitor extends FileWatchdog implements Watcher {
String path;
protected LogMonitor(String instance, String filename, int delay) {
super(filename);
setDelay(delay);
this.path = ZooUtil.getRoot(instance) + Constants.ZMONITOR_LOG4J_PORT;
}
private void setMonitorPort() {
try {
String port = new String(ZooReaderWriter.getInstance().getData(path, null));
System.setProperty("org.apache.accumulo.core.host.log.port", port);
log.info("Changing monitor log4j port to "+port);
doOnChange();
} catch (Exception e) {
log.error("Error reading zookeeper data for monitor log4j port", e);
}
}
@Override
public void run() {
try {
if (ZooReaderWriter.getInstance().getZooKeeper().exists(path, this) != null)
setMonitorPort();
log.info("Set watch for monitor log4j port");
} catch (Exception e) {
log.error("Unable to set watch for monitor log4j port " + path);
}
super.run();
}
@Override
protected void doOnChange() {
LogManager.resetConfiguration();
new DOMConfigurator().doConfigure(filename, LogManager.getLoggerRepository());
}
@Override
public void process(WatchedEvent event) {
setMonitorPort();
if (event.getPath() != null) {
try {
ZooReaderWriter.getInstance().exists(event.getPath(), this);
} catch (Exception ex) {
log.error("Unable to reset watch for monitor log4j port", ex);
}
}
}
}
public static void init(VolumeManager fs, ServerConfiguration config, String application) throws UnknownHostException {
System.setProperty("org.apache.accumulo.core.application", application);
if (System.getenv("ACCUMULO_LOG_DIR") != null)
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_LOG_DIR"));
else
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_HOME") + "/logs/");
String localhost = InetAddress.getLocalHost().getHostName();
System.setProperty("org.apache.accumulo.core.ip.localhost.hostname", localhost);
if (System.getenv("ACCUMULO_LOG_HOST") != null)
System.setProperty("org.apache.accumulo.core.host.log", System.getenv("ACCUMULO_LOG_HOST"));
else
System.setProperty("org.apache.accumulo.core.host.log", localhost);
int logPort = config.getConfiguration().getPort(Property.MONITOR_LOG4J_PORT);
System.setProperty("org.apache.accumulo.core.host.log.port", Integer.toString(logPort));
// Use a specific log config, if it exists
String logConfig = String.format("%s/%s_logger.xml", System.getenv("ACCUMULO_CONF_DIR"), application);
if (!new File(logConfig).exists()) {
// otherwise, use the generic config
logConfig = String.format("%s/generic_logger.xml", System.getenv("ACCUMULO_CONF_DIR"));
}
// Turn off messages about not being able to reach the remote logger... we protect against that.
LogLog.setQuietMode(true);
// Configure logging
if (logPort==0)
new LogMonitor(config.getInstance().getInstanceID(), logConfig, 5000).start();
else
DOMConfigurator.configureAndWatch(logConfig, 5000);
// Read the auditing config
- String auditConfig = String.format("%s/conf/auditLog.xml", System.getenv("ACCUMULO_HOME"), application);
+ String auditConfig = String.format("%s/auditLog.xml", System.getenv("ACCUMULO_CONF_DIR"), application);
DOMConfigurator.configureAndWatch(auditConfig, 5000);
log.info(application + " starting");
log.info("Instance " + config.getInstance().getInstanceID());
int dataVersion = Accumulo.getAccumuloPersistentVersion(fs);
log.info("Data Version " + dataVersion);
Accumulo.waitForZookeeperAndHdfs(fs);
Version codeVersion = new Version(Constants.VERSION);
if (dataVersion != ServerConstants.DATA_VERSION && dataVersion != ServerConstants.PREV_DATA_VERSION) {
throw new RuntimeException("This version of accumulo (" + codeVersion + ") is not compatible with files stored using data version " + dataVersion);
}
TreeMap<String,String> sortedProps = new TreeMap<String,String>();
for (Entry<String,String> entry : config.getConfiguration())
sortedProps.put(entry.getKey(), entry.getValue());
for (Entry<String,String> entry : sortedProps.entrySet()) {
String key = entry.getKey();
log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue()));
}
monitorSwappiness();
}
/**
*
*/
public static void monitorSwappiness() {
SimpleTimer.getInstance().schedule(new Runnable() {
@Override
public void run() {
try {
String procFile = "/proc/sys/vm/swappiness";
File swappiness = new File(procFile);
if (swappiness.exists() && swappiness.canRead()) {
InputStream is = new FileInputStream(procFile);
try {
byte[] buffer = new byte[10];
int bytes = is.read(buffer);
String setting = new String(buffer, 0, bytes);
setting = setting.trim();
if (bytes > 0 && Integer.parseInt(setting) > 10) {
log.warn("System swappiness setting is greater than ten (" + setting + ") which can cause time-sensitive operations to be delayed. "
+ " Accumulo is time sensitive because it needs to maintain distributed lock agreement.");
}
} finally {
is.close();
}
}
} catch (Throwable t) {
log.error(t, t);
}
}
}, 1000, 10 * 60 * 1000);
}
public static void waitForZookeeperAndHdfs(VolumeManager fs) {
log.info("Attempting to talk to zookeeper");
while (true) {
try {
ZooReaderWriter.getInstance().getChildren(Constants.ZROOT);
break;
} catch (InterruptedException e) {
// ignored
} catch (KeeperException ex) {
log.info("Waiting for accumulo to be initialized");
UtilWaitThread.sleep(1000);
}
}
log.info("Zookeeper connected and initialized, attemping to talk to HDFS");
long sleep = 1000;
while (true) {
try {
if (fs.isReady())
break;
log.warn("Waiting for the NameNode to leave safemode");
} catch (IOException ex) {
log.warn("Unable to connect to HDFS");
}
log.info("Sleeping " + sleep / 1000. + " seconds");
UtilWaitThread.sleep(sleep);
sleep = Math.min(60 * 1000, sleep * 2);
}
log.info("Connected to HDFS");
}
}
| true | true | public static void init(VolumeManager fs, ServerConfiguration config, String application) throws UnknownHostException {
System.setProperty("org.apache.accumulo.core.application", application);
if (System.getenv("ACCUMULO_LOG_DIR") != null)
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_LOG_DIR"));
else
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_HOME") + "/logs/");
String localhost = InetAddress.getLocalHost().getHostName();
System.setProperty("org.apache.accumulo.core.ip.localhost.hostname", localhost);
if (System.getenv("ACCUMULO_LOG_HOST") != null)
System.setProperty("org.apache.accumulo.core.host.log", System.getenv("ACCUMULO_LOG_HOST"));
else
System.setProperty("org.apache.accumulo.core.host.log", localhost);
int logPort = config.getConfiguration().getPort(Property.MONITOR_LOG4J_PORT);
System.setProperty("org.apache.accumulo.core.host.log.port", Integer.toString(logPort));
// Use a specific log config, if it exists
String logConfig = String.format("%s/%s_logger.xml", System.getenv("ACCUMULO_CONF_DIR"), application);
if (!new File(logConfig).exists()) {
// otherwise, use the generic config
logConfig = String.format("%s/generic_logger.xml", System.getenv("ACCUMULO_CONF_DIR"));
}
// Turn off messages about not being able to reach the remote logger... we protect against that.
LogLog.setQuietMode(true);
// Configure logging
if (logPort==0)
new LogMonitor(config.getInstance().getInstanceID(), logConfig, 5000).start();
else
DOMConfigurator.configureAndWatch(logConfig, 5000);
// Read the auditing config
String auditConfig = String.format("%s/conf/auditLog.xml", System.getenv("ACCUMULO_HOME"), application);
DOMConfigurator.configureAndWatch(auditConfig, 5000);
log.info(application + " starting");
log.info("Instance " + config.getInstance().getInstanceID());
int dataVersion = Accumulo.getAccumuloPersistentVersion(fs);
log.info("Data Version " + dataVersion);
Accumulo.waitForZookeeperAndHdfs(fs);
Version codeVersion = new Version(Constants.VERSION);
if (dataVersion != ServerConstants.DATA_VERSION && dataVersion != ServerConstants.PREV_DATA_VERSION) {
throw new RuntimeException("This version of accumulo (" + codeVersion + ") is not compatible with files stored using data version " + dataVersion);
}
TreeMap<String,String> sortedProps = new TreeMap<String,String>();
for (Entry<String,String> entry : config.getConfiguration())
sortedProps.put(entry.getKey(), entry.getValue());
for (Entry<String,String> entry : sortedProps.entrySet()) {
String key = entry.getKey();
log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue()));
}
monitorSwappiness();
}
| public static void init(VolumeManager fs, ServerConfiguration config, String application) throws UnknownHostException {
System.setProperty("org.apache.accumulo.core.application", application);
if (System.getenv("ACCUMULO_LOG_DIR") != null)
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_LOG_DIR"));
else
System.setProperty("org.apache.accumulo.core.dir.log", System.getenv("ACCUMULO_HOME") + "/logs/");
String localhost = InetAddress.getLocalHost().getHostName();
System.setProperty("org.apache.accumulo.core.ip.localhost.hostname", localhost);
if (System.getenv("ACCUMULO_LOG_HOST") != null)
System.setProperty("org.apache.accumulo.core.host.log", System.getenv("ACCUMULO_LOG_HOST"));
else
System.setProperty("org.apache.accumulo.core.host.log", localhost);
int logPort = config.getConfiguration().getPort(Property.MONITOR_LOG4J_PORT);
System.setProperty("org.apache.accumulo.core.host.log.port", Integer.toString(logPort));
// Use a specific log config, if it exists
String logConfig = String.format("%s/%s_logger.xml", System.getenv("ACCUMULO_CONF_DIR"), application);
if (!new File(logConfig).exists()) {
// otherwise, use the generic config
logConfig = String.format("%s/generic_logger.xml", System.getenv("ACCUMULO_CONF_DIR"));
}
// Turn off messages about not being able to reach the remote logger... we protect against that.
LogLog.setQuietMode(true);
// Configure logging
if (logPort==0)
new LogMonitor(config.getInstance().getInstanceID(), logConfig, 5000).start();
else
DOMConfigurator.configureAndWatch(logConfig, 5000);
// Read the auditing config
String auditConfig = String.format("%s/auditLog.xml", System.getenv("ACCUMULO_CONF_DIR"), application);
DOMConfigurator.configureAndWatch(auditConfig, 5000);
log.info(application + " starting");
log.info("Instance " + config.getInstance().getInstanceID());
int dataVersion = Accumulo.getAccumuloPersistentVersion(fs);
log.info("Data Version " + dataVersion);
Accumulo.waitForZookeeperAndHdfs(fs);
Version codeVersion = new Version(Constants.VERSION);
if (dataVersion != ServerConstants.DATA_VERSION && dataVersion != ServerConstants.PREV_DATA_VERSION) {
throw new RuntimeException("This version of accumulo (" + codeVersion + ") is not compatible with files stored using data version " + dataVersion);
}
TreeMap<String,String> sortedProps = new TreeMap<String,String>();
for (Entry<String,String> entry : config.getConfiguration())
sortedProps.put(entry.getKey(), entry.getValue());
for (Entry<String,String> entry : sortedProps.entrySet()) {
String key = entry.getKey();
log.info(key + " = " + (Property.isSensitive(key) ? "<hidden>" : entry.getValue()));
}
monitorSwappiness();
}
|
diff --git a/lucene/src/test/org/apache/lucene/index/TestThreadedForceMerge.java b/lucene/src/test/org/apache/lucene/index/TestThreadedForceMerge.java
index aeb883a8b..520791990 100644
--- a/lucene/src/test/org/apache/lucene/index/TestThreadedForceMerge.java
+++ b/lucene/src/test/org/apache/lucene/index/TestThreadedForceMerge.java
@@ -1,143 +1,143 @@
package org.apache.lucene.index;
/**
* 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.
*/
import org.apache.lucene.analysis.MockAnalyzer;
import org.apache.lucene.analysis.Analyzer;
import org.apache.lucene.analysis.MockTokenizer;
import org.apache.lucene.store.Directory;
import org.apache.lucene.document.Document;
import org.apache.lucene.document.FieldType;
import org.apache.lucene.document.StringField;
import org.apache.lucene.index.IndexWriterConfig.OpenMode;
import org.apache.lucene.util.English;
import org.apache.lucene.util.LuceneTestCase;
import java.util.Random;
public class TestThreadedForceMerge extends LuceneTestCase {
private static final Analyzer ANALYZER = new MockAnalyzer(random, MockTokenizer.SIMPLE, true);
private final static int NUM_THREADS = 3;
//private final static int NUM_THREADS = 5;
private final static int NUM_ITER = 1;
private final static int NUM_ITER2 = 1;
private volatile boolean failed;
private void setFailed() {
failed = true;
}
public void runTest(Random random, Directory directory) throws Exception {
IndexWriter writer = new IndexWriter(
directory,
newIndexWriterConfig(TEST_VERSION_CURRENT, ANALYZER).
setOpenMode(OpenMode.CREATE).
setMaxBufferedDocs(2).
setMergePolicy(newLogMergePolicy())
);
for(int iter=0;iter<NUM_ITER;iter++) {
final int iterFinal = iter;
((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(1000);
final FieldType customType = new FieldType(StringField.TYPE_STORED);
customType.setOmitNorms(true);
for(int i=0;i<200;i++) {
Document d = new Document();
d.add(newField("id", Integer.toString(i), customType));
d.add(newField("contents", English.intToEnglish(i), customType));
writer.addDocument(d);
}
((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(4);
Thread[] threads = new Thread[NUM_THREADS];
for(int i=0;i<NUM_THREADS;i++) {
final int iFinal = i;
final IndexWriter writerFinal = writer;
threads[i] = new Thread() {
@Override
public void run() {
try {
for(int j=0;j<NUM_ITER2;j++) {
writerFinal.forceMerge(1, false);
for(int k=0;k<17*(1+iFinal);k++) {
Document d = new Document();
d.add(newField("id", iterFinal + "_" + iFinal + "_" + j + "_" + k, customType));
d.add(newField("contents", English.intToEnglish(iFinal+k), customType));
writerFinal.addDocument(d);
}
for(int k=0;k<9*(1+iFinal);k++)
writerFinal.deleteDocuments(new Term("id", iterFinal + "_" + iFinal + "_" + j + "_" + k));
writerFinal.forceMerge(1);
}
} catch (Throwable t) {
setFailed();
System.out.println(Thread.currentThread().getName() + ": hit exception");
t.printStackTrace(System.out);
}
}
};
}
for(int i=0;i<NUM_THREADS;i++)
threads[i].start();
for(int i=0;i<NUM_THREADS;i++)
threads[i].join();
assertTrue(!failed);
final int expectedDocCount = (int) ((1+iter)*(200+8*NUM_ITER2*(NUM_THREADS/2.0)*(1+NUM_THREADS)));
assertEquals("index=" + writer.segString() + " numDocs=" + writer.numDocs() + " maxDoc=" + writer.maxDoc() + " config=" + writer.getConfig(), expectedDocCount, writer.numDocs());
assertEquals("index=" + writer.segString() + " numDocs=" + writer.numDocs() + " maxDoc=" + writer.maxDoc() + " config=" + writer.getConfig(), expectedDocCount, writer.maxDoc());
writer.close();
writer = new IndexWriter(directory, newIndexWriterConfig(
TEST_VERSION_CURRENT, ANALYZER).setOpenMode(
OpenMode.APPEND).setMaxBufferedDocs(2));
- IndexReader reader = IndexReader.open(directory);
+ DirectoryReader reader = IndexReader.open(directory);
assertEquals("reader=" + reader, 1, reader.getSequentialSubReaders().length);
assertEquals(expectedDocCount, reader.numDocs());
reader.close();
}
writer.close();
}
/*
Run above stress test against RAMDirectory and then
FSDirectory.
*/
public void testThreadedForceMerge() throws Exception {
Directory directory = newDirectory();
runTest(random, directory);
directory.close();
}
}
| true | true | public void runTest(Random random, Directory directory) throws Exception {
IndexWriter writer = new IndexWriter(
directory,
newIndexWriterConfig(TEST_VERSION_CURRENT, ANALYZER).
setOpenMode(OpenMode.CREATE).
setMaxBufferedDocs(2).
setMergePolicy(newLogMergePolicy())
);
for(int iter=0;iter<NUM_ITER;iter++) {
final int iterFinal = iter;
((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(1000);
final FieldType customType = new FieldType(StringField.TYPE_STORED);
customType.setOmitNorms(true);
for(int i=0;i<200;i++) {
Document d = new Document();
d.add(newField("id", Integer.toString(i), customType));
d.add(newField("contents", English.intToEnglish(i), customType));
writer.addDocument(d);
}
((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(4);
Thread[] threads = new Thread[NUM_THREADS];
for(int i=0;i<NUM_THREADS;i++) {
final int iFinal = i;
final IndexWriter writerFinal = writer;
threads[i] = new Thread() {
@Override
public void run() {
try {
for(int j=0;j<NUM_ITER2;j++) {
writerFinal.forceMerge(1, false);
for(int k=0;k<17*(1+iFinal);k++) {
Document d = new Document();
d.add(newField("id", iterFinal + "_" + iFinal + "_" + j + "_" + k, customType));
d.add(newField("contents", English.intToEnglish(iFinal+k), customType));
writerFinal.addDocument(d);
}
for(int k=0;k<9*(1+iFinal);k++)
writerFinal.deleteDocuments(new Term("id", iterFinal + "_" + iFinal + "_" + j + "_" + k));
writerFinal.forceMerge(1);
}
} catch (Throwable t) {
setFailed();
System.out.println(Thread.currentThread().getName() + ": hit exception");
t.printStackTrace(System.out);
}
}
};
}
for(int i=0;i<NUM_THREADS;i++)
threads[i].start();
for(int i=0;i<NUM_THREADS;i++)
threads[i].join();
assertTrue(!failed);
final int expectedDocCount = (int) ((1+iter)*(200+8*NUM_ITER2*(NUM_THREADS/2.0)*(1+NUM_THREADS)));
assertEquals("index=" + writer.segString() + " numDocs=" + writer.numDocs() + " maxDoc=" + writer.maxDoc() + " config=" + writer.getConfig(), expectedDocCount, writer.numDocs());
assertEquals("index=" + writer.segString() + " numDocs=" + writer.numDocs() + " maxDoc=" + writer.maxDoc() + " config=" + writer.getConfig(), expectedDocCount, writer.maxDoc());
writer.close();
writer = new IndexWriter(directory, newIndexWriterConfig(
TEST_VERSION_CURRENT, ANALYZER).setOpenMode(
OpenMode.APPEND).setMaxBufferedDocs(2));
IndexReader reader = IndexReader.open(directory);
assertEquals("reader=" + reader, 1, reader.getSequentialSubReaders().length);
assertEquals(expectedDocCount, reader.numDocs());
reader.close();
}
writer.close();
}
| public void runTest(Random random, Directory directory) throws Exception {
IndexWriter writer = new IndexWriter(
directory,
newIndexWriterConfig(TEST_VERSION_CURRENT, ANALYZER).
setOpenMode(OpenMode.CREATE).
setMaxBufferedDocs(2).
setMergePolicy(newLogMergePolicy())
);
for(int iter=0;iter<NUM_ITER;iter++) {
final int iterFinal = iter;
((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(1000);
final FieldType customType = new FieldType(StringField.TYPE_STORED);
customType.setOmitNorms(true);
for(int i=0;i<200;i++) {
Document d = new Document();
d.add(newField("id", Integer.toString(i), customType));
d.add(newField("contents", English.intToEnglish(i), customType));
writer.addDocument(d);
}
((LogMergePolicy) writer.getConfig().getMergePolicy()).setMergeFactor(4);
Thread[] threads = new Thread[NUM_THREADS];
for(int i=0;i<NUM_THREADS;i++) {
final int iFinal = i;
final IndexWriter writerFinal = writer;
threads[i] = new Thread() {
@Override
public void run() {
try {
for(int j=0;j<NUM_ITER2;j++) {
writerFinal.forceMerge(1, false);
for(int k=0;k<17*(1+iFinal);k++) {
Document d = new Document();
d.add(newField("id", iterFinal + "_" + iFinal + "_" + j + "_" + k, customType));
d.add(newField("contents", English.intToEnglish(iFinal+k), customType));
writerFinal.addDocument(d);
}
for(int k=0;k<9*(1+iFinal);k++)
writerFinal.deleteDocuments(new Term("id", iterFinal + "_" + iFinal + "_" + j + "_" + k));
writerFinal.forceMerge(1);
}
} catch (Throwable t) {
setFailed();
System.out.println(Thread.currentThread().getName() + ": hit exception");
t.printStackTrace(System.out);
}
}
};
}
for(int i=0;i<NUM_THREADS;i++)
threads[i].start();
for(int i=0;i<NUM_THREADS;i++)
threads[i].join();
assertTrue(!failed);
final int expectedDocCount = (int) ((1+iter)*(200+8*NUM_ITER2*(NUM_THREADS/2.0)*(1+NUM_THREADS)));
assertEquals("index=" + writer.segString() + " numDocs=" + writer.numDocs() + " maxDoc=" + writer.maxDoc() + " config=" + writer.getConfig(), expectedDocCount, writer.numDocs());
assertEquals("index=" + writer.segString() + " numDocs=" + writer.numDocs() + " maxDoc=" + writer.maxDoc() + " config=" + writer.getConfig(), expectedDocCount, writer.maxDoc());
writer.close();
writer = new IndexWriter(directory, newIndexWriterConfig(
TEST_VERSION_CURRENT, ANALYZER).setOpenMode(
OpenMode.APPEND).setMaxBufferedDocs(2));
DirectoryReader reader = IndexReader.open(directory);
assertEquals("reader=" + reader, 1, reader.getSequentialSubReaders().length);
assertEquals(expectedDocCount, reader.numDocs());
reader.close();
}
writer.close();
}
|
diff --git a/frost-wot/source/frost/threads/UpdateIdThread.java b/frost-wot/source/frost/threads/UpdateIdThread.java
index 613bda58..aa7446aa 100644
--- a/frost-wot/source/frost/threads/UpdateIdThread.java
+++ b/frost-wot/source/frost/threads/UpdateIdThread.java
@@ -1,282 +1,290 @@
/*
UpdateIdThread.java / Frost
Copyright (C) 2001 Jan-Thomas Czornack <[email protected]>
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., 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package frost.threads;
import java.util.*;
import java.io.*;
import frost.*;
import frost.gui.objects.*;
public class UpdateIdThread extends BoardUpdateThreadObject implements BoardUpdateThread
{
private static boolean DEBUG = true;
private static int maxFailures = 3;
private static int keyCount = 0;
private static int minKeyCount = 50;
private static int maxKeysPerFile = 5000;
private int maxKeys;
private String date;
private String oldDate;
private int requestHtl;
private int insertHtl;
private String keypool;
private FrostBoardObject board;
private String publicKey;
private String privateKey;
private String requestKey;
private String insertKey;
private String boardState;
public int getThreadType() { return BoardUpdateThread.BOARD_FILE_DNLOAD; }
/**
* Generates a new index file containing keys to upload.
* @return true if index file was created, else false.
*/
private boolean makeIndexFile()
{
if( DEBUG ) System.out.println("FILEDN: UpdateIdThread.makeIndexFile for " + board.toString());
// Calculate the keys to be uploaded
keyCount = Index.getUploadKeys(board.getBoardFilename());
// Adjust maxAge
adjustMaxAge(keyCount);
if( keyCount > 0 )
return true;
else
return false;
}
private void uploadIndexFile()//int i)
{
File indexFile = new File(keypool + board.getBoardFilename() + "_upload.txt");
boolean success = false;
int tries = 0;
String[] result = {"Error", "Error"};
if( indexFile.length() > 0 && indexFile.isFile() )
{
String tozip = FileAccess.readFile(indexFile);
FileAccess.writeZipFile(tozip, "entry", indexFile);
// search empty slot
int index = 0;
while( !success && tries <= maxFailures )
{
// Does this index already exist?
String testFilename = new StringBuffer().append(keypool)
.append(date)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".idx").toString();
File testMe = new File(testFilename);
if( testMe.length() > 0 )
{
index++;
//if( DEBUG ) System.out.println("FILEDN: File exists, increasing index to " + index);
continue;
}
tries++;
result = FcpInsert.putFile(insertKey + index + ".idx.zip",
new File(keypool + board.getBoardFilename() + "_upload.txt"),
insertHtl,
true,
true,
board.getBoardFilename());
if( result[0].equals("Success") )
{
success = true;
if( DEBUG ) System.out.println("FILEDN:***** Index file successfully uploaded *****");
}
else
{
if( result[0].equals("KeyCollision") )
{
index++;
tries=0; // reset tries
if( DEBUG ) System.out.println("FILEDN:***** Index file collided, increasing index. *****");
}
else
{
String tv = result[0];
if( tv == null ) tv="";
if( DEBUG ) System.out.println("FILEDN:***** Unknown upload error (#" + tries + ", '"+tv+"'), retrying. *****");
}
}
}
}
}
// If we're getting too much files on a board, we lower
// the maxAge of keys. That way older keys get removed
// sooner. With the new index system it should be possible
// to work with large numbers of keys because they are
// no longer kept in memory, but on disk.
private void adjustMaxAge(int count) {
//if (DEBUG) System.out.println("FILEDN: AdjustMaxAge: old value = " + frame1.frostSettings.getValue("maxAge"));
int lowerLimit = 10 * maxKeys / 100;
int upperLimit = 90 * maxKeys / 100;
int maxAge = frame1.frostSettings.getIntValue("maxAge");
if (count < lowerLimit && maxAge < 21)
maxAge++;
if (count > upperLimit && maxAge > 1)
maxAge--;
frame1.frostSettings.setValue("maxAge", maxAge);
//if (DEBUG) System.out.println("FILEDN: AdjustMaxAge: new value = " + maxAge);
}
public void run()
{
notifyThreadStarted(this);
try {
// Wait some random time to speed up the update of the TOF table
// ... and to not to flood the node
int waitTime = (int)(Math.random() * 5000); // wait a max. of 5 seconds between start of threads
mixed.wait(waitTime);
int index = 0;
int failures = 0;
while( failures < maxFailures )
{
String filename = new StringBuffer().append(keypool)
.append(date)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".idx").toString();
File target = new File(filename);
// First look if this keyfile has already been downloaded
// and increase the index until we found the last index
if( target.isFile() && target.length() > 0 )
{
index++;
}
else
{
if( DEBUG ) System.out.println("FILEDN: Requesting index " + index);
// Download the keyfile
FcpRequest.getFile(requestKey + index + ".idx.zip",
null,
target,
requestHtl,
true);
if( target.length() > 0 )
{
// Add it to the index
- String unzipped = FileAccess.readZipFile(target);
- FileAccess.writeFile(unzipped,target);
- Index.add(target, new File(keypool + board.getBoardFilename()));
+ try {
+ // maybe the file is corrupted ... so try
+ String unzipped = FileAccess.readZipFile(target);
+ FileAccess.writeFile(unzipped,target);
+ Index.add(target, new File(keypool + board.getBoardFilename()));
+ }
+ catch(Throwable t)
+ {
+ System.out.println("Error in UpdateIdThread: "+t.getMessage());
+ // delete the file and try a re download???
+ }
index++;
failures = 0;
}
else
{
// download failed. Sometimes there are some 0 byte
// files left, we better remove them now.
target.delete();
failures++;
index++;
}
}
if( isInterrupted() ) // check if thread should stop
{
notifyThreadFinished(this);
return;
}
}
// Ok, we're done with downloading the keyfiles
// Now calculate whitch keys we want to upload.
// We only upload own keyfiles if:
// 1. We've got more than minKeyCount keys to upload
// 2. We don't upload any more files
//index -= maxFailures;
if( makeIndexFile() )
{
if( !frame1.generateCHK || keyCount >= minKeyCount )
{
if( DEBUG ) System.out.println("FILEDN: Starting upload of index file to board '"+board.toString()+"'; uploadFiles = " + keyCount);
uploadIndexFile();
}
}
else
{
if( DEBUG ) System.out.println("FILEDN: No keys to upload, stopping UpdateIdThread for " + board.toString());
}
}
catch(Throwable t)
{
System.out.println("Oo. EXCEPTION in UpdateIdThread:");
t.printStackTrace();
}
notifyThreadFinished( this );
}
/**Constructor*/
public UpdateIdThread(FrostBoardObject board)
{
super(board);
this.board = board;
date = DateFun.getExtendedDate();
requestHtl = frame1.frostSettings.getIntValue("keyDownloadHtl");
insertHtl = frame1.frostSettings.getIntValue("keyUploadHtl");
keypool = frame1.frostSettings.getValue("keypool.dir");
maxKeys = frame1.frostSettings.getIntValue("maxKeys");
publicKey = board.getPublicKey();
privateKey = board.getPrivateKey();
if( board.isPublicBoard()==false && publicKey != null )
{
requestKey = new StringBuffer().append(publicKey).append("/").append(date).append("/").toString();
}
else
{
requestKey = new StringBuffer().append("KSK@frost/index/")
.append(board.getBoardFilename())
.append("/")
.append(date)
.append("/").toString();
}
if( board.isPublicBoard()==false && privateKey != null )
insertKey = new StringBuffer().append(privateKey).append("/").append(date).append("/").toString();
else
insertKey = new StringBuffer().append("KSK@frost/index/").append(board.getBoardFilename())
.append("/").append(date).append("/").toString();
}
}
| true | true | public void run()
{
notifyThreadStarted(this);
try {
// Wait some random time to speed up the update of the TOF table
// ... and to not to flood the node
int waitTime = (int)(Math.random() * 5000); // wait a max. of 5 seconds between start of threads
mixed.wait(waitTime);
int index = 0;
int failures = 0;
while( failures < maxFailures )
{
String filename = new StringBuffer().append(keypool)
.append(date)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".idx").toString();
File target = new File(filename);
// First look if this keyfile has already been downloaded
// and increase the index until we found the last index
if( target.isFile() && target.length() > 0 )
{
index++;
}
else
{
if( DEBUG ) System.out.println("FILEDN: Requesting index " + index);
// Download the keyfile
FcpRequest.getFile(requestKey + index + ".idx.zip",
null,
target,
requestHtl,
true);
if( target.length() > 0 )
{
// Add it to the index
String unzipped = FileAccess.readZipFile(target);
FileAccess.writeFile(unzipped,target);
Index.add(target, new File(keypool + board.getBoardFilename()));
index++;
failures = 0;
}
else
{
// download failed. Sometimes there are some 0 byte
// files left, we better remove them now.
target.delete();
failures++;
index++;
}
}
if( isInterrupted() ) // check if thread should stop
{
notifyThreadFinished(this);
return;
}
}
// Ok, we're done with downloading the keyfiles
// Now calculate whitch keys we want to upload.
// We only upload own keyfiles if:
// 1. We've got more than minKeyCount keys to upload
// 2. We don't upload any more files
//index -= maxFailures;
if( makeIndexFile() )
{
if( !frame1.generateCHK || keyCount >= minKeyCount )
{
if( DEBUG ) System.out.println("FILEDN: Starting upload of index file to board '"+board.toString()+"'; uploadFiles = " + keyCount);
uploadIndexFile();
}
}
else
{
if( DEBUG ) System.out.println("FILEDN: No keys to upload, stopping UpdateIdThread for " + board.toString());
}
}
catch(Throwable t)
{
System.out.println("Oo. EXCEPTION in UpdateIdThread:");
t.printStackTrace();
}
notifyThreadFinished( this );
}
| public void run()
{
notifyThreadStarted(this);
try {
// Wait some random time to speed up the update of the TOF table
// ... and to not to flood the node
int waitTime = (int)(Math.random() * 5000); // wait a max. of 5 seconds between start of threads
mixed.wait(waitTime);
int index = 0;
int failures = 0;
while( failures < maxFailures )
{
String filename = new StringBuffer().append(keypool)
.append(date)
.append("-")
.append(board.getBoardFilename())
.append("-")
.append(index)
.append(".idx").toString();
File target = new File(filename);
// First look if this keyfile has already been downloaded
// and increase the index until we found the last index
if( target.isFile() && target.length() > 0 )
{
index++;
}
else
{
if( DEBUG ) System.out.println("FILEDN: Requesting index " + index);
// Download the keyfile
FcpRequest.getFile(requestKey + index + ".idx.zip",
null,
target,
requestHtl,
true);
if( target.length() > 0 )
{
// Add it to the index
try {
// maybe the file is corrupted ... so try
String unzipped = FileAccess.readZipFile(target);
FileAccess.writeFile(unzipped,target);
Index.add(target, new File(keypool + board.getBoardFilename()));
}
catch(Throwable t)
{
System.out.println("Error in UpdateIdThread: "+t.getMessage());
// delete the file and try a re download???
}
index++;
failures = 0;
}
else
{
// download failed. Sometimes there are some 0 byte
// files left, we better remove them now.
target.delete();
failures++;
index++;
}
}
if( isInterrupted() ) // check if thread should stop
{
notifyThreadFinished(this);
return;
}
}
// Ok, we're done with downloading the keyfiles
// Now calculate whitch keys we want to upload.
// We only upload own keyfiles if:
// 1. We've got more than minKeyCount keys to upload
// 2. We don't upload any more files
//index -= maxFailures;
if( makeIndexFile() )
{
if( !frame1.generateCHK || keyCount >= minKeyCount )
{
if( DEBUG ) System.out.println("FILEDN: Starting upload of index file to board '"+board.toString()+"'; uploadFiles = " + keyCount);
uploadIndexFile();
}
}
else
{
if( DEBUG ) System.out.println("FILEDN: No keys to upload, stopping UpdateIdThread for " + board.toString());
}
}
catch(Throwable t)
{
System.out.println("Oo. EXCEPTION in UpdateIdThread:");
t.printStackTrace();
}
notifyThreadFinished( this );
}
|
diff --git a/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/reports/tests/ContextParsingTest.java b/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/reports/tests/ContextParsingTest.java
index ee0cf536..eea91e8a 100644
--- a/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/reports/tests/ContextParsingTest.java
+++ b/org.eclipse.mylyn.monitor.tests/src/org/eclipse/mylyn/monitor/reports/tests/ContextParsingTest.java
@@ -1,99 +1,99 @@
/*******************************************************************************
* Copyright (c) 2004 - 2006 University Of British Columbia and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* University Of British Columbia - initial API and implementation
*******************************************************************************/
package org.eclipse.mylar.monitor.reports.tests;
import java.io.File;
import java.util.List;
import junit.framework.TestCase;
import org.eclipse.core.runtime.Path;
import org.eclipse.mylar.core.IMylarElement;
import org.eclipse.mylar.core.InteractionEvent;
import org.eclipse.mylar.internal.core.MylarContext;
import org.eclipse.mylar.internal.core.ScalingFactor;
import org.eclipse.mylar.internal.core.ScalingFactors;
import org.eclipse.mylar.internal.monitor.InteractionEventLogger;
import org.eclipse.mylar.internal.monitor.monitors.SelectionMonitor;
import org.eclipse.mylar.monitor.tests.MylarMonitorTestsPlugin;
/**
* @author Mik Kersten
*/
public class ContextParsingTest extends TestCase {
private static final String PATH_USAGE_FILE = "testdata/usage-parsing.zip";
private List<InteractionEvent> events;
@Override
protected void setUp() throws Exception {
super.setUp();
File file;
if (MylarMonitorTestsPlugin.getDefault() != null) {
file = FileTool.getFileInPlugin(MylarMonitorTestsPlugin.getDefault(), new Path(PATH_USAGE_FILE));
} else {
file = new File(PATH_USAGE_FILE);
}
InteractionEventLogger logger = new InteractionEventLogger(file);
events = logger.getHistoryFromFile(file);
}
@Override
protected void tearDown() throws Exception {
super.tearDown();
events.clear();
}
public void testOriginIdValidity() {
for (InteractionEvent event : events) {
if (event.isValidStructureHandle()) {
assertFalse(event.getStructureHandle().equals("null"));
}
}
}
- public void testInteractionHistoryWithoutDecay() {
+ public void testHistoryParsingWithDecayReset() {
ScalingFactors scalingFactors = new ScalingFactors();
// scalingFactors.setDecay(new ScalingFactor("decay", .05f));
MylarContext context = new MylarContext("test", scalingFactors);
int numEvents = 0;
for (InteractionEvent event : events) {
if (SelectionMonitor.isValidStructureHandle(event)) {
InteractionEvent newEvent = InteractionEvent.makeCopy(event, 1f);
context.parseEvent(newEvent);
if (SelectionMonitor.isValidStructureHandle(event) && event.getKind().equals(InteractionEvent.Kind.SELECTION)) {
IMylarElement element = context.parseEvent(event);
// reset decay if not selected
if (element.getInterest().getValue() < 0) {
float decayOffset = (-1) * (element.getInterest().getValue()) + 1;
element = context.parseEvent(new InteractionEvent(InteractionEvent.Kind.MANIPULATION,
event.getContentType(), event.getStructureHandle(), "test-decay", decayOffset));
}
assertTrue("should be positive: " + element.getInterest().getValue(), element.getInterest().getValue() >= 0);
// System.err.println(">>> " + element.getInterest().getValue() + ", handle: "
// + element.getHandleIdentifier());
numEvents++;
}
}
}
}
public void testScalingVactorSet() {
ScalingFactors scalingFactors = new ScalingFactors();
scalingFactors.setDecay(new ScalingFactor("decay", 0f));
MylarContext context = new MylarContext("test", scalingFactors);
assertEquals(0f, context.getScalingFactors().getDecay().getValue());
}
}
| true | true | public void testInteractionHistoryWithoutDecay() {
ScalingFactors scalingFactors = new ScalingFactors();
// scalingFactors.setDecay(new ScalingFactor("decay", .05f));
MylarContext context = new MylarContext("test", scalingFactors);
int numEvents = 0;
for (InteractionEvent event : events) {
if (SelectionMonitor.isValidStructureHandle(event)) {
InteractionEvent newEvent = InteractionEvent.makeCopy(event, 1f);
context.parseEvent(newEvent);
if (SelectionMonitor.isValidStructureHandle(event) && event.getKind().equals(InteractionEvent.Kind.SELECTION)) {
IMylarElement element = context.parseEvent(event);
// reset decay if not selected
if (element.getInterest().getValue() < 0) {
float decayOffset = (-1) * (element.getInterest().getValue()) + 1;
element = context.parseEvent(new InteractionEvent(InteractionEvent.Kind.MANIPULATION,
event.getContentType(), event.getStructureHandle(), "test-decay", decayOffset));
}
assertTrue("should be positive: " + element.getInterest().getValue(), element.getInterest().getValue() >= 0);
// System.err.println(">>> " + element.getInterest().getValue() + ", handle: "
// + element.getHandleIdentifier());
numEvents++;
}
}
}
}
| public void testHistoryParsingWithDecayReset() {
ScalingFactors scalingFactors = new ScalingFactors();
// scalingFactors.setDecay(new ScalingFactor("decay", .05f));
MylarContext context = new MylarContext("test", scalingFactors);
int numEvents = 0;
for (InteractionEvent event : events) {
if (SelectionMonitor.isValidStructureHandle(event)) {
InteractionEvent newEvent = InteractionEvent.makeCopy(event, 1f);
context.parseEvent(newEvent);
if (SelectionMonitor.isValidStructureHandle(event) && event.getKind().equals(InteractionEvent.Kind.SELECTION)) {
IMylarElement element = context.parseEvent(event);
// reset decay if not selected
if (element.getInterest().getValue() < 0) {
float decayOffset = (-1) * (element.getInterest().getValue()) + 1;
element = context.parseEvent(new InteractionEvent(InteractionEvent.Kind.MANIPULATION,
event.getContentType(), event.getStructureHandle(), "test-decay", decayOffset));
}
assertTrue("should be positive: " + element.getInterest().getValue(), element.getInterest().getValue() >= 0);
// System.err.println(">>> " + element.getInterest().getValue() + ", handle: "
// + element.getHandleIdentifier());
numEvents++;
}
}
}
}
|
diff --git a/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/coverageview/CoverageView.java b/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/coverageview/CoverageView.java
index 7e6f1a2..d19a7d8 100644
--- a/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/coverageview/CoverageView.java
+++ b/com.mountainminds.eclemma.ui/src/com/mountainminds/eclemma/internal/ui/coverageview/CoverageView.java
@@ -1,366 +1,366 @@
/*******************************************************************************
* Copyright (c) 2006, 2014 Mountainminds GmbH & Co. KG and Contributors
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* Marc R. Hoffmann - initial API and implementation
* Brock Janiczak - link with selection option (SF #1774547)
*
******************************************************************************/
package com.mountainminds.eclemma.internal.ui.coverageview;
import java.util.ArrayList;
import java.util.List;
import org.eclipse.core.commands.IHandler;
import org.eclipse.jdt.ui.actions.IJavaEditorActionDefinitionIds;
import org.eclipse.jdt.ui.actions.JdtActionConstants;
import org.eclipse.jdt.ui.actions.OpenAction;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.viewers.CellLabelProvider;
import org.eclipse.jface.viewers.ILabelProvider;
import org.eclipse.jface.viewers.IOpenListener;
import org.eclipse.jface.viewers.ISelection;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.viewers.OpenEvent;
import org.eclipse.jface.viewers.OwnerDrawLabelProvider;
import org.eclipse.jface.viewers.TreeViewer;
import org.eclipse.jface.viewers.TreeViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.jface.viewers.ViewerCell;
import org.eclipse.jface.viewers.ViewerFilter;
import org.eclipse.swt.SWT;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Event;
import org.eclipse.swt.widgets.Tree;
import org.eclipse.ui.IActionBars;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchCommandConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.actions.ActionFactory;
import org.eclipse.ui.dialogs.PropertyDialogAction;
import org.eclipse.ui.handlers.CollapseAllHandler;
import org.eclipse.ui.handlers.IHandlerService;
import org.eclipse.ui.model.WorkbenchLabelProvider;
import org.eclipse.ui.part.IShowInTarget;
import org.eclipse.ui.part.ShowInContext;
import org.eclipse.ui.part.ViewPart;
import org.jacoco.core.analysis.ICounter;
import org.jacoco.core.analysis.ICoverageNode;
import com.mountainminds.eclemma.core.CoverageTools;
import com.mountainminds.eclemma.core.ICoverageSession;
import com.mountainminds.eclemma.core.ISessionListener;
import com.mountainminds.eclemma.core.analysis.IJavaCoverageListener;
import com.mountainminds.eclemma.internal.ui.ContextHelp;
import com.mountainminds.eclemma.internal.ui.RedGreenBar;
import com.mountainminds.eclemma.internal.ui.UIMessages;
/**
* Implementation of the coverage view.
*/
public class CoverageView extends ViewPart implements IShowInTarget {
public static final String ID = "com.mountainminds.eclemma.ui.CoverageView"; //$NON-NLS-1$
/**
* Placeholder element for displaying "Loading..." in the coverage view.
*/
public static final Object LOADING_ELEMENT = new Object();
private final ViewSettings settings = new ViewSettings();
private final CellTextConverter cellTextConverter = new CellTextConverter(
settings);
private final MaxTotalCache maxTotalCache = new MaxTotalCache(settings);
protected static final int COLUMN_ELEMENT = 0;
protected static final int COLUMN_RATIO = 1;
protected static final int COLUMN_COVERED = 2;
protected static final int COLUMN_MISSED = 3;
protected static final int COLUMN_TOTAL = 4;
private TreeViewer viewer;
// Actions
private OpenAction openAction;
private final List<IHandler> handlers = new ArrayList<IHandler>();
private SelectionTracker selectiontracker;
private CoverageViewSorter sorter = new CoverageViewSorter(settings, this);
private final ISessionListener descriptionUpdater = new ISessionListener() {
public void sessionActivated(ICoverageSession session) {
getViewSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
final ICoverageSession active = CoverageTools.getSessionManager()
.getActiveSession();
setContentDescription(active == null ? "" : active.getDescription()); //$NON-NLS-1$
}
});
}
public void sessionAdded(ICoverageSession addedSession) {
// Nothing to do
}
public void sessionRemoved(ICoverageSession removedSession) {
// Nothing to do
}
};
private final IJavaCoverageListener coverageListener = new IJavaCoverageListener() {
public void coverageChanged() {
getSite().getShell().getDisplay().asyncExec(new Runnable() {
public void run() {
maxTotalCache.reset();
viewer.setInput(CoverageTools.getJavaModelCoverage());
}
});
}
};
public void init(IViewSite site, IMemento memento) throws PartInitException {
super.init(site, memento);
settings.init(memento);
}
public void saveState(IMemento memento) {
settings.storeColumnWidth(viewer);
settings.save(memento);
super.saveState(memento);
}
public void createPartControl(Composite parent) {
ContextHelp.setHelp(parent, ContextHelp.COVERAGE_VIEW);
Tree tree = new Tree(parent, SWT.MULTI);
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
viewer = new TreeViewer(tree);
final TreeViewerColumn column0 = new TreeViewerColumn(viewer, SWT.LEFT);
column0.setLabelProvider(new CellLabelProvider() {
private final ILabelProvider delegate = new WorkbenchLabelProvider();
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(UIMessages.CoverageView_loadingMessage);
cell.setImage(null);
} else {
cell.setText(cellTextConverter.getElementName(cell.getElement()));
cell.setImage(delegate.getImage(cell.getElement()));
}
}
});
sorter.addColumn(column0, COLUMN_ELEMENT);
final TreeViewerColumn column1 = new TreeViewerColumn(viewer, SWT.RIGHT);
column1.setLabelProvider(new OwnerDrawLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getRatio(cell.getElement()));
}
}
@Override
protected void erase(Event event, Object element) {
}
@Override
protected void measure(Event event, Object element) {
}
@Override
protected void paint(Event event, Object element) {
- if (element != LOADING_ELEMENT) {
- ICounter counter = CoverageTools.getCoverageInfo(element).getCounter(
- settings.getCounters());
+ final ICoverageNode coverage = CoverageTools.getCoverageInfo(element);
+ if (coverage != null) {
+ final ICounter counter = coverage.getCounter(settings.getCounters());
RedGreenBar.draw(event, column1.getColumn().getWidth(), counter,
maxTotalCache.getMaxTotal(element));
}
}
});
sorter.addColumn(column1, COLUMN_RATIO);
final TreeViewerColumn column2 = new TreeViewerColumn(viewer, SWT.RIGHT);
column2.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getCovered(cell.getElement()));
}
}
});
sorter.addColumn(column2, COLUMN_COVERED);
final TreeViewerColumn column3 = new TreeViewerColumn(viewer, SWT.RIGHT);
column3.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getMissed(cell.getElement()));
}
}
});
sorter.addColumn(column3, COLUMN_MISSED);
final TreeViewerColumn column4 = new TreeViewerColumn(viewer, SWT.RIGHT);
column4.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getTotal(cell.getElement()));
}
}
});
sorter.addColumn(column4, COLUMN_TOTAL);
viewer.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element == LOADING_ELEMENT) {
return true;
} else {
final ICoverageNode c = CoverageTools.getCoverageInfo(element);
if (c == null) {
return false;
}
final ICounter instructions = c.getInstructionCounter();
if (instructions.getTotalCount() == 0) {
return false;
}
if (settings.getHideUnusedElements()
&& instructions.getCoveredCount() == 0) {
return false;
}
return true;
}
}
});
settings.updateColumnHeaders(viewer);
settings.restoreColumnWidth(viewer);
viewer.setComparator(sorter);
viewer.setContentProvider(new CoveredElementsContentProvider(settings));
viewer.setInput(CoverageTools.getJavaModelCoverage());
getSite().setSelectionProvider(viewer);
selectiontracker = new SelectionTracker(this, viewer);
createHandlers();
createActions();
viewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
openAction.run((IStructuredSelection) event.getSelection());
}
});
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
tree.setMenu(menuMgr.createContextMenu(tree));
getSite().registerContextMenu(menuMgr, viewer);
CoverageTools.getSessionManager().addSessionListener(descriptionUpdater);
CoverageTools.addJavaCoverageListener(coverageListener);
}
/**
* Create local handlers.
*/
private void createHandlers() {
activateHandler(SelectRootElementsHandler.ID,
new SelectRootElementsHandler(settings, this));
activateHandler(SelectCountersHandler.ID, new SelectCountersHandler(
settings, this));
activateHandler(HideUnusedElementsHandler.ID,
new HideUnusedElementsHandler(settings, this));
activateHandler(IWorkbenchCommandConstants.EDIT_COPY, new CopyHandler(
settings, getSite().getShell().getDisplay(), viewer));
activateHandler(IWorkbenchCommandConstants.FILE_REFRESH,
new RefreshSessionHandler(CoverageTools.getSessionManager()));
activateHandler(IWorkbenchCommandConstants.NAVIGATE_COLLAPSE_ALL,
new CollapseAllHandler(viewer));
activateHandler(LinkWithSelectionHandler.ID, new LinkWithSelectionHandler(
settings, selectiontracker));
}
private void activateHandler(String id, IHandler handler) {
final IHandlerService hs = (IHandlerService) getSite().getService(
IHandlerService.class);
hs.activateHandler(id, handler);
handlers.add(handler);
}
private void createActions() {
// For the following commands we use actions, as they are already available
final IActionBars ab = getViewSite().getActionBars();
openAction = new OpenAction(getSite());
openAction
.setActionDefinitionId(IJavaEditorActionDefinitionIds.OPEN_EDITOR);
ab.setGlobalActionHandler(JdtActionConstants.OPEN, openAction);
openAction.setEnabled(false);
viewer.addSelectionChangedListener(openAction);
PropertyDialogAction propertiesAction = new PropertyDialogAction(getSite(),
viewer);
propertiesAction
.setActionDefinitionId(IWorkbenchCommandConstants.FILE_PROPERTIES);
ab.setGlobalActionHandler(ActionFactory.PROPERTIES.getId(),
propertiesAction);
propertiesAction.setEnabled(false);
viewer.addSelectionChangedListener(propertiesAction);
}
public void setFocus() {
viewer.getTree().setFocus();
}
public void dispose() {
for (IHandler h : handlers) {
h.dispose();
}
handlers.clear();
CoverageTools.removeJavaCoverageListener(coverageListener);
CoverageTools.getSessionManager().removeSessionListener(descriptionUpdater);
selectiontracker.dispose();
super.dispose();
}
protected void refreshViewer() {
maxTotalCache.reset();
settings.updateColumnHeaders(viewer);
viewer.refresh();
}
public boolean show(ShowInContext context) {
final ISelection selection = context.getSelection();
if (selection instanceof IStructuredSelection) {
viewer.setSelection(selection);
return true;
}
return false;
}
}
| true | true | public void createPartControl(Composite parent) {
ContextHelp.setHelp(parent, ContextHelp.COVERAGE_VIEW);
Tree tree = new Tree(parent, SWT.MULTI);
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
viewer = new TreeViewer(tree);
final TreeViewerColumn column0 = new TreeViewerColumn(viewer, SWT.LEFT);
column0.setLabelProvider(new CellLabelProvider() {
private final ILabelProvider delegate = new WorkbenchLabelProvider();
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(UIMessages.CoverageView_loadingMessage);
cell.setImage(null);
} else {
cell.setText(cellTextConverter.getElementName(cell.getElement()));
cell.setImage(delegate.getImage(cell.getElement()));
}
}
});
sorter.addColumn(column0, COLUMN_ELEMENT);
final TreeViewerColumn column1 = new TreeViewerColumn(viewer, SWT.RIGHT);
column1.setLabelProvider(new OwnerDrawLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getRatio(cell.getElement()));
}
}
@Override
protected void erase(Event event, Object element) {
}
@Override
protected void measure(Event event, Object element) {
}
@Override
protected void paint(Event event, Object element) {
if (element != LOADING_ELEMENT) {
ICounter counter = CoverageTools.getCoverageInfo(element).getCounter(
settings.getCounters());
RedGreenBar.draw(event, column1.getColumn().getWidth(), counter,
maxTotalCache.getMaxTotal(element));
}
}
});
sorter.addColumn(column1, COLUMN_RATIO);
final TreeViewerColumn column2 = new TreeViewerColumn(viewer, SWT.RIGHT);
column2.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getCovered(cell.getElement()));
}
}
});
sorter.addColumn(column2, COLUMN_COVERED);
final TreeViewerColumn column3 = new TreeViewerColumn(viewer, SWT.RIGHT);
column3.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getMissed(cell.getElement()));
}
}
});
sorter.addColumn(column3, COLUMN_MISSED);
final TreeViewerColumn column4 = new TreeViewerColumn(viewer, SWT.RIGHT);
column4.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getTotal(cell.getElement()));
}
}
});
sorter.addColumn(column4, COLUMN_TOTAL);
viewer.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element == LOADING_ELEMENT) {
return true;
} else {
final ICoverageNode c = CoverageTools.getCoverageInfo(element);
if (c == null) {
return false;
}
final ICounter instructions = c.getInstructionCounter();
if (instructions.getTotalCount() == 0) {
return false;
}
if (settings.getHideUnusedElements()
&& instructions.getCoveredCount() == 0) {
return false;
}
return true;
}
}
});
settings.updateColumnHeaders(viewer);
settings.restoreColumnWidth(viewer);
viewer.setComparator(sorter);
viewer.setContentProvider(new CoveredElementsContentProvider(settings));
viewer.setInput(CoverageTools.getJavaModelCoverage());
getSite().setSelectionProvider(viewer);
selectiontracker = new SelectionTracker(this, viewer);
createHandlers();
createActions();
viewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
openAction.run((IStructuredSelection) event.getSelection());
}
});
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
tree.setMenu(menuMgr.createContextMenu(tree));
getSite().registerContextMenu(menuMgr, viewer);
CoverageTools.getSessionManager().addSessionListener(descriptionUpdater);
CoverageTools.addJavaCoverageListener(coverageListener);
}
| public void createPartControl(Composite parent) {
ContextHelp.setHelp(parent, ContextHelp.COVERAGE_VIEW);
Tree tree = new Tree(parent, SWT.MULTI);
tree.setHeaderVisible(true);
tree.setLinesVisible(true);
viewer = new TreeViewer(tree);
final TreeViewerColumn column0 = new TreeViewerColumn(viewer, SWT.LEFT);
column0.setLabelProvider(new CellLabelProvider() {
private final ILabelProvider delegate = new WorkbenchLabelProvider();
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(UIMessages.CoverageView_loadingMessage);
cell.setImage(null);
} else {
cell.setText(cellTextConverter.getElementName(cell.getElement()));
cell.setImage(delegate.getImage(cell.getElement()));
}
}
});
sorter.addColumn(column0, COLUMN_ELEMENT);
final TreeViewerColumn column1 = new TreeViewerColumn(viewer, SWT.RIGHT);
column1.setLabelProvider(new OwnerDrawLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getRatio(cell.getElement()));
}
}
@Override
protected void erase(Event event, Object element) {
}
@Override
protected void measure(Event event, Object element) {
}
@Override
protected void paint(Event event, Object element) {
final ICoverageNode coverage = CoverageTools.getCoverageInfo(element);
if (coverage != null) {
final ICounter counter = coverage.getCounter(settings.getCounters());
RedGreenBar.draw(event, column1.getColumn().getWidth(), counter,
maxTotalCache.getMaxTotal(element));
}
}
});
sorter.addColumn(column1, COLUMN_RATIO);
final TreeViewerColumn column2 = new TreeViewerColumn(viewer, SWT.RIGHT);
column2.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getCovered(cell.getElement()));
}
}
});
sorter.addColumn(column2, COLUMN_COVERED);
final TreeViewerColumn column3 = new TreeViewerColumn(viewer, SWT.RIGHT);
column3.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getMissed(cell.getElement()));
}
}
});
sorter.addColumn(column3, COLUMN_MISSED);
final TreeViewerColumn column4 = new TreeViewerColumn(viewer, SWT.RIGHT);
column4.setLabelProvider(new CellLabelProvider() {
@Override
public void update(ViewerCell cell) {
if (cell.getElement() == LOADING_ELEMENT) {
cell.setText(""); //$NON-NLS-1$
} else {
cell.setText(cellTextConverter.getTotal(cell.getElement()));
}
}
});
sorter.addColumn(column4, COLUMN_TOTAL);
viewer.addFilter(new ViewerFilter() {
public boolean select(Viewer viewer, Object parentElement, Object element) {
if (element == LOADING_ELEMENT) {
return true;
} else {
final ICoverageNode c = CoverageTools.getCoverageInfo(element);
if (c == null) {
return false;
}
final ICounter instructions = c.getInstructionCounter();
if (instructions.getTotalCount() == 0) {
return false;
}
if (settings.getHideUnusedElements()
&& instructions.getCoveredCount() == 0) {
return false;
}
return true;
}
}
});
settings.updateColumnHeaders(viewer);
settings.restoreColumnWidth(viewer);
viewer.setComparator(sorter);
viewer.setContentProvider(new CoveredElementsContentProvider(settings));
viewer.setInput(CoverageTools.getJavaModelCoverage());
getSite().setSelectionProvider(viewer);
selectiontracker = new SelectionTracker(this, viewer);
createHandlers();
createActions();
viewer.addOpenListener(new IOpenListener() {
public void open(OpenEvent event) {
openAction.run((IStructuredSelection) event.getSelection());
}
});
MenuManager menuMgr = new MenuManager("#PopupMenu"); //$NON-NLS-1$
menuMgr.setRemoveAllWhenShown(true);
tree.setMenu(menuMgr.createContextMenu(tree));
getSite().registerContextMenu(menuMgr, viewer);
CoverageTools.getSessionManager().addSessionListener(descriptionUpdater);
CoverageTools.addJavaCoverageListener(coverageListener);
}
|
diff --git a/main-src/net/minecraft/src/MAtProcessorFrequent.java b/main-src/net/minecraft/src/MAtProcessorFrequent.java
index 673c0f1..5465b7a 100644
--- a/main-src/net/minecraft/src/MAtProcessorFrequent.java
+++ b/main-src/net/minecraft/src/MAtProcessorFrequent.java
@@ -1,252 +1,252 @@
package net.minecraft.src;
import net.minecraft.client.Minecraft;
import eu.ha3.matmos.engine.Data;
/*
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
Version 2, December 2004
Copyright (C) 2004 Sam Hocevar <[email protected]>
Everyone is permitted to copy and distribute verbatim or modified
copies of this license document, and changing it is allowed as long
as the name is changed.
DO WHAT THE FUCK YOU WANT TO PUBLIC LICENSE
TERMS AND CONDITIONS FOR COPYING, DISTRIBUTION AND MODIFICATION
0. You just DO WHAT THE FUCK YOU WANT TO.
*/
public class MAtProcessorFrequent extends MAtProcessorModel
{
public MAtProcessorFrequent(MAtMod modIn, Data dataIn, String normalNameIn, String deltaNameIn)
{
super(modIn, dataIn, normalNameIn, deltaNameIn);
}
@Override
protected void doProcess()
{
Minecraft mc = mod().manager().getMinecraft();
World w = mc.theWorld;
WorldInfo worldinfo = w.worldInfo;
EntityPlayerSP player = mc.thePlayer;
int x = (int) Math.floor(player.posX);
int y = (int) Math.floor(player.posY);
int z = (int) Math.floor(player.posZ);
int mx = (int) Math.round(player.motionX * 1000);
int my = (int) Math.round(player.motionY * 1000);
int mz = (int) Math.round(player.motionZ * 1000);
// Get the Sky Light value
setValue(0, w.getSavedLightValue(EnumSkyBlock.Sky, x, y, z));
// Get the Artificial Light value
setValue(1, w.getSavedLightValue(EnumSkyBlock.Block, x, y, z));
// Get the Block Light value
setValue(2, w.getBlockLightValue(x, y, z));
// Get the World Time modulo 24KL
setValue(3, (int) (worldinfo.getWorldTime() % 24000L));
// Get the Altitude (Y)
setValue(4, y);
// 5 : (RELAXED)
// Get if Is in Water
setValue(6, player.isInWater() ? 1 : 0);
// Get if It's Raining
setValue(7, worldinfo.isRaining() ? 1 : 0);
// Get if It's Thundering (regardless of rain)
setValue(8, worldinfo.isThundering() ? 1 : 0);
// Get if the Current block player is on is exposed to the sky
setValue(9, w.canBlockSeeTheSky(x, y, z) ? 1 : 0);
// Get if Player is un the Nether
setValue(10, player.dimension == -1 ? 1 : 0);
// Get the Skylight level subtracted (the amount of light stripped from Skylight)
setValue(11, w.skylightSubtracted);
// [12,18] (RELAXED)
// Get if Player is inside of Water material
setValue(19, player.isWet() ? 1 : 0);
// Get if Player X (Floored (Double) Player X, casted into to Integer)
setValue(20, x);
// Get if Player Z (Floored (Double) Player Z, casted into to Integer)
setValue(21, z);
// Get if Player is on Ground
setValue(22, player.onGround ? 1 : 0);
// Get Player oxygen amount (Integer)
setValue(23, player.getAir());
// Get Player health amount (Integer)
setValue(24, player.health);
// Get Player dimension (Integer)
setValue(25, player.dimension);
setValue(26, w.canBlockSeeTheSky(x, y, z) && !(w.getTopSolidOrLiquidBlock(x, z) > y) ? 1 : 0);
setValue(27, w.getTopSolidOrLiquidBlock(x, z));
setValue(28, w.getTopSolidOrLiquidBlock(x, z) - y);
// [29,31] : (RELAXED)
setValue(32, player.inventory.getCurrentItem() != null ? player.inventory.getCurrentItem().itemID : -1);
//setValue( 32, player.getHeldItem() != null ? player.getHeldItem().itemID : -1 );
setValue(33, mx);
setValue(34, my);
setValue(35, mz);
setValue(
36, y >= 1 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y - 1, z)) : -1); //FIXME difference in Altitude notion
setValue(
37, y >= 2 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y - 2, z)) : -1); //FIXME difference in Altitude notion
setValue(38, (int) mod().util().getClientTick());
setValue(39, player.isBurning() ? 1 : 0); // XXX ERROR NOW IS A PRIVATE VALUE
setValue(40, (int) Math.floor(player.swingProgress * 16));
setValue(41, player.swingProgress != 0 ? 1 : 0); // is swinging
setValue(42, player.isJumping ? 1 : 0);
setValue(43, (int) (player.fallDistance * 1000));
setValue(44, player.isInWeb ? 1 : 0);
setValue(45, (int) Math.floor(Math.sqrt(mx * mx + mz * mz)));
setValue(46, player.inventory.currentItem);
setValue(47, mc.objectMouseOver != null ? 1 : 0);
setValue(48, mc.objectMouseOver != null ? mc.objectMouseOver.typeOfHit.ordinal() : -1);
setValue(49, player.isBurning() ? 1 : 0);
setValue(50, player.getTotalArmorValue());
setValue(51, player.foodStats.getFoodLevel()); //(getFoodStats())
setValue(52, (int) (player.foodStats.getSaturationLevel() * 1000)); //(getFoodStats())
setValue(53, 0); // TODO (Food Exhaustion Level)
setValue(54, player.experienceValue * 1000);
setValue(55, player.experienceLevel);
setValue(56, player.experienceTotal);
setValue(57, player.isOnLadder() ? 1 : 0);
setValue(58, player.getItemInUseDuration());
// ---- / --- // / / setValue( 59, player.inventory.func_35157_d(Item.arrow.shiftedIndex) ? 1 : 0);
setValue(59, 0);
setValue(60, player.isBlocking() ? 1 : 0);
setValue(61, 72000 - player.getItemInUseDuration());
setValue(62, player.inventory.getCurrentItem() == null ? -1 : player.inventory.getCurrentItem().getItemDamage());
setValue(63, player.isSprinting() ? 1 : 0);
setValue(64, player.isSneaking() ? 1 : 0);
setValue(65, player.isAirBorne ? 1 : 0);
setValue(66, player.isUsingItem() ? 1 : 0);
setValue(67, player.isRiding() ? 1 : 0);
- setValue(68, player.ridingEntity != null && player.ridingEntity.getClass() == EntityMinecart.class ? 1 : 0);
+ setValue(68, player.ridingEntity != null && player.ridingEntity.getClass() == EntityMinecartEmpty.class ? 1 : 0);
setValue(69, player.ridingEntity != null && player.ridingEntity.getClass() == EntityBoat.class ? 1 : 0);
setValue(70, mc.playerController != null && mc.playerController.isInCreativeMode() ? 1 : 0);
int rmx = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionX * 1000) : 0;
int rmy = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionY * 1000) : 0;
int rmz = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionZ * 1000) : 0;
setValue(71, rmx);
setValue(72, rmy);
setValue(73, rmz);
setValue(74, player.ridingEntity != null ? (int) Math.floor(Math.sqrt(rmx * rmx + rmz * rmz)) : 0);
// 75-85 relaxed server
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == EnumMovingObjectType.TILE)
{
setValue(86, w.getBlockId(mc.objectMouseOver.blockX, mc.objectMouseOver.blockY, mc.objectMouseOver.blockZ));
setValue(
87, w.getBlockMetadata(mc.objectMouseOver.blockX, mc.objectMouseOver.blockY, mc.objectMouseOver.blockZ));
}
else
{
setValue(86, 0);
setValue(87, 0);
}
// 88 - moon phase
setValue(89, player.inventory.armorInventory[0] != null ? player.inventory.armorInventory[0].itemID : -1);
setValue(90, player.inventory.armorInventory[1] != null ? player.inventory.armorInventory[1].itemID : -1);
setValue(91, player.inventory.armorInventory[2] != null ? player.inventory.armorInventory[2].itemID : -1);
setValue(92, player.inventory.armorInventory[3] != null ? player.inventory.armorInventory[3].itemID : -1);
// 93 - ME BiomeID
setValue(94, y >= 0 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y, z)) : -1); //FIXME difference in Altitude notion
setValue(
95,
y >= 0 && y < mod().util().getWorldHeight() - 1
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y + 1, z)) : -1);
//
/*
for (int i = 0; i < 64; i++)
{
setValue(100 + i, 0);
}
if (player.inventory.getCurrentItem() != null
&& player.inventory.getCurrentItem().getEnchantmentTagList() != null
&& player.inventory.getCurrentItem().getEnchantmentTagList().tagCount() > 0)
{
int total = player.inventory.getCurrentItem().getEnchantmentTagList().tagCount();
NBTTagList enchantments = player.inventory.getCurrentItem().getEnchantmentTagList();
for (int i = 0; i < total; i++)
{
short id = ((NBTTagCompound) enchantments.tagAt(i)).getShort("id");
short lvl = ((NBTTagCompound) enchantments.tagAt(i)).getShort("lvl");
if (id < 64 && i >= 0)
{
setValue(100 + id, lvl);
}
}
}*/
/*
for (int i = 0; i < 32; i++)
{
setValue(200 + i, 0);
}
for (Object oeffect : player.getActivePotionEffects())
{
PotionEffect effect = (PotionEffect) oeffect;
int id = effect.getPotionID();
if (id < 32 && id >= 0)
{
setValue(200 + id, 1 + effect.getAmplifier());
}
}*/
// Remember to increase the data size.
}
private int getTranslatedBlockId(int dataValue)
{
// XXX Crash prevention in case of data value system hack
if (dataValue < 0)
return 0;
if (dataValue >= MAtDataGatherer.COUNT_WORLD_BLOCKS)
return 0;
return dataValue;
}
}
| true | true | protected void doProcess()
{
Minecraft mc = mod().manager().getMinecraft();
World w = mc.theWorld;
WorldInfo worldinfo = w.worldInfo;
EntityPlayerSP player = mc.thePlayer;
int x = (int) Math.floor(player.posX);
int y = (int) Math.floor(player.posY);
int z = (int) Math.floor(player.posZ);
int mx = (int) Math.round(player.motionX * 1000);
int my = (int) Math.round(player.motionY * 1000);
int mz = (int) Math.round(player.motionZ * 1000);
// Get the Sky Light value
setValue(0, w.getSavedLightValue(EnumSkyBlock.Sky, x, y, z));
// Get the Artificial Light value
setValue(1, w.getSavedLightValue(EnumSkyBlock.Block, x, y, z));
// Get the Block Light value
setValue(2, w.getBlockLightValue(x, y, z));
// Get the World Time modulo 24KL
setValue(3, (int) (worldinfo.getWorldTime() % 24000L));
// Get the Altitude (Y)
setValue(4, y);
// 5 : (RELAXED)
// Get if Is in Water
setValue(6, player.isInWater() ? 1 : 0);
// Get if It's Raining
setValue(7, worldinfo.isRaining() ? 1 : 0);
// Get if It's Thundering (regardless of rain)
setValue(8, worldinfo.isThundering() ? 1 : 0);
// Get if the Current block player is on is exposed to the sky
setValue(9, w.canBlockSeeTheSky(x, y, z) ? 1 : 0);
// Get if Player is un the Nether
setValue(10, player.dimension == -1 ? 1 : 0);
// Get the Skylight level subtracted (the amount of light stripped from Skylight)
setValue(11, w.skylightSubtracted);
// [12,18] (RELAXED)
// Get if Player is inside of Water material
setValue(19, player.isWet() ? 1 : 0);
// Get if Player X (Floored (Double) Player X, casted into to Integer)
setValue(20, x);
// Get if Player Z (Floored (Double) Player Z, casted into to Integer)
setValue(21, z);
// Get if Player is on Ground
setValue(22, player.onGround ? 1 : 0);
// Get Player oxygen amount (Integer)
setValue(23, player.getAir());
// Get Player health amount (Integer)
setValue(24, player.health);
// Get Player dimension (Integer)
setValue(25, player.dimension);
setValue(26, w.canBlockSeeTheSky(x, y, z) && !(w.getTopSolidOrLiquidBlock(x, z) > y) ? 1 : 0);
setValue(27, w.getTopSolidOrLiquidBlock(x, z));
setValue(28, w.getTopSolidOrLiquidBlock(x, z) - y);
// [29,31] : (RELAXED)
setValue(32, player.inventory.getCurrentItem() != null ? player.inventory.getCurrentItem().itemID : -1);
//setValue( 32, player.getHeldItem() != null ? player.getHeldItem().itemID : -1 );
setValue(33, mx);
setValue(34, my);
setValue(35, mz);
setValue(
36, y >= 1 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y - 1, z)) : -1); //FIXME difference in Altitude notion
setValue(
37, y >= 2 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y - 2, z)) : -1); //FIXME difference in Altitude notion
setValue(38, (int) mod().util().getClientTick());
setValue(39, player.isBurning() ? 1 : 0); // XXX ERROR NOW IS A PRIVATE VALUE
setValue(40, (int) Math.floor(player.swingProgress * 16));
setValue(41, player.swingProgress != 0 ? 1 : 0); // is swinging
setValue(42, player.isJumping ? 1 : 0);
setValue(43, (int) (player.fallDistance * 1000));
setValue(44, player.isInWeb ? 1 : 0);
setValue(45, (int) Math.floor(Math.sqrt(mx * mx + mz * mz)));
setValue(46, player.inventory.currentItem);
setValue(47, mc.objectMouseOver != null ? 1 : 0);
setValue(48, mc.objectMouseOver != null ? mc.objectMouseOver.typeOfHit.ordinal() : -1);
setValue(49, player.isBurning() ? 1 : 0);
setValue(50, player.getTotalArmorValue());
setValue(51, player.foodStats.getFoodLevel()); //(getFoodStats())
setValue(52, (int) (player.foodStats.getSaturationLevel() * 1000)); //(getFoodStats())
setValue(53, 0); // TODO (Food Exhaustion Level)
setValue(54, player.experienceValue * 1000);
setValue(55, player.experienceLevel);
setValue(56, player.experienceTotal);
setValue(57, player.isOnLadder() ? 1 : 0);
setValue(58, player.getItemInUseDuration());
// ---- / --- // / / setValue( 59, player.inventory.func_35157_d(Item.arrow.shiftedIndex) ? 1 : 0);
setValue(59, 0);
setValue(60, player.isBlocking() ? 1 : 0);
setValue(61, 72000 - player.getItemInUseDuration());
setValue(62, player.inventory.getCurrentItem() == null ? -1 : player.inventory.getCurrentItem().getItemDamage());
setValue(63, player.isSprinting() ? 1 : 0);
setValue(64, player.isSneaking() ? 1 : 0);
setValue(65, player.isAirBorne ? 1 : 0);
setValue(66, player.isUsingItem() ? 1 : 0);
setValue(67, player.isRiding() ? 1 : 0);
setValue(68, player.ridingEntity != null && player.ridingEntity.getClass() == EntityMinecart.class ? 1 : 0);
setValue(69, player.ridingEntity != null && player.ridingEntity.getClass() == EntityBoat.class ? 1 : 0);
setValue(70, mc.playerController != null && mc.playerController.isInCreativeMode() ? 1 : 0);
int rmx = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionX * 1000) : 0;
int rmy = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionY * 1000) : 0;
int rmz = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionZ * 1000) : 0;
setValue(71, rmx);
setValue(72, rmy);
setValue(73, rmz);
setValue(74, player.ridingEntity != null ? (int) Math.floor(Math.sqrt(rmx * rmx + rmz * rmz)) : 0);
// 75-85 relaxed server
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == EnumMovingObjectType.TILE)
{
setValue(86, w.getBlockId(mc.objectMouseOver.blockX, mc.objectMouseOver.blockY, mc.objectMouseOver.blockZ));
setValue(
87, w.getBlockMetadata(mc.objectMouseOver.blockX, mc.objectMouseOver.blockY, mc.objectMouseOver.blockZ));
}
else
{
setValue(86, 0);
setValue(87, 0);
}
// 88 - moon phase
setValue(89, player.inventory.armorInventory[0] != null ? player.inventory.armorInventory[0].itemID : -1);
setValue(90, player.inventory.armorInventory[1] != null ? player.inventory.armorInventory[1].itemID : -1);
setValue(91, player.inventory.armorInventory[2] != null ? player.inventory.armorInventory[2].itemID : -1);
setValue(92, player.inventory.armorInventory[3] != null ? player.inventory.armorInventory[3].itemID : -1);
// 93 - ME BiomeID
setValue(94, y >= 0 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y, z)) : -1); //FIXME difference in Altitude notion
setValue(
95,
y >= 0 && y < mod().util().getWorldHeight() - 1
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y + 1, z)) : -1);
//
/*
for (int i = 0; i < 64; i++)
{
setValue(100 + i, 0);
}
if (player.inventory.getCurrentItem() != null
&& player.inventory.getCurrentItem().getEnchantmentTagList() != null
&& player.inventory.getCurrentItem().getEnchantmentTagList().tagCount() > 0)
{
int total = player.inventory.getCurrentItem().getEnchantmentTagList().tagCount();
NBTTagList enchantments = player.inventory.getCurrentItem().getEnchantmentTagList();
for (int i = 0; i < total; i++)
{
short id = ((NBTTagCompound) enchantments.tagAt(i)).getShort("id");
short lvl = ((NBTTagCompound) enchantments.tagAt(i)).getShort("lvl");
if (id < 64 && i >= 0)
{
setValue(100 + id, lvl);
}
}
}*/
/*
for (int i = 0; i < 32; i++)
{
setValue(200 + i, 0);
}
for (Object oeffect : player.getActivePotionEffects())
{
PotionEffect effect = (PotionEffect) oeffect;
int id = effect.getPotionID();
if (id < 32 && id >= 0)
{
setValue(200 + id, 1 + effect.getAmplifier());
}
}*/
// Remember to increase the data size.
}
| protected void doProcess()
{
Minecraft mc = mod().manager().getMinecraft();
World w = mc.theWorld;
WorldInfo worldinfo = w.worldInfo;
EntityPlayerSP player = mc.thePlayer;
int x = (int) Math.floor(player.posX);
int y = (int) Math.floor(player.posY);
int z = (int) Math.floor(player.posZ);
int mx = (int) Math.round(player.motionX * 1000);
int my = (int) Math.round(player.motionY * 1000);
int mz = (int) Math.round(player.motionZ * 1000);
// Get the Sky Light value
setValue(0, w.getSavedLightValue(EnumSkyBlock.Sky, x, y, z));
// Get the Artificial Light value
setValue(1, w.getSavedLightValue(EnumSkyBlock.Block, x, y, z));
// Get the Block Light value
setValue(2, w.getBlockLightValue(x, y, z));
// Get the World Time modulo 24KL
setValue(3, (int) (worldinfo.getWorldTime() % 24000L));
// Get the Altitude (Y)
setValue(4, y);
// 5 : (RELAXED)
// Get if Is in Water
setValue(6, player.isInWater() ? 1 : 0);
// Get if It's Raining
setValue(7, worldinfo.isRaining() ? 1 : 0);
// Get if It's Thundering (regardless of rain)
setValue(8, worldinfo.isThundering() ? 1 : 0);
// Get if the Current block player is on is exposed to the sky
setValue(9, w.canBlockSeeTheSky(x, y, z) ? 1 : 0);
// Get if Player is un the Nether
setValue(10, player.dimension == -1 ? 1 : 0);
// Get the Skylight level subtracted (the amount of light stripped from Skylight)
setValue(11, w.skylightSubtracted);
// [12,18] (RELAXED)
// Get if Player is inside of Water material
setValue(19, player.isWet() ? 1 : 0);
// Get if Player X (Floored (Double) Player X, casted into to Integer)
setValue(20, x);
// Get if Player Z (Floored (Double) Player Z, casted into to Integer)
setValue(21, z);
// Get if Player is on Ground
setValue(22, player.onGround ? 1 : 0);
// Get Player oxygen amount (Integer)
setValue(23, player.getAir());
// Get Player health amount (Integer)
setValue(24, player.health);
// Get Player dimension (Integer)
setValue(25, player.dimension);
setValue(26, w.canBlockSeeTheSky(x, y, z) && !(w.getTopSolidOrLiquidBlock(x, z) > y) ? 1 : 0);
setValue(27, w.getTopSolidOrLiquidBlock(x, z));
setValue(28, w.getTopSolidOrLiquidBlock(x, z) - y);
// [29,31] : (RELAXED)
setValue(32, player.inventory.getCurrentItem() != null ? player.inventory.getCurrentItem().itemID : -1);
//setValue( 32, player.getHeldItem() != null ? player.getHeldItem().itemID : -1 );
setValue(33, mx);
setValue(34, my);
setValue(35, mz);
setValue(
36, y >= 1 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y - 1, z)) : -1); //FIXME difference in Altitude notion
setValue(
37, y >= 2 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y - 2, z)) : -1); //FIXME difference in Altitude notion
setValue(38, (int) mod().util().getClientTick());
setValue(39, player.isBurning() ? 1 : 0); // XXX ERROR NOW IS A PRIVATE VALUE
setValue(40, (int) Math.floor(player.swingProgress * 16));
setValue(41, player.swingProgress != 0 ? 1 : 0); // is swinging
setValue(42, player.isJumping ? 1 : 0);
setValue(43, (int) (player.fallDistance * 1000));
setValue(44, player.isInWeb ? 1 : 0);
setValue(45, (int) Math.floor(Math.sqrt(mx * mx + mz * mz)));
setValue(46, player.inventory.currentItem);
setValue(47, mc.objectMouseOver != null ? 1 : 0);
setValue(48, mc.objectMouseOver != null ? mc.objectMouseOver.typeOfHit.ordinal() : -1);
setValue(49, player.isBurning() ? 1 : 0);
setValue(50, player.getTotalArmorValue());
setValue(51, player.foodStats.getFoodLevel()); //(getFoodStats())
setValue(52, (int) (player.foodStats.getSaturationLevel() * 1000)); //(getFoodStats())
setValue(53, 0); // TODO (Food Exhaustion Level)
setValue(54, player.experienceValue * 1000);
setValue(55, player.experienceLevel);
setValue(56, player.experienceTotal);
setValue(57, player.isOnLadder() ? 1 : 0);
setValue(58, player.getItemInUseDuration());
// ---- / --- // / / setValue( 59, player.inventory.func_35157_d(Item.arrow.shiftedIndex) ? 1 : 0);
setValue(59, 0);
setValue(60, player.isBlocking() ? 1 : 0);
setValue(61, 72000 - player.getItemInUseDuration());
setValue(62, player.inventory.getCurrentItem() == null ? -1 : player.inventory.getCurrentItem().getItemDamage());
setValue(63, player.isSprinting() ? 1 : 0);
setValue(64, player.isSneaking() ? 1 : 0);
setValue(65, player.isAirBorne ? 1 : 0);
setValue(66, player.isUsingItem() ? 1 : 0);
setValue(67, player.isRiding() ? 1 : 0);
setValue(68, player.ridingEntity != null && player.ridingEntity.getClass() == EntityMinecartEmpty.class ? 1 : 0);
setValue(69, player.ridingEntity != null && player.ridingEntity.getClass() == EntityBoat.class ? 1 : 0);
setValue(70, mc.playerController != null && mc.playerController.isInCreativeMode() ? 1 : 0);
int rmx = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionX * 1000) : 0;
int rmy = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionY * 1000) : 0;
int rmz = player.ridingEntity != null ? (int) Math.round(player.ridingEntity.motionZ * 1000) : 0;
setValue(71, rmx);
setValue(72, rmy);
setValue(73, rmz);
setValue(74, player.ridingEntity != null ? (int) Math.floor(Math.sqrt(rmx * rmx + rmz * rmz)) : 0);
// 75-85 relaxed server
if (mc.objectMouseOver != null && mc.objectMouseOver.typeOfHit == EnumMovingObjectType.TILE)
{
setValue(86, w.getBlockId(mc.objectMouseOver.blockX, mc.objectMouseOver.blockY, mc.objectMouseOver.blockZ));
setValue(
87, w.getBlockMetadata(mc.objectMouseOver.blockX, mc.objectMouseOver.blockY, mc.objectMouseOver.blockZ));
}
else
{
setValue(86, 0);
setValue(87, 0);
}
// 88 - moon phase
setValue(89, player.inventory.armorInventory[0] != null ? player.inventory.armorInventory[0].itemID : -1);
setValue(90, player.inventory.armorInventory[1] != null ? player.inventory.armorInventory[1].itemID : -1);
setValue(91, player.inventory.armorInventory[2] != null ? player.inventory.armorInventory[2].itemID : -1);
setValue(92, player.inventory.armorInventory[3] != null ? player.inventory.armorInventory[3].itemID : -1);
// 93 - ME BiomeID
setValue(94, y >= 0 && y < mod().util().getWorldHeight()
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y, z)) : -1); //FIXME difference in Altitude notion
setValue(
95,
y >= 0 && y < mod().util().getWorldHeight() - 1
? getTranslatedBlockId(mc.theWorld.getBlockId(x, y + 1, z)) : -1);
//
/*
for (int i = 0; i < 64; i++)
{
setValue(100 + i, 0);
}
if (player.inventory.getCurrentItem() != null
&& player.inventory.getCurrentItem().getEnchantmentTagList() != null
&& player.inventory.getCurrentItem().getEnchantmentTagList().tagCount() > 0)
{
int total = player.inventory.getCurrentItem().getEnchantmentTagList().tagCount();
NBTTagList enchantments = player.inventory.getCurrentItem().getEnchantmentTagList();
for (int i = 0; i < total; i++)
{
short id = ((NBTTagCompound) enchantments.tagAt(i)).getShort("id");
short lvl = ((NBTTagCompound) enchantments.tagAt(i)).getShort("lvl");
if (id < 64 && i >= 0)
{
setValue(100 + id, lvl);
}
}
}*/
/*
for (int i = 0; i < 32; i++)
{
setValue(200 + i, 0);
}
for (Object oeffect : player.getActivePotionEffects())
{
PotionEffect effect = (PotionEffect) oeffect;
int id = effect.getPotionID();
if (id < 32 && id >= 0)
{
setValue(200 + id, 1 + effect.getAmplifier());
}
}*/
// Remember to increase the data size.
}
|
diff --git a/src/xmlvm/org/xmlvm/proc/out/OutputProcessFactory.java b/src/xmlvm/org/xmlvm/proc/out/OutputProcessFactory.java
index 840ef2dc..50eee34f 100755
--- a/src/xmlvm/org/xmlvm/proc/out/OutputProcessFactory.java
+++ b/src/xmlvm/org/xmlvm/proc/out/OutputProcessFactory.java
@@ -1,85 +1,85 @@
/*
* Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language
*
* 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., 675 Mass
* Ave, Cambridge, MA 02139, USA.
*
* For more information, visit the XMLVM Home Page at http://www.xmlvm.org
*/
package org.xmlvm.proc.out;
import org.xmlvm.Log;
import org.xmlvm.main.Arguments;
import org.xmlvm.main.Targets;
import org.xmlvm.proc.XmlvmProcess;
/**
* Creates OutputProcess based on the given targets.
*/
public class OutputProcessFactory {
/**
* The arguments that should be given to the created processes.
*/
protected Arguments arguments;
/**
* Creates a new OutputProcessFactory
*
* @param arguments
* The arguments that should be given to the created processes.
*/
public OutputProcessFactory(Arguments arguments) {
this.arguments = arguments;
}
/**
* Based on the given target, returns a suitable target process or null, if
* no process could be found.
*/
public XmlvmProcess<?> createTargetProcess(Targets target, String out) {
switch (target) {
case JS:
return new JavaScriptOutputProcess(arguments);
case PYTHON:
return new PythonOutputProcess(arguments);
case CPP:
return new CppOutputProcess(arguments);
case OBJC:
return new ObjectiveCOutputProcess(arguments);
case QOOXDOO:
return new QooxdooOutputProcess(arguments);
case IPHONE:
return new IPhoneOutputProcess(arguments);
case IPHONEANDROID:
return new Android2IPhoneOutputProcess(arguments);
case WEBOS:
- return new Android2IPhoneOutputProcess(arguments);
+ return new Android2PalmPreOutputProcess(arguments);
case XMLVM:
return new XmlvmOutputProcess(arguments);
case IPHONETEMPLATE:
return new TemplateOutputProcess(arguments);
case CLASS:
return new JavaByteCodeOutputProcess(arguments);
case EXE:
return new CILByteCodeOutputProcess(arguments);
case DEX:
return new DexOutputProcess(arguments);
case DEXMLVM:
return new DEXmlvmOutputProcess(arguments);
}
Log.error("Could not create target process for target '" + target + "'.");
return null;
}
}
| true | true | public XmlvmProcess<?> createTargetProcess(Targets target, String out) {
switch (target) {
case JS:
return new JavaScriptOutputProcess(arguments);
case PYTHON:
return new PythonOutputProcess(arguments);
case CPP:
return new CppOutputProcess(arguments);
case OBJC:
return new ObjectiveCOutputProcess(arguments);
case QOOXDOO:
return new QooxdooOutputProcess(arguments);
case IPHONE:
return new IPhoneOutputProcess(arguments);
case IPHONEANDROID:
return new Android2IPhoneOutputProcess(arguments);
case WEBOS:
return new Android2IPhoneOutputProcess(arguments);
case XMLVM:
return new XmlvmOutputProcess(arguments);
case IPHONETEMPLATE:
return new TemplateOutputProcess(arguments);
case CLASS:
return new JavaByteCodeOutputProcess(arguments);
case EXE:
return new CILByteCodeOutputProcess(arguments);
case DEX:
return new DexOutputProcess(arguments);
case DEXMLVM:
return new DEXmlvmOutputProcess(arguments);
}
Log.error("Could not create target process for target '" + target + "'.");
return null;
}
| public XmlvmProcess<?> createTargetProcess(Targets target, String out) {
switch (target) {
case JS:
return new JavaScriptOutputProcess(arguments);
case PYTHON:
return new PythonOutputProcess(arguments);
case CPP:
return new CppOutputProcess(arguments);
case OBJC:
return new ObjectiveCOutputProcess(arguments);
case QOOXDOO:
return new QooxdooOutputProcess(arguments);
case IPHONE:
return new IPhoneOutputProcess(arguments);
case IPHONEANDROID:
return new Android2IPhoneOutputProcess(arguments);
case WEBOS:
return new Android2PalmPreOutputProcess(arguments);
case XMLVM:
return new XmlvmOutputProcess(arguments);
case IPHONETEMPLATE:
return new TemplateOutputProcess(arguments);
case CLASS:
return new JavaByteCodeOutputProcess(arguments);
case EXE:
return new CILByteCodeOutputProcess(arguments);
case DEX:
return new DexOutputProcess(arguments);
case DEXMLVM:
return new DEXmlvmOutputProcess(arguments);
}
Log.error("Could not create target process for target '" + target + "'.");
return null;
}
|
diff --git a/java/src/org/broadinstitute/sting/gatk/walkers/indels/ConstrainedMateFixingManager.java b/java/src/org/broadinstitute/sting/gatk/walkers/indels/ConstrainedMateFixingManager.java
index 75ca976e8..d3e61092c 100755
--- a/java/src/org/broadinstitute/sting/gatk/walkers/indels/ConstrainedMateFixingManager.java
+++ b/java/src/org/broadinstitute/sting/gatk/walkers/indels/ConstrainedMateFixingManager.java
@@ -1,288 +1,288 @@
package org.broadinstitute.sting.gatk.walkers.indels;
import net.sf.picard.sam.SamPairUtil;
import net.sf.samtools.*;
import org.apache.log4j.Logger;
import org.broadinstitute.sting.utils.GenomeLoc;
import org.broadinstitute.sting.utils.GenomeLocParser;
import org.broadinstitute.sting.utils.exceptions.UserException;
import java.util.HashMap;
import java.util.PriorityQueue;
import java.util.Queue;
/*
* Copyright (c) 2009 The Broad Institute
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use,
* copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the
* Software is furnished to do so, subject to the following
* conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
* OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
* HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
* WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
*/
/**
* A locally resorting, mate fixing sam file writer that supports an idiom where reads are only moved around if
* the ISIZE of the pair is < X and reads are not allowed to move any more than Y bp from their original positions.
*
* To understand this data structure, let's begin by asking -- when are we certain we know the position of read R added
* to the writer and its mate M given that R has been added to the writer (but M may not be), their ISIZE in R, at the
* moment that a read K is added to the writer, under the constraints X and Y? Complex I know. First, because
* reads cannot move more than Y bp in either direction, we know that R originated at most R.pos + Y bp from its
* current position. Also, we know that K is at most K.pos + Y bp from it's original position. If R is maximally
* shifted to the right, and K shifted to the left, then they could at most move 2Y together. So if the distance
* between R and K > 2Y, we know that there are no reads left in the original stream that could be moved before R.
*
* Now, we also need to be certain if we have a mate pair M, that won't emit R before we can incorporate any move of
* M into the mate pair info R. There are two cases to consider here:
*
* If ISIZE > X, we know that we won't move M when we see it, so we can safely emit R knowing that
* M is fixed in place.
*
* If ISIZE <= X, M might be moved, and it we have to wait until we see M in the stream to know it's position.
* So R must be buffered until either M arrives, or we see a read K that's more than 2Y units past the original position
* of M.
*
* So the worst-case memory consumption here is proportional to the number of reads
* occurring between R and M + 2 Y, and so is proportional to the depth of the data and X and Y.
*
* This leads to the following simple algorithm:
*
* addAlignment(newRead):
* addReadToListOfReads(newRead)
* update mate pair of newRead if present in list of reads
*
* for ( read in list of reads [in order of increasing read.pos] ):
* if read.pos < newRead.pos - 2Y && (read.isize >= X || read.matePos < newRead.pos - 2 * Y):
* emit read and remove from list of reads
* else:
* break
*
* @author depristo, ebanks
* @version 0.2
*/
public class ConstrainedMateFixingManager {
protected static final Logger logger = Logger.getLogger(ConstrainedMateFixingManager.class);
private static final boolean DEBUG = false;
/** How often do we check whether we want to emit reads? */
private final static int EMIT_FREQUENCY = 1000;
/**
* How much could a single read move in position from its original position?
*/
final int MAX_POS_MOVE_ALLOWED;
/**
* How many reads should we store in memory before flushing the queue?
*/
final int MAX_RECORDS_IN_MEMORY;
/** how we order our SAM records */
private final SAMRecordComparator comparer = new SAMRecordCoordinateComparator();
/** The place where we ultimately write out our records */
final SAMFileWriter writer;
/**
* what is the maximum isize of a pair of reads that can move? Reads with isize > this value
* are assumes to not be allowed to move in the incoming read stream.
*/
final int maxInsertSizeForMovingReadPairs;
final GenomeLocParser genomeLocParser;
private GenomeLoc lastLocFlushed = null;
int counter = 0;
/** read.name -> records */
HashMap<String, SAMRecord> forMateMatching = new HashMap<String, SAMRecord>();
Queue<SAMRecord> waitingReads = new PriorityQueue<SAMRecord>(1000, comparer);
//private SimpleTimer timer = new SimpleTimer("ConstrainedWriter");
//private long PROGRESS_PRINT_FREQUENCY = 10 * 1000; // in milliseconds
//private long lastProgressPrintTime = -1; // When was the last time we printed progress log?
/**
*
* @param writer actual writer
* @param genomeLocParser the GenomeLocParser object
* @param maxInsertSizeForMovingReadPairs max insert size allowed for moving pairs
* @param maxMoveAllowed max positional move allowed for any read
* @param maxRecordsInMemory max records to keep in memory
*/
public ConstrainedMateFixingManager(final SAMFileWriter writer,
final GenomeLocParser genomeLocParser,
final int maxInsertSizeForMovingReadPairs,
final int maxMoveAllowed,
final int maxRecordsInMemory) {
this.writer = writer;
this.genomeLocParser = genomeLocParser;
this.maxInsertSizeForMovingReadPairs = maxInsertSizeForMovingReadPairs;
this.MAX_POS_MOVE_ALLOWED = maxMoveAllowed;
this.MAX_RECORDS_IN_MEMORY = maxRecordsInMemory;
//timer.start();
//lastProgressPrintTime = timer.currentTime();
}
public int getNReadsInQueue() { return waitingReads.size(); }
public boolean canMoveReads(GenomeLoc earliestPosition) {
if ( DEBUG ) logger.info("Refusing to realign? " + earliestPosition + " vs. " + lastLocFlushed);
return lastLocFlushed == null ||
lastLocFlushed.compareContigs(earliestPosition) != 0 ||
lastLocFlushed.distance(earliestPosition) > maxInsertSizeForMovingReadPairs;
}
private boolean noReadCanMoveBefore(int pos, SAMRecord addedRead) {
return pos + 2 * MAX_POS_MOVE_ALLOWED < addedRead.getAlignmentStart();
}
private void writeRead(SAMRecord read) {
try {
writer.addAlignment(read);
} catch (IllegalArgumentException e) {
throw new UserException("If the maximum allowable reads in memory is too small, it may cause reads to be written out of order when trying to write the BAM; please see the --maxReadsInMemory argument for details. " + e.getMessage(), e);
}
}
public void addRead( SAMRecord newRead ) {
if ( DEBUG ) logger.info("New read pos " + newRead.getAlignmentStart() + " OP = " + newRead.getAttribute("OP"));
//final long curTime = timer.currentTime();
//if ( curTime - lastProgressPrintTime > PROGRESS_PRINT_FREQUENCY ) {
// lastProgressPrintTime = curTime;
// System.out.println("WaitingReads.size = " + waitingReads.size() + ", forMateMatching.size = " + forMateMatching.size());
//}
// if the new read is on a different contig or we have too many reads, then we need to flush the queue and clear the map
boolean tooManyReads = getNReadsInQueue() >= MAX_RECORDS_IN_MEMORY;
- if ( tooManyReads || (getNReadsInQueue() > 0 && waitingReads.peek().getReferenceIndex() != newRead.getReferenceIndex()) ) {
+ if ( tooManyReads || (getNReadsInQueue() > 0 && !waitingReads.peek().getReferenceIndex().equals(newRead.getReferenceIndex())) ) {
if ( DEBUG ) logger.warn("Flushing queue on " + (tooManyReads ? "too many reads" : ("move to new contig: " + newRead.getReferenceName() + " from " + waitingReads.peek().getReferenceName())) + " at " + newRead.getAlignmentStart());
while ( getNReadsInQueue() > 1 ) {
// emit to disk
writeRead(waitingReads.remove());
}
SAMRecord lastRead = waitingReads.remove();
lastLocFlushed = (lastRead.getReferenceIndex() == -1) ? null : genomeLocParser.createGenomeLoc(lastRead);
writeRead(lastRead);
if ( !tooManyReads )
forMateMatching.clear();
}
// fix mates, as needed
// Since setMateInfo can move reads, we potentially need to remove the mate, and requeue
// it to ensure proper sorting
if ( newRead.getReadPairedFlag() ) {
SAMRecord mate = forMateMatching.get(newRead.getReadName());
if ( mate != null ) {
// 1. Frustratingly, Picard's setMateInfo() method unaligns (by setting the reference contig
// to '*') read pairs when both of their flags have the unmapped bit set. This is problematic
// when trying to emit reads in coordinate order because all of a sudden we have reads in the
// middle of the bam file that now belong at the end - and any mapped reads that get emitted
// after them trigger an exception in the writer. For our purposes, because we shouldn't be
// moving read pairs when they are both unmapped anyways, we'll just not run fix mates on them.
// 2. Furthermore, when reads get mapped to the junction of two chromosomes (e.g. MT since it
// is actually circular DNA), their unmapped bit is set, but they are given legitimate coordinates.
// The Picard code will come in and move the read all the way back to its mate (which can be
// arbitrarily far away). However, we do still want to move legitimately unmapped reads whose
// mates are mapped, so the compromise will be that if the mate is still in the queue then we'll
// move the read and otherwise we won't.
boolean doNotFixMates = newRead.getReadUnmappedFlag() && (mate.getReadUnmappedFlag() || !waitingReads.contains(mate));
if ( !doNotFixMates ) {
boolean reQueueMate = mate.getReadUnmappedFlag() && ! newRead.getReadUnmappedFlag();
if ( reQueueMate ) {
// the mate was unmapped, but newRead was mapped, so the mate may have been moved
// to be next-to newRead, so needs to be reinserted into the waitingReads queue
// note -- this must be called before the setMateInfo call below
if ( ! waitingReads.remove(mate) )
// we must have hit a region with too much depth and flushed the queue
reQueueMate = false;
}
// we've already seen our mate -- set the mate info and remove it from the map
SamPairUtil.setMateInfo(mate, newRead, null);
if ( reQueueMate ) waitingReads.add(mate);
}
forMateMatching.remove(newRead.getReadName());
} else {
forMateMatching.put(newRead.getReadName(), newRead);
}
}
waitingReads.add(newRead);
if ( ++counter % EMIT_FREQUENCY == 0 ) {
while ( ! waitingReads.isEmpty() ) { // there's something in the queue
SAMRecord read = waitingReads.peek();
if ( noReadCanMoveBefore(read.getAlignmentStart(), newRead) &&
(iSizeTooBigToMove(read) // we won't try to move such a read
|| ! read.getReadPairedFlag() // we're not a paired read
|| read.getReadUnmappedFlag() && read.getMateUnmappedFlag() // both reads are unmapped
|| noReadCanMoveBefore(read.getMateAlignmentStart(), newRead ) ) ) { // we're already past where the mate started
// remove reads from the map that we have emitted -- useful for case where the mate never showed up
forMateMatching.remove(read.getReadName());
if ( DEBUG )
logger.warn(String.format("EMIT! At %d: read %s at %d with isize %d, mate start %d, op = %s",
newRead.getAlignmentStart(), read.getReadName(), read.getAlignmentStart(),
read.getInferredInsertSize(), read.getMateAlignmentStart(), read.getAttribute("OP")));
// emit to disk
writeRead(waitingReads.remove());
} else {
if ( DEBUG )
logger.warn(String.format("At %d: read %s at %d with isize %d couldn't be emited, mate start %d",
newRead.getAlignmentStart(), read.getReadName(), read.getAlignmentStart(), read.getInferredInsertSize(), read.getMateAlignmentStart()));
break;
}
}
if ( DEBUG ) logger.warn(String.format("At %d: Done with emit cycle", newRead.getAlignmentStart()));
}
}
/**
* @param read the read
* @return true if the read shouldn't be moved given the constraints of this SAMFileWriter
*/
public boolean iSizeTooBigToMove(SAMRecord read) {
return iSizeTooBigToMove(read, maxInsertSizeForMovingReadPairs); // we won't try to move such a read
}
public static boolean iSizeTooBigToMove(SAMRecord read, int maxInsertSizeForMovingReadPairs) {
return ( read.getReadPairedFlag() && ! read.getMateUnmappedFlag() && read.getReferenceName() != read.getMateReferenceName() ) // maps to different chromosomes
|| Math.abs(read.getInferredInsertSize()) > maxInsertSizeForMovingReadPairs; // we won't try to move such a read
}
public void close() {
// write out all of the remaining reads
while ( ! waitingReads.isEmpty() ) { // there's something in the queue
writeRead(waitingReads.remove());
}
}
}
| true | true | public void addRead( SAMRecord newRead ) {
if ( DEBUG ) logger.info("New read pos " + newRead.getAlignmentStart() + " OP = " + newRead.getAttribute("OP"));
//final long curTime = timer.currentTime();
//if ( curTime - lastProgressPrintTime > PROGRESS_PRINT_FREQUENCY ) {
// lastProgressPrintTime = curTime;
// System.out.println("WaitingReads.size = " + waitingReads.size() + ", forMateMatching.size = " + forMateMatching.size());
//}
// if the new read is on a different contig or we have too many reads, then we need to flush the queue and clear the map
boolean tooManyReads = getNReadsInQueue() >= MAX_RECORDS_IN_MEMORY;
if ( tooManyReads || (getNReadsInQueue() > 0 && waitingReads.peek().getReferenceIndex() != newRead.getReferenceIndex()) ) {
if ( DEBUG ) logger.warn("Flushing queue on " + (tooManyReads ? "too many reads" : ("move to new contig: " + newRead.getReferenceName() + " from " + waitingReads.peek().getReferenceName())) + " at " + newRead.getAlignmentStart());
while ( getNReadsInQueue() > 1 ) {
// emit to disk
writeRead(waitingReads.remove());
}
SAMRecord lastRead = waitingReads.remove();
lastLocFlushed = (lastRead.getReferenceIndex() == -1) ? null : genomeLocParser.createGenomeLoc(lastRead);
writeRead(lastRead);
if ( !tooManyReads )
forMateMatching.clear();
}
// fix mates, as needed
// Since setMateInfo can move reads, we potentially need to remove the mate, and requeue
// it to ensure proper sorting
if ( newRead.getReadPairedFlag() ) {
SAMRecord mate = forMateMatching.get(newRead.getReadName());
if ( mate != null ) {
// 1. Frustratingly, Picard's setMateInfo() method unaligns (by setting the reference contig
// to '*') read pairs when both of their flags have the unmapped bit set. This is problematic
// when trying to emit reads in coordinate order because all of a sudden we have reads in the
// middle of the bam file that now belong at the end - and any mapped reads that get emitted
// after them trigger an exception in the writer. For our purposes, because we shouldn't be
// moving read pairs when they are both unmapped anyways, we'll just not run fix mates on them.
// 2. Furthermore, when reads get mapped to the junction of two chromosomes (e.g. MT since it
// is actually circular DNA), their unmapped bit is set, but they are given legitimate coordinates.
// The Picard code will come in and move the read all the way back to its mate (which can be
// arbitrarily far away). However, we do still want to move legitimately unmapped reads whose
// mates are mapped, so the compromise will be that if the mate is still in the queue then we'll
// move the read and otherwise we won't.
boolean doNotFixMates = newRead.getReadUnmappedFlag() && (mate.getReadUnmappedFlag() || !waitingReads.contains(mate));
if ( !doNotFixMates ) {
boolean reQueueMate = mate.getReadUnmappedFlag() && ! newRead.getReadUnmappedFlag();
if ( reQueueMate ) {
// the mate was unmapped, but newRead was mapped, so the mate may have been moved
// to be next-to newRead, so needs to be reinserted into the waitingReads queue
// note -- this must be called before the setMateInfo call below
if ( ! waitingReads.remove(mate) )
// we must have hit a region with too much depth and flushed the queue
reQueueMate = false;
}
// we've already seen our mate -- set the mate info and remove it from the map
SamPairUtil.setMateInfo(mate, newRead, null);
if ( reQueueMate ) waitingReads.add(mate);
}
forMateMatching.remove(newRead.getReadName());
} else {
forMateMatching.put(newRead.getReadName(), newRead);
}
}
waitingReads.add(newRead);
if ( ++counter % EMIT_FREQUENCY == 0 ) {
while ( ! waitingReads.isEmpty() ) { // there's something in the queue
SAMRecord read = waitingReads.peek();
if ( noReadCanMoveBefore(read.getAlignmentStart(), newRead) &&
(iSizeTooBigToMove(read) // we won't try to move such a read
|| ! read.getReadPairedFlag() // we're not a paired read
|| read.getReadUnmappedFlag() && read.getMateUnmappedFlag() // both reads are unmapped
|| noReadCanMoveBefore(read.getMateAlignmentStart(), newRead ) ) ) { // we're already past where the mate started
// remove reads from the map that we have emitted -- useful for case where the mate never showed up
forMateMatching.remove(read.getReadName());
if ( DEBUG )
logger.warn(String.format("EMIT! At %d: read %s at %d with isize %d, mate start %d, op = %s",
newRead.getAlignmentStart(), read.getReadName(), read.getAlignmentStart(),
read.getInferredInsertSize(), read.getMateAlignmentStart(), read.getAttribute("OP")));
// emit to disk
writeRead(waitingReads.remove());
} else {
if ( DEBUG )
logger.warn(String.format("At %d: read %s at %d with isize %d couldn't be emited, mate start %d",
newRead.getAlignmentStart(), read.getReadName(), read.getAlignmentStart(), read.getInferredInsertSize(), read.getMateAlignmentStart()));
break;
}
}
if ( DEBUG ) logger.warn(String.format("At %d: Done with emit cycle", newRead.getAlignmentStart()));
}
}
| public void addRead( SAMRecord newRead ) {
if ( DEBUG ) logger.info("New read pos " + newRead.getAlignmentStart() + " OP = " + newRead.getAttribute("OP"));
//final long curTime = timer.currentTime();
//if ( curTime - lastProgressPrintTime > PROGRESS_PRINT_FREQUENCY ) {
// lastProgressPrintTime = curTime;
// System.out.println("WaitingReads.size = " + waitingReads.size() + ", forMateMatching.size = " + forMateMatching.size());
//}
// if the new read is on a different contig or we have too many reads, then we need to flush the queue and clear the map
boolean tooManyReads = getNReadsInQueue() >= MAX_RECORDS_IN_MEMORY;
if ( tooManyReads || (getNReadsInQueue() > 0 && !waitingReads.peek().getReferenceIndex().equals(newRead.getReferenceIndex())) ) {
if ( DEBUG ) logger.warn("Flushing queue on " + (tooManyReads ? "too many reads" : ("move to new contig: " + newRead.getReferenceName() + " from " + waitingReads.peek().getReferenceName())) + " at " + newRead.getAlignmentStart());
while ( getNReadsInQueue() > 1 ) {
// emit to disk
writeRead(waitingReads.remove());
}
SAMRecord lastRead = waitingReads.remove();
lastLocFlushed = (lastRead.getReferenceIndex() == -1) ? null : genomeLocParser.createGenomeLoc(lastRead);
writeRead(lastRead);
if ( !tooManyReads )
forMateMatching.clear();
}
// fix mates, as needed
// Since setMateInfo can move reads, we potentially need to remove the mate, and requeue
// it to ensure proper sorting
if ( newRead.getReadPairedFlag() ) {
SAMRecord mate = forMateMatching.get(newRead.getReadName());
if ( mate != null ) {
// 1. Frustratingly, Picard's setMateInfo() method unaligns (by setting the reference contig
// to '*') read pairs when both of their flags have the unmapped bit set. This is problematic
// when trying to emit reads in coordinate order because all of a sudden we have reads in the
// middle of the bam file that now belong at the end - and any mapped reads that get emitted
// after them trigger an exception in the writer. For our purposes, because we shouldn't be
// moving read pairs when they are both unmapped anyways, we'll just not run fix mates on them.
// 2. Furthermore, when reads get mapped to the junction of two chromosomes (e.g. MT since it
// is actually circular DNA), their unmapped bit is set, but they are given legitimate coordinates.
// The Picard code will come in and move the read all the way back to its mate (which can be
// arbitrarily far away). However, we do still want to move legitimately unmapped reads whose
// mates are mapped, so the compromise will be that if the mate is still in the queue then we'll
// move the read and otherwise we won't.
boolean doNotFixMates = newRead.getReadUnmappedFlag() && (mate.getReadUnmappedFlag() || !waitingReads.contains(mate));
if ( !doNotFixMates ) {
boolean reQueueMate = mate.getReadUnmappedFlag() && ! newRead.getReadUnmappedFlag();
if ( reQueueMate ) {
// the mate was unmapped, but newRead was mapped, so the mate may have been moved
// to be next-to newRead, so needs to be reinserted into the waitingReads queue
// note -- this must be called before the setMateInfo call below
if ( ! waitingReads.remove(mate) )
// we must have hit a region with too much depth and flushed the queue
reQueueMate = false;
}
// we've already seen our mate -- set the mate info and remove it from the map
SamPairUtil.setMateInfo(mate, newRead, null);
if ( reQueueMate ) waitingReads.add(mate);
}
forMateMatching.remove(newRead.getReadName());
} else {
forMateMatching.put(newRead.getReadName(), newRead);
}
}
waitingReads.add(newRead);
if ( ++counter % EMIT_FREQUENCY == 0 ) {
while ( ! waitingReads.isEmpty() ) { // there's something in the queue
SAMRecord read = waitingReads.peek();
if ( noReadCanMoveBefore(read.getAlignmentStart(), newRead) &&
(iSizeTooBigToMove(read) // we won't try to move such a read
|| ! read.getReadPairedFlag() // we're not a paired read
|| read.getReadUnmappedFlag() && read.getMateUnmappedFlag() // both reads are unmapped
|| noReadCanMoveBefore(read.getMateAlignmentStart(), newRead ) ) ) { // we're already past where the mate started
// remove reads from the map that we have emitted -- useful for case where the mate never showed up
forMateMatching.remove(read.getReadName());
if ( DEBUG )
logger.warn(String.format("EMIT! At %d: read %s at %d with isize %d, mate start %d, op = %s",
newRead.getAlignmentStart(), read.getReadName(), read.getAlignmentStart(),
read.getInferredInsertSize(), read.getMateAlignmentStart(), read.getAttribute("OP")));
// emit to disk
writeRead(waitingReads.remove());
} else {
if ( DEBUG )
logger.warn(String.format("At %d: read %s at %d with isize %d couldn't be emited, mate start %d",
newRead.getAlignmentStart(), read.getReadName(), read.getAlignmentStart(), read.getInferredInsertSize(), read.getMateAlignmentStart()));
break;
}
}
if ( DEBUG ) logger.warn(String.format("At %d: Done with emit cycle", newRead.getAlignmentStart()));
}
}
|
diff --git a/src/org/broad/igv/tools/CoverageCounter.java b/src/org/broad/igv/tools/CoverageCounter.java
index c6e68e8c1..958f163da 100644
--- a/src/org/broad/igv/tools/CoverageCounter.java
+++ b/src/org/broad/igv/tools/CoverageCounter.java
@@ -1,772 +1,772 @@
/*
* Copyright (c) 2007-2011 by The Broad Institute of MIT and Harvard. All Rights Reserved.
*
* This software is licensed under the terms of the GNU Lesser General Public License (LGPL),
* Version 2.1 which is available at http://www.opensource.org/licenses/lgpl-2.1.php.
*
* THE SOFTWARE IS PROVIDED "AS IS." THE BROAD AND MIT MAKE NO REPRESENTATIONS OR
* WARRANTES OF ANY KIND CONCERNING THE SOFTWARE, EXPRESS OR IMPLIED, INCLUDING,
* WITHOUT LIMITATION, WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR
* PURPOSE, NONINFRINGEMENT, OR THE ABSENCE OF LATENT OR OTHER DEFECTS, WHETHER
* OR NOT DISCOVERABLE. IN NO EVENT SHALL THE BROAD OR MIT, OR THEIR RESPECTIVE
* TRUSTEES, DIRECTORS, OFFICERS, EMPLOYEES, AND AFFILIATES BE LIABLE FOR ANY DAMAGES
* OF ANY KIND, INCLUDING, WITHOUT LIMITATION, INCIDENTAL OR CONSEQUENTIAL DAMAGES,
* ECONOMIC DAMAGES OR INJURY TO PROPERTY AND LOST PROFITS, REGARDLESS OF WHETHER
* THE BROAD OR MIT SHALL BE ADVISED, SHALL HAVE OTHER REASON TO KNOW, OR IN FACT
* SHALL KNOW OF THE POSSIBILITY OF THE FOREGOING.
*/
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package org.broad.igv.tools;
import net.sf.samtools.util.CloseableIterator;
import org.broad.igv.feature.Chromosome;
import org.broad.igv.feature.Locus;
import org.broad.igv.feature.Strand;
import org.broad.igv.feature.genome.Genome;
import org.broad.igv.sam.Alignment;
import org.broad.igv.sam.AlignmentBlock;
import org.broad.igv.sam.ReadMate;
import org.broad.igv.sam.reader.AlignmentReader;
import org.broad.igv.sam.reader.AlignmentReaderFactory;
import org.broad.igv.tools.parsers.DataConsumer;
import java.io.File;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.*;
/**
* Class to compute coverage on an alignment or feature file. This class is designed to be instantiated and executed
* from a single thread.
*/
public class CoverageCounter {
/**
* The path to the alignment file being counted.
*/
private String alignmentFile;
/**
* A consumer of data produced by this class, normally a TDF Preprocessor.
*/
private DataConsumer consumer;
/**
* Window size in base pairs. Genome is divided into non-overlapping windows of this size. The counts reported
* are averages over the window.
*/
private int windowSize = 1;
/**
* Minimum mapping quality. Alignments with MQ less than this value are filtered.
*/
private int minMappingQuality = 0;
/*
* Output data from each strand separately (as opposed to combining them)
* using the read strand.
*/
static final int STRANDS_BY_READ = 0x01;
/*
* Output strand data separately by first-in-pair
*/
static final int STRANDS_BY_FIRST_IN_PAIR = 0x02;
/**
* Output strand data separately by second-in-pair
*/
static final int STRANDS_BY_SECOND_IN_PAIR = 0x04;
/**
* Output counts of each base. Whether the data will be output
* for each strand separately is determined by STRAND_SEPARATE
* by
*/
static final int BASES = 0x08;
public static final int INCLUDE_DUPS = 0x20;
public static final int PAIRED_COVERAGE = 0x40;
private boolean outputSeparate;
private boolean firstInPair;
private boolean secondInPair;
private boolean outputBases;
private static final int[] output_strands = new int[]{0, 1};
public static final int NUM_STRANDS = output_strands.length;
/**
* Extension factor. Reads are extended by this amount from the 3' end before counting. The purpose is to yield
* an approximate count of fragment "coverage", as opposed to read coverage. If used, the value should be set to
* extFactor = averageFragmentSize - averageReadLength
*/
private int extFactor;
/**
* 5' "pre" extension factor. Read is extended by this amount from the 5' end of the read
*/
private int preExtFactor;
/**
* 5' "post" extension factor. Essentially, replace actual read length by this amount.
*/
private int postExtFactor;
/**
* Flag to control treatment of duplicates. If true duplicates are counted. The default value is false.
*/
private boolean includeDuplicates = false;
/**
* If true, coverage is computed based from properly paired reads, counting entire insert.
*/
private boolean pairedCoverage = false;
private Genome genome;
/**
* Optional wig file specifier. If non-null, a "wiggle" file is created in addition to the TDF file.
*/
private File wigFile = null;
/**
* Total number of alignments that pass filters and are counted.
*/
private int totalCount = 0;
/**
* The query interval, usually this is null but can be used to restrict the interval of the alignment file that is
* computed. The file must be indexed (queryable) if this is not null
*/
private Locus queryInterval;
/**
* Data buffer to pass data to the "consumer" (preprocessor).
*/
private float[] buffer;
private boolean computeTDF = true;
private final static Set<Byte> nucleotidesKeep = new HashSet<Byte>();
private final static byte[] nucleotides = new byte[]{'A', 'C', 'G', 'T', 'N'};
static {
for (byte b : nucleotides) {
nucleotidesKeep.add(b);
}
}
/**
* @param alignmentFile - path to the file to count
* @param consumer - the data consumer, in this case a TDF preprocessor
* @param windowSize - window size in bp, counts are performed over this window
* @param extFactor - the extension factor, read is artificially extended by this amount
* @param wigFile - path to the wig file (optional)
* @param genome - the Genome, used to size chromosomes
* @param queryString - Locus query string, such as 1:1-1000. Only count the queried region. Set to null for entire genome
* @param minMapQual - Minimum mapping quality to include
* @param countFlags - Combination of flags for BASES, STRAND_SEPARATE, INCLUDE_DUPES, FIRST_IN_PAIR
*/
public CoverageCounter(String alignmentFile,
DataConsumer consumer,
int windowSize,
int extFactor,
File wigFile,
Genome genome,
String queryString,
int minMapQual,
int countFlags) {
this.alignmentFile = alignmentFile;
this.consumer = consumer;
this.windowSize = windowSize;
this.extFactor = extFactor;
this.wigFile = wigFile;
this.genome = genome;
parseOptions(queryString, minMapQual, countFlags);
//Count the number of output columns. 1 or 2 if not outputting bases
//5 or 10 if are.
int multiplier = outputBases ? 5 : 1;
int datacols = (outputSeparate ? 2 : 1) * multiplier;
buffer = new float[datacols];
}
public void setPreExtFactor(int preExtFactor) {
this.preExtFactor = preExtFactor;
}
public void setPosExtFactor(int postExtFactor) {
this.postExtFactor = postExtFactor;
}
/**
* Take additional optional command line arguments and parse them
*
* @param queryString
* @param minMapQual
* @param countFlags
*/
private void parseOptions(String queryString, int minMapQual, int countFlags) {
if (queryString != null) {
this.queryInterval = new Locus(queryString);
}
this.minMappingQuality = minMapQual;
outputSeparate = (countFlags & STRANDS_BY_READ) > 0;
firstInPair = (countFlags & STRANDS_BY_FIRST_IN_PAIR) > 0;
secondInPair = (countFlags & STRANDS_BY_SECOND_IN_PAIR) > 0;
outputSeparate |= firstInPair || secondInPair;
if (firstInPair && secondInPair) {
throw new IllegalArgumentException("Can't set both first and second in pair");
}
outputBases = (countFlags & BASES) > 0;
includeDuplicates = (countFlags & INCLUDE_DUPS) > 0;
pairedCoverage = (countFlags & PAIRED_COVERAGE) > 0;
}
// TODO -- command-line options to override all of these checks
private boolean passFilter(Alignment alignment) {
// If the first-in-pair or second-in-pair option is selected test that we have that information, otherwise
// alignment is filtered.
boolean pairingInfo = (!firstInPair && !secondInPair) ||
(alignment.getFirstOfPairStrand() != Strand.NONE);
// For paired coverage, see if the alignment is properly paired, and if it is the "leftmost" alignment
// (to prevent double-counting the pair).
if (pairedCoverage) {
ReadMate mate = alignment.getMate();
if (!alignment.isProperPair() || alignment.getMate() == null || alignment.getStart() > mate.getStart()) {
return false;
}
if (Math.abs(alignment.getInferredInsertSize()) > 10000) {
System.out.println("Very large insert size: " + Math.abs(alignment.getInferredInsertSize()) +
" for read " + alignment.getReadName() + ". Skipped.");
return false;
}
}
return alignment.isMapped() && pairingInfo &&
(includeDuplicates || !alignment.isDuplicate()) &&
alignment.getMappingQuality() >= minMappingQuality &&
!alignment.isVendorFailedRead();
}
/**
* Parse and "count" the alignment file. The main method.
* <p/>
* This method is not thread safe due to the use of the member variable "buffer".
*
* @throws IOException
*/
public synchronized void parse() throws IOException {
int maxExtFactor = Math.max(extFactor, Math.max(preExtFactor, postExtFactor));
int tolerance = (int) (windowSize * (Math.floor(maxExtFactor / windowSize) + 2));
consumer.setSortTolerance(tolerance);
AlignmentReader reader = null;
CloseableIterator<Alignment> iter = null;
String lastChr = "";
ReadCounter counter = null;
WigWriter wigWriter = null;
if (wigFile != null) {
wigWriter = new WigWriter(wigFile, windowSize);
}
try {
if (queryInterval == null) {
reader = AlignmentReaderFactory.getReader(alignmentFile, false);
iter = reader.iterator();
} else {
reader = AlignmentReaderFactory.getReader(alignmentFile, true);
iter = reader.query(queryInterval.getChr(), queryInterval.getStart() - 1, queryInterval.getEnd(), false);
}
while (iter != null && iter.hasNext()) {
Alignment alignment = iter.next();
if (passFilter(alignment)) {
//Sort into the read strand or first-in-pair strand,
//depending on input flag. Note that this can
//be very unreliable depending on data
Strand strand;
if (firstInPair) {
strand = alignment.getFirstOfPairStrand();
} else if (secondInPair) {
strand = alignment.getSecondOfPairStrand();
} else {
strand = alignment.getReadStrand();
}
if (strand.equals(Strand.NONE)) {
//TODO move this into passFilter, or move passFilter here
continue;
}
boolean readNegStrand = alignment.isNegativeStrand();
totalCount++;
String alignmentChr = alignment.getChr();
// Close all counters with position < alignment.getStart()
if (alignmentChr.equals(lastChr)) {
if (counter != null) {
counter.closeBucketsBefore(alignment.getAlignmentStart() - tolerance, wigWriter);
}
} else { // New chromosome
if (counter != null) {
counter.closeBucketsBefore(Integer.MAX_VALUE, wigWriter);
}
counter = new ReadCounter(alignmentChr);
lastChr = alignmentChr;
}
AlignmentBlock[] blocks = alignment.getAlignmentBlocks();
if (blocks != null && !pairedCoverage) {
int lastBlockEnd = -1;
for (AlignmentBlock block : blocks) {
if (!block.isSoftClipped()) {
byte[] bases = block.getBases();
int blockStart = block.getStart();
int blockEnd = block.getEnd();
int adjustedStart = block.getStart();
int adjustedEnd = block.getEnd();
if (preExtFactor > 0) {
if (readNegStrand) {
adjustedEnd = blockEnd + preExtFactor;
} else {
adjustedStart = Math.max(0, blockStart - preExtFactor);
}
}
// If both postExtFactor and extFactor are specified, postExtFactor takes precedence
if (postExtFactor > 0) {
if (readNegStrand) {
- adjustedStart = Math.max(0, blockStart - postExtFactor);
+ adjustedStart = Math.max(0, blockEnd - postExtFactor);
} else {
- adjustedEnd = blockEnd + postExtFactor;
+ adjustedEnd = blockStart + postExtFactor;
}
} else if (extFactor > 0) {
// Standard extension option -- extend read on 3' end
if (readNegStrand) {
adjustedStart = Math.max(0, adjustedStart - extFactor);
} else {
adjustedEnd += extFactor;
}
}
if (queryInterval != null) {
adjustedStart = Math.max(queryInterval.getStart() - 1, adjustedStart);
adjustedEnd = Math.min(queryInterval.getEnd(), adjustedEnd);
}
for (int pos = adjustedStart; pos < adjustedEnd; pos++) {
byte base = 0;
int baseIdx = pos - blockStart;
if (bases != null && baseIdx >= 0 && baseIdx < bases.length) {
base = bases[baseIdx];
}
int idx = pos - blockStart;
byte quality = (idx >= 0 && idx < block.qualities.length) ?
block.qualities[pos - blockStart] : (byte) 0;
counter.incrementCount(pos, base, quality, strand);
}
lastBlockEnd = block.getEnd();
}
}
} else {
int adjustedStart = alignment.getAlignmentStart();
int adjustedEnd = pairedCoverage ?
adjustedStart + Math.abs(alignment.getInferredInsertSize()) :
alignment.getAlignmentEnd();
if (readNegStrand) {
adjustedStart = Math.max(0, adjustedStart - extFactor);
} else {
adjustedEnd += extFactor;
}
if (queryInterval != null) {
adjustedStart = Math.max(queryInterval.getStart() - 1, adjustedStart);
adjustedEnd = Math.min(queryInterval.getEnd(), adjustedEnd);
}
for (int pos = adjustedStart; pos < adjustedEnd; pos++) {
counter.incrementCount(pos, (byte) 'N', (byte) 0, strand);
}
}
}
}
consumer.setAttribute("totalCount", String.valueOf(totalCount));
consumer.parsingComplete();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (counter != null) {
counter.closeBucketsBefore(Integer.MAX_VALUE, wigWriter);
}
if (iter != null) {
iter.close();
}
if (reader != null) {
reader.close();
}
if (wigWriter != null) {
wigWriter.close();
}
}
}
/**
* The names of tracks which will be created by this parser
*
* @param prefix String to be prepended to each track name
* @return
*/
public String[] getTrackNames(String prefix) {
if (prefix == null) {
prefix = "";
}
String[] trackNames = new String[this.buffer.length];
String[] strandArr;
if (outputSeparate) {
strandArr = new String[]{"Positive Strand", "Negative Strand"};
} else {
strandArr = new String[]{"Combined Strands"};
}
int col = 0;
for (String sA : strandArr) {
if (outputBases) {
for (Byte n : nucleotides) {
trackNames[col] = prefix + " " + sA + " " + new String(new byte[]{n});
col++;
}
} else {
trackNames[col] = prefix + " " + sA;
col++;
}
}
return trackNames;
}
class ReadCounter {
String chr;
/**
* Map of window index -> counter
*/
TreeMap<Integer, Counter> counts = new TreeMap();
ReadCounter(String chr) {
this.chr = chr;
}
/**
* @param position - genomic position
* @param base - nucleotide
* @param quality - base quality of call
* @param strand - which strand to increment count. Should be POSITIVE or NEGATIVE
*/
void incrementCount(int position, byte base, byte quality, Strand strand) {
final Counter counter = getCounterForPosition(position);
int strandNum = strand.equals(Strand.POSITIVE) ? 0 : 1;
counter.increment(base, quality, strandNum);
}
private Counter getCounterForPosition(int position) {
int idx = position / windowSize;
return getCounter(idx);
}
private Counter getCounter(int idx) {
if (!counts.containsKey(idx)) {
counts.put(idx, new Counter());
}
final Counter counter = counts.get(idx);
return counter;
}
/**
* Close (finalize) all buckets before the given position. Called when we are sure this position will not be
* visited again.
*
* @param position - genomic position
*/
void closeBucketsBefore(int position, WigWriter wigWriter) {
List<Integer> bucketsToClose = new ArrayList();
int bucket = position / windowSize;
for (Map.Entry<Integer, Counter> entry : counts.entrySet()) {
if (entry.getKey() < bucket) {
// Divide total count by window size. This is the average count per
// base over the window, so for example 30x coverage remains 30x irrespective of window size.
int bucketStartPosition = entry.getKey() * windowSize;
int bucketEndPosition = bucketStartPosition + windowSize;
if (genome != null) {
Chromosome chromosome = genome.getChromosome(chr);
if (chromosome != null) {
bucketEndPosition = Math.min(bucketEndPosition, chromosome.getLength());
}
}
int bucketSize = bucketEndPosition - bucketStartPosition;
final Counter counter = entry.getValue();
int col = 0;
//Not outputting base info, just totals
if (!outputBases) {
if (outputSeparate) {
//Output strand specific information, if applicable
for (int strandNum : output_strands) {
buffer[col] = ((float) counter.getCount(strandNum)) / bucketSize;
col++;
}
} else {
buffer[col] = ((float) counter.getTotalCounts()) / bucketSize;
col++;
}
//Output counts of each base
} else {
if (outputSeparate) {
for (int strandNum : output_strands) {
for (byte base : nucleotides) {
buffer[col] = ((float) counter.getBaseCount(base, strandNum)) / bucketSize;
col++;
}
}
} else {
for (byte base : nucleotides) {
buffer[col] = ((float) counter.getBaseCount(base)) / bucketSize;
col++;
}
}
}
consumer.addData(chr, bucketStartPosition, bucketEndPosition, buffer, null);
if (wigWriter != null) {
wigWriter.addData(chr, bucketStartPosition, bucketEndPosition, buffer);
}
bucketsToClose.add(entry.getKey());
}
}
for (Integer key : bucketsToClose) {
counts.remove(key);
}
}
}
/**
* Class for counting nucleotides and strands over an interval.
*/
class Counter {
/**
* The total number of counts on this Counter. Will
* be the sum of baseCount over the second index.
*/
int[] strandCount;
int totalCount = 0;
//int qualityCount = 0;
//String chr;
//int start;
//int end;
//byte[] ref;
/**
* The number of times a particular base has been encountered (ie # of reads of that base)
*/
//int[][] baseCount = new int[NUM_STRANDS][];
private Map<Byte, Integer>[] baseTypeCounts;
Counter() {
//this.chr = chr;
//this.start = start;
//this.end = end;
if (outputBases) {
baseTypeCounts = new HashMap[NUM_STRANDS];
for (int ii = 0; ii < NUM_STRANDS; ii++) {
baseTypeCounts[ii] = new HashMap<Byte, Integer>();
}
}
if (outputSeparate) {
strandCount = new int[NUM_STRANDS];
}
}
int getCount(int strand) {
return strandCount[strand];
}
public int getTotalCounts() {
return totalCount;
}
void increment(byte base, byte quality, int strand) {
if (outputBases) {
incrementNucleotide(base, strand);
}
if (outputSeparate) {
this.strandCount[strand]++;
}
this.totalCount++;
//this.qualityCount += quality;
}
/**
* Increment the nucleotide counts.
*
* @param base 65, 67, 71, 84, 78
* aka A, C, G, T, N (upper case).
* Anything else is stored as 0
* @param strand index of strand, 0 for positive and 1 for negative
*/
private void incrementNucleotide(byte base, int strand) {
Map<Byte, Integer> btc = baseTypeCounts[strand];
if (!nucleotidesKeep.contains(base)) {
base = 0;
}
int orig = 0;
if (btc.containsKey(base)) {
orig = btc.get(base);
}
btc.put(base, orig + 1);
}
public int getBaseCount(byte base, int strand) {
return baseTypeCounts[strand].containsKey(base) ? baseTypeCounts[strand].get(base) : 0;
}
public int getBaseCount(byte base) {
int count = 0;
for (int strand = 0; strand < NUM_STRANDS; strand++) {
count += getBaseCount(base, strand);
}
return count;
}
}
/**
* Creates a vary step wig file
*/
class WigWriter {
String lastChr = null;
int lastPosition = 0;
int step;
int span;
PrintWriter pw;
WigWriter(File file, int step) throws IOException {
this.step = step;
this.span = step;
pw = new PrintWriter(new FileWriter(file));
}
public void addData(String chr, int start, int end, float[] data) {
for (int i = 0; i < data.length; i++) {
if (Float.isNaN(data[i])) {
return;
}
}
if (genome.getChromosome(chr) == null) {
return;
}
if (end <= start) { // Not sure why or how this could happen
return;
}
int dataSpan = end - start;
if (chr == null || !chr.equals(lastChr) || dataSpan != span) {
span = dataSpan;
outputHeader(chr, start + 1);
}
pw.print(start + 1);
for (int i = 0; i < data.length; i++) {
pw.print("\t" + data[i]);
}
pw.println();
lastPosition = start;
lastChr = chr;
}
private void close() {
pw.close();
}
private void outputHeader(String chr, int start) {
//Write label column
String labels = "Pos";
for (String s : getTrackNames("")) {
labels += "," + s;
}
pw.println("#Columns: " + labels);
pw.println("variableStep chrom=" + chr + " span=" + span);
}
}
}
| false | true | public synchronized void parse() throws IOException {
int maxExtFactor = Math.max(extFactor, Math.max(preExtFactor, postExtFactor));
int tolerance = (int) (windowSize * (Math.floor(maxExtFactor / windowSize) + 2));
consumer.setSortTolerance(tolerance);
AlignmentReader reader = null;
CloseableIterator<Alignment> iter = null;
String lastChr = "";
ReadCounter counter = null;
WigWriter wigWriter = null;
if (wigFile != null) {
wigWriter = new WigWriter(wigFile, windowSize);
}
try {
if (queryInterval == null) {
reader = AlignmentReaderFactory.getReader(alignmentFile, false);
iter = reader.iterator();
} else {
reader = AlignmentReaderFactory.getReader(alignmentFile, true);
iter = reader.query(queryInterval.getChr(), queryInterval.getStart() - 1, queryInterval.getEnd(), false);
}
while (iter != null && iter.hasNext()) {
Alignment alignment = iter.next();
if (passFilter(alignment)) {
//Sort into the read strand or first-in-pair strand,
//depending on input flag. Note that this can
//be very unreliable depending on data
Strand strand;
if (firstInPair) {
strand = alignment.getFirstOfPairStrand();
} else if (secondInPair) {
strand = alignment.getSecondOfPairStrand();
} else {
strand = alignment.getReadStrand();
}
if (strand.equals(Strand.NONE)) {
//TODO move this into passFilter, or move passFilter here
continue;
}
boolean readNegStrand = alignment.isNegativeStrand();
totalCount++;
String alignmentChr = alignment.getChr();
// Close all counters with position < alignment.getStart()
if (alignmentChr.equals(lastChr)) {
if (counter != null) {
counter.closeBucketsBefore(alignment.getAlignmentStart() - tolerance, wigWriter);
}
} else { // New chromosome
if (counter != null) {
counter.closeBucketsBefore(Integer.MAX_VALUE, wigWriter);
}
counter = new ReadCounter(alignmentChr);
lastChr = alignmentChr;
}
AlignmentBlock[] blocks = alignment.getAlignmentBlocks();
if (blocks != null && !pairedCoverage) {
int lastBlockEnd = -1;
for (AlignmentBlock block : blocks) {
if (!block.isSoftClipped()) {
byte[] bases = block.getBases();
int blockStart = block.getStart();
int blockEnd = block.getEnd();
int adjustedStart = block.getStart();
int adjustedEnd = block.getEnd();
if (preExtFactor > 0) {
if (readNegStrand) {
adjustedEnd = blockEnd + preExtFactor;
} else {
adjustedStart = Math.max(0, blockStart - preExtFactor);
}
}
// If both postExtFactor and extFactor are specified, postExtFactor takes precedence
if (postExtFactor > 0) {
if (readNegStrand) {
adjustedStart = Math.max(0, blockStart - postExtFactor);
} else {
adjustedEnd = blockEnd + postExtFactor;
}
} else if (extFactor > 0) {
// Standard extension option -- extend read on 3' end
if (readNegStrand) {
adjustedStart = Math.max(0, adjustedStart - extFactor);
} else {
adjustedEnd += extFactor;
}
}
if (queryInterval != null) {
adjustedStart = Math.max(queryInterval.getStart() - 1, adjustedStart);
adjustedEnd = Math.min(queryInterval.getEnd(), adjustedEnd);
}
for (int pos = adjustedStart; pos < adjustedEnd; pos++) {
byte base = 0;
int baseIdx = pos - blockStart;
if (bases != null && baseIdx >= 0 && baseIdx < bases.length) {
base = bases[baseIdx];
}
int idx = pos - blockStart;
byte quality = (idx >= 0 && idx < block.qualities.length) ?
block.qualities[pos - blockStart] : (byte) 0;
counter.incrementCount(pos, base, quality, strand);
}
lastBlockEnd = block.getEnd();
}
}
} else {
int adjustedStart = alignment.getAlignmentStart();
int adjustedEnd = pairedCoverage ?
adjustedStart + Math.abs(alignment.getInferredInsertSize()) :
alignment.getAlignmentEnd();
if (readNegStrand) {
adjustedStart = Math.max(0, adjustedStart - extFactor);
} else {
adjustedEnd += extFactor;
}
if (queryInterval != null) {
adjustedStart = Math.max(queryInterval.getStart() - 1, adjustedStart);
adjustedEnd = Math.min(queryInterval.getEnd(), adjustedEnd);
}
for (int pos = adjustedStart; pos < adjustedEnd; pos++) {
counter.incrementCount(pos, (byte) 'N', (byte) 0, strand);
}
}
}
}
consumer.setAttribute("totalCount", String.valueOf(totalCount));
consumer.parsingComplete();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (counter != null) {
counter.closeBucketsBefore(Integer.MAX_VALUE, wigWriter);
}
if (iter != null) {
iter.close();
}
if (reader != null) {
reader.close();
}
if (wigWriter != null) {
wigWriter.close();
}
}
}
| public synchronized void parse() throws IOException {
int maxExtFactor = Math.max(extFactor, Math.max(preExtFactor, postExtFactor));
int tolerance = (int) (windowSize * (Math.floor(maxExtFactor / windowSize) + 2));
consumer.setSortTolerance(tolerance);
AlignmentReader reader = null;
CloseableIterator<Alignment> iter = null;
String lastChr = "";
ReadCounter counter = null;
WigWriter wigWriter = null;
if (wigFile != null) {
wigWriter = new WigWriter(wigFile, windowSize);
}
try {
if (queryInterval == null) {
reader = AlignmentReaderFactory.getReader(alignmentFile, false);
iter = reader.iterator();
} else {
reader = AlignmentReaderFactory.getReader(alignmentFile, true);
iter = reader.query(queryInterval.getChr(), queryInterval.getStart() - 1, queryInterval.getEnd(), false);
}
while (iter != null && iter.hasNext()) {
Alignment alignment = iter.next();
if (passFilter(alignment)) {
//Sort into the read strand or first-in-pair strand,
//depending on input flag. Note that this can
//be very unreliable depending on data
Strand strand;
if (firstInPair) {
strand = alignment.getFirstOfPairStrand();
} else if (secondInPair) {
strand = alignment.getSecondOfPairStrand();
} else {
strand = alignment.getReadStrand();
}
if (strand.equals(Strand.NONE)) {
//TODO move this into passFilter, or move passFilter here
continue;
}
boolean readNegStrand = alignment.isNegativeStrand();
totalCount++;
String alignmentChr = alignment.getChr();
// Close all counters with position < alignment.getStart()
if (alignmentChr.equals(lastChr)) {
if (counter != null) {
counter.closeBucketsBefore(alignment.getAlignmentStart() - tolerance, wigWriter);
}
} else { // New chromosome
if (counter != null) {
counter.closeBucketsBefore(Integer.MAX_VALUE, wigWriter);
}
counter = new ReadCounter(alignmentChr);
lastChr = alignmentChr;
}
AlignmentBlock[] blocks = alignment.getAlignmentBlocks();
if (blocks != null && !pairedCoverage) {
int lastBlockEnd = -1;
for (AlignmentBlock block : blocks) {
if (!block.isSoftClipped()) {
byte[] bases = block.getBases();
int blockStart = block.getStart();
int blockEnd = block.getEnd();
int adjustedStart = block.getStart();
int adjustedEnd = block.getEnd();
if (preExtFactor > 0) {
if (readNegStrand) {
adjustedEnd = blockEnd + preExtFactor;
} else {
adjustedStart = Math.max(0, blockStart - preExtFactor);
}
}
// If both postExtFactor and extFactor are specified, postExtFactor takes precedence
if (postExtFactor > 0) {
if (readNegStrand) {
adjustedStart = Math.max(0, blockEnd - postExtFactor);
} else {
adjustedEnd = blockStart + postExtFactor;
}
} else if (extFactor > 0) {
// Standard extension option -- extend read on 3' end
if (readNegStrand) {
adjustedStart = Math.max(0, adjustedStart - extFactor);
} else {
adjustedEnd += extFactor;
}
}
if (queryInterval != null) {
adjustedStart = Math.max(queryInterval.getStart() - 1, adjustedStart);
adjustedEnd = Math.min(queryInterval.getEnd(), adjustedEnd);
}
for (int pos = adjustedStart; pos < adjustedEnd; pos++) {
byte base = 0;
int baseIdx = pos - blockStart;
if (bases != null && baseIdx >= 0 && baseIdx < bases.length) {
base = bases[baseIdx];
}
int idx = pos - blockStart;
byte quality = (idx >= 0 && idx < block.qualities.length) ?
block.qualities[pos - blockStart] : (byte) 0;
counter.incrementCount(pos, base, quality, strand);
}
lastBlockEnd = block.getEnd();
}
}
} else {
int adjustedStart = alignment.getAlignmentStart();
int adjustedEnd = pairedCoverage ?
adjustedStart + Math.abs(alignment.getInferredInsertSize()) :
alignment.getAlignmentEnd();
if (readNegStrand) {
adjustedStart = Math.max(0, adjustedStart - extFactor);
} else {
adjustedEnd += extFactor;
}
if (queryInterval != null) {
adjustedStart = Math.max(queryInterval.getStart() - 1, adjustedStart);
adjustedEnd = Math.min(queryInterval.getEnd(), adjustedEnd);
}
for (int pos = adjustedStart; pos < adjustedEnd; pos++) {
counter.incrementCount(pos, (byte) 'N', (byte) 0, strand);
}
}
}
}
consumer.setAttribute("totalCount", String.valueOf(totalCount));
consumer.parsingComplete();
} catch (Exception e) {
e.printStackTrace();
} finally {
if (counter != null) {
counter.closeBucketsBefore(Integer.MAX_VALUE, wigWriter);
}
if (iter != null) {
iter.close();
}
if (reader != null) {
reader.close();
}
if (wigWriter != null) {
wigWriter.close();
}
}
}
|
diff --git a/src/main/java/com/onarandombox/MultiverseNetherPortals/listeners/MVNPPlayerListener.java b/src/main/java/com/onarandombox/MultiverseNetherPortals/listeners/MVNPPlayerListener.java
index 7fe46fc..43dc863 100644
--- a/src/main/java/com/onarandombox/MultiverseNetherPortals/listeners/MVNPPlayerListener.java
+++ b/src/main/java/com/onarandombox/MultiverseNetherPortals/listeners/MVNPPlayerListener.java
@@ -1,102 +1,103 @@
package com.onarandombox.MultiverseNetherPortals.listeners;
import com.onarandombox.MultiverseCore.api.MVWorldManager;
import com.onarandombox.MultiverseCore.api.MultiverseWorld;
import com.onarandombox.MultiverseCore.utils.PermissionTools;
import com.onarandombox.MultiverseNetherPortals.MultiverseNetherPortals;
import com.onarandombox.MultiverseNetherPortals.enums.PortalType;
import com.onarandombox.MultiverseNetherPortals.utils.MVLinkChecker;
import com.onarandombox.MultiverseNetherPortals.utils.MVNameChecker;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.player.PlayerPortalEvent;
import java.util.logging.Level;
public class MVNPPlayerListener implements Listener {
private MultiverseNetherPortals plugin;
private MVNameChecker nameChecker;
private MVLinkChecker linkChecker;
private MVWorldManager worldManager;
private PermissionTools pt;
public MVNPPlayerListener(MultiverseNetherPortals plugin) {
this.plugin = plugin;
this.nameChecker = new MVNameChecker(plugin);
this.worldManager = this.plugin.getCore().getMVWorldManager();
this.pt = new PermissionTools(this.plugin.getCore());
this.linkChecker = new MVLinkChecker(this.plugin);
}
@EventHandler(priority = EventPriority.NORMAL)
public void onPlayerPortal(PlayerPortalEvent event) {
if (event.isCancelled()) {
this.plugin.log(Level.FINEST, "PlayerPortalEvent was cancelled! NOT teleporting!");
return;
}
Location originalTo = event.getTo();
if (originalTo != null) {
originalTo = originalTo.clone();
}
Location currentLocation = event.getFrom().clone();
String currentWorld = currentLocation.getWorld().getName();
PortalType type = PortalType.END;
if (event.getFrom().getBlock().getType() == Material.PORTAL) {
type = PortalType.NETHER;
+ event.useTravelAgent(true);
}
String linkedWorld = this.plugin.getWorldLink(currentWorld, type);
if (linkedWorld != null) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, linkedWorld);
} else if (this.nameChecker.isValidNetherName(currentWorld)) {
if (type == PortalType.NETHER) {
this.plugin.log(Level.FINER, "");
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.NETHER));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(this.nameChecker.getNormalName(currentWorld, PortalType.NETHER)));
}
} else if (this.nameChecker.isValidEndName(currentWorld)) {
if (type == PortalType.NETHER) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(this.nameChecker.getNormalName(currentWorld, PortalType.END)));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.END));
}
} else {
if(type == PortalType.END) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(currentWorld));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(currentWorld));
}
}
if (event.getTo() == null || event.getFrom() == null) {
return;
}
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Portaling to the same world.
this.plugin.log(Level.FINER, "Player '" + event.getPlayer().getName() + "' is portaling to the same world. Ignoring.");
event.setTo(originalTo);
return;
}
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (!event.isCancelled() && fromWorld.getEnvironment() == World.Environment.THE_END && type == PortalType.END) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' will be teleported to the spawn of '" + toWorld.getName() + "' since they used an end exit portal.");
event.getPortalTravelAgent().setCanCreatePortal(false);
if (toWorld.getBedRespawn()
&& event.getPlayer().getBedSpawnLocation() != null
&& event.getPlayer().getBedSpawnLocation().getWorld().getUID() == toWorld.getCBWorld().getUID()) {
event.setTo(event.getPlayer().getBedSpawnLocation());
} else {
event.setTo(toWorld.getSpawnLocation());
}
}
}
}
| true | true | public void onPlayerPortal(PlayerPortalEvent event) {
if (event.isCancelled()) {
this.plugin.log(Level.FINEST, "PlayerPortalEvent was cancelled! NOT teleporting!");
return;
}
Location originalTo = event.getTo();
if (originalTo != null) {
originalTo = originalTo.clone();
}
Location currentLocation = event.getFrom().clone();
String currentWorld = currentLocation.getWorld().getName();
PortalType type = PortalType.END;
if (event.getFrom().getBlock().getType() == Material.PORTAL) {
type = PortalType.NETHER;
}
String linkedWorld = this.plugin.getWorldLink(currentWorld, type);
if (linkedWorld != null) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, linkedWorld);
} else if (this.nameChecker.isValidNetherName(currentWorld)) {
if (type == PortalType.NETHER) {
this.plugin.log(Level.FINER, "");
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.NETHER));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(this.nameChecker.getNormalName(currentWorld, PortalType.NETHER)));
}
} else if (this.nameChecker.isValidEndName(currentWorld)) {
if (type == PortalType.NETHER) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(this.nameChecker.getNormalName(currentWorld, PortalType.END)));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.END));
}
} else {
if(type == PortalType.END) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(currentWorld));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(currentWorld));
}
}
if (event.getTo() == null || event.getFrom() == null) {
return;
}
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Portaling to the same world.
this.plugin.log(Level.FINER, "Player '" + event.getPlayer().getName() + "' is portaling to the same world. Ignoring.");
event.setTo(originalTo);
return;
}
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (!event.isCancelled() && fromWorld.getEnvironment() == World.Environment.THE_END && type == PortalType.END) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' will be teleported to the spawn of '" + toWorld.getName() + "' since they used an end exit portal.");
event.getPortalTravelAgent().setCanCreatePortal(false);
if (toWorld.getBedRespawn()
&& event.getPlayer().getBedSpawnLocation() != null
&& event.getPlayer().getBedSpawnLocation().getWorld().getUID() == toWorld.getCBWorld().getUID()) {
event.setTo(event.getPlayer().getBedSpawnLocation());
} else {
event.setTo(toWorld.getSpawnLocation());
}
}
}
| public void onPlayerPortal(PlayerPortalEvent event) {
if (event.isCancelled()) {
this.plugin.log(Level.FINEST, "PlayerPortalEvent was cancelled! NOT teleporting!");
return;
}
Location originalTo = event.getTo();
if (originalTo != null) {
originalTo = originalTo.clone();
}
Location currentLocation = event.getFrom().clone();
String currentWorld = currentLocation.getWorld().getName();
PortalType type = PortalType.END;
if (event.getFrom().getBlock().getType() == Material.PORTAL) {
type = PortalType.NETHER;
event.useTravelAgent(true);
}
String linkedWorld = this.plugin.getWorldLink(currentWorld, type);
if (linkedWorld != null) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, linkedWorld);
} else if (this.nameChecker.isValidNetherName(currentWorld)) {
if (type == PortalType.NETHER) {
this.plugin.log(Level.FINER, "");
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.NETHER));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(this.nameChecker.getNormalName(currentWorld, PortalType.NETHER)));
}
} else if (this.nameChecker.isValidEndName(currentWorld)) {
if (type == PortalType.NETHER) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(this.nameChecker.getNormalName(currentWorld, PortalType.END)));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNormalName(currentWorld, PortalType.END));
}
} else {
if(type == PortalType.END) {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getEndName(currentWorld));
} else {
this.linkChecker.getNewTeleportLocation(event, currentLocation, this.nameChecker.getNetherName(currentWorld));
}
}
if (event.getTo() == null || event.getFrom() == null) {
return;
}
if (event.getFrom().getWorld().equals(event.getTo().getWorld())) {
// The player is Portaling to the same world.
this.plugin.log(Level.FINER, "Player '" + event.getPlayer().getName() + "' is portaling to the same world. Ignoring.");
event.setTo(originalTo);
return;
}
MultiverseWorld fromWorld = this.worldManager.getMVWorld(event.getFrom().getWorld().getName());
MultiverseWorld toWorld = this.worldManager.getMVWorld(event.getTo().getWorld().getName());
if (!event.isCancelled() && fromWorld.getEnvironment() == World.Environment.THE_END && type == PortalType.END) {
this.plugin.log(Level.FINE, "Player '" + event.getPlayer().getName() + "' will be teleported to the spawn of '" + toWorld.getName() + "' since they used an end exit portal.");
event.getPortalTravelAgent().setCanCreatePortal(false);
if (toWorld.getBedRespawn()
&& event.getPlayer().getBedSpawnLocation() != null
&& event.getPlayer().getBedSpawnLocation().getWorld().getUID() == toWorld.getCBWorld().getUID()) {
event.setTo(event.getPlayer().getBedSpawnLocation());
} else {
event.setTo(toWorld.getSpawnLocation());
}
}
}
|
diff --git a/framework/src/test/java/org/papoose/framework/launch/PapooseFrameworkFactoryTest.java b/framework/src/test/java/org/papoose/framework/launch/PapooseFrameworkFactoryTest.java
index bfdb0d2..26fafce 100644
--- a/framework/src/test/java/org/papoose/framework/launch/PapooseFrameworkFactoryTest.java
+++ b/framework/src/test/java/org/papoose/framework/launch/PapooseFrameworkFactoryTest.java
@@ -1,122 +1,122 @@
/**
*
* Copyright 2009 (C) The original author or authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.papoose.framework.launch;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.Callable;
import java.util.concurrent.Future;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.junit.Assert;
import org.junit.Test;
import org.osgi.framework.Bundle;
import org.osgi.framework.Constants;
import org.osgi.framework.FrameworkEvent;
import org.osgi.framework.launch.Framework;
import org.osgi.framework.launch.FrameworkFactory;
import static org.junit.Assert.assertEquals;
import static org.junit.Assert.assertNotNull;
import static org.junit.Assert.assertSame;
import org.papoose.core.PapooseFrameworkFactory;
/**
* @version $Revision$ $Date$
*/
public class PapooseFrameworkFactoryTest
{
@Test
public void test() throws Exception
{
Map<String, String> configuration = new HashMap<String, String>();
- configuration.put(Constants.FRAMEWORK_STORAGE, "targets/papoose");
+ configuration.put(Constants.FRAMEWORK_STORAGE, "target/papoose");
FrameworkFactory factory = new PapooseFrameworkFactory();
final Framework framework = factory.newFramework(configuration);
FrameworkEvent frameworkEvent = framework.waitForStop(0);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(framework, frameworkEvent.getBundle());
framework.init();
Bundle systemBundle = framework.getBundleContext().getBundle(0);
assertEquals(Bundle.STARTING, framework.getState());
assertEquals(Bundle.STARTING, systemBundle.getState());
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
try
{
Future<FrameworkEvent> result = pool.submit(new Callable<FrameworkEvent>()
{
public FrameworkEvent call() throws Exception
{
return framework.waitForStop(0);
}
});
framework.stop();
frameworkEvent = result.get();
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
framework.waitForStop(0);
}
finally
{
pool.shutdown();
}
try
{
framework.waitForStop(-1);
Assert.fail("Should never accept negative wait timeouts");
}
catch (IllegalArgumentException iae)
{
}
frameworkEvent = framework.waitForStop(Long.MAX_VALUE);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
framework.start();
framework.stop();
Thread.sleep(1);
frameworkEvent = framework.waitForStop(0);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
}
}
| true | true | public void test() throws Exception
{
Map<String, String> configuration = new HashMap<String, String>();
configuration.put(Constants.FRAMEWORK_STORAGE, "targets/papoose");
FrameworkFactory factory = new PapooseFrameworkFactory();
final Framework framework = factory.newFramework(configuration);
FrameworkEvent frameworkEvent = framework.waitForStop(0);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(framework, frameworkEvent.getBundle());
framework.init();
Bundle systemBundle = framework.getBundleContext().getBundle(0);
assertEquals(Bundle.STARTING, framework.getState());
assertEquals(Bundle.STARTING, systemBundle.getState());
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
try
{
Future<FrameworkEvent> result = pool.submit(new Callable<FrameworkEvent>()
{
public FrameworkEvent call() throws Exception
{
return framework.waitForStop(0);
}
});
framework.stop();
frameworkEvent = result.get();
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
framework.waitForStop(0);
}
finally
{
pool.shutdown();
}
try
{
framework.waitForStop(-1);
Assert.fail("Should never accept negative wait timeouts");
}
catch (IllegalArgumentException iae)
{
}
frameworkEvent = framework.waitForStop(Long.MAX_VALUE);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
framework.start();
framework.stop();
Thread.sleep(1);
frameworkEvent = framework.waitForStop(0);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
}
| public void test() throws Exception
{
Map<String, String> configuration = new HashMap<String, String>();
configuration.put(Constants.FRAMEWORK_STORAGE, "target/papoose");
FrameworkFactory factory = new PapooseFrameworkFactory();
final Framework framework = factory.newFramework(configuration);
FrameworkEvent frameworkEvent = framework.waitForStop(0);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(framework, frameworkEvent.getBundle());
framework.init();
Bundle systemBundle = framework.getBundleContext().getBundle(0);
assertEquals(Bundle.STARTING, framework.getState());
assertEquals(Bundle.STARTING, systemBundle.getState());
ThreadPoolExecutor pool = new ThreadPoolExecutor(1, 1, 60, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>());
try
{
Future<FrameworkEvent> result = pool.submit(new Callable<FrameworkEvent>()
{
public FrameworkEvent call() throws Exception
{
return framework.waitForStop(0);
}
});
framework.stop();
frameworkEvent = result.get();
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
framework.waitForStop(0);
}
finally
{
pool.shutdown();
}
try
{
framework.waitForStop(-1);
Assert.fail("Should never accept negative wait timeouts");
}
catch (IllegalArgumentException iae)
{
}
frameworkEvent = framework.waitForStop(Long.MAX_VALUE);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
framework.start();
framework.stop();
Thread.sleep(1);
frameworkEvent = framework.waitForStop(0);
assertNotNull(frameworkEvent);
assertEquals(FrameworkEvent.STOPPED, frameworkEvent.getType());
assertSame(systemBundle, frameworkEvent.getBundle());
}
|
diff --git a/nuxeo-launcher-commons/src/main/java/org/nuxeo/launcher/config/ConfigurationGenerator.java b/nuxeo-launcher-commons/src/main/java/org/nuxeo/launcher/config/ConfigurationGenerator.java
index a0004972..eb4cab99 100644
--- a/nuxeo-launcher-commons/src/main/java/org/nuxeo/launcher/config/ConfigurationGenerator.java
+++ b/nuxeo-launcher-commons/src/main/java/org/nuxeo/launcher/config/ConfigurationGenerator.java
@@ -1,1206 +1,1204 @@
/*
* (C) Copyright 2010-2011 Nuxeo SAS (http://nuxeo.com/) and contributors.
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the GNU Lesser General Public License
* (LGPL) version 2.1 which accompanies this distribution, and is available at
* http://www.gnu.org/licenses/lgpl.html
*
* This library is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* Contributors:
* Julien Carsique
*
* $Id$
*/
package org.nuxeo.launcher.config;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.net.Inet4Address;
import java.net.Inet6Address;
import java.net.InetAddress;
import java.net.ServerSocket;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.StringTokenizer;
import java.util.UUID;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.log4j.Logger;
import org.apache.log4j.helpers.NullEnumeration;
import org.nuxeo.log4j.Log4JHelper;
/**
* Builder for server configuration and datasource files from templates and
* properties.
*
* @author jcarsique
*/
public class ConfigurationGenerator {
private static final Log log = LogFactory.getLog(ConfigurationGenerator.class);
public static final String NUXEO_HOME = "nuxeo.home";
public static final String NUXEO_CONF = "nuxeo.conf";
protected static final String TEMPLATES = "templates";
protected static final String NUXEO_DEFAULT_CONF = "nuxeo.defaults";
/**
* Absolute or relative PATH to the user chosen template
*
* @deprecated use {@link #PARAM_TEMPLATES_NAME} instead
*/
@Deprecated
public static final String PARAM_TEMPLATE_NAME = "nuxeo.template";
/**
* Absolute or relative PATH to the user chosen templates (comma separated
* list)
*/
public static final String PARAM_TEMPLATES_NAME = "nuxeo.templates";
public static final String PARAM_TEMPLATE_DBNAME = "nuxeo.dbtemplate";
public static final String PARAM_TEMPLATES_NODB = "nuxeo.nodbtemplates";
public static final String PARAM_TEMPLATES_PARSING_EXTENSIONS = "nuxeo.templates.parsing.extensions";
/**
* Absolute or relative PATH to the included templates (comma separated
* list)
*/
protected static final String PARAM_INCLUDED_TEMPLATES = "nuxeo.template.includes";
public static final String PARAM_FORCE_GENERATION = "nuxeo.force.generation";
public static final String BOUNDARY_BEGIN = "### BEGIN - DO NOT EDIT BETWEEN BEGIN AND END ###";
public static final String BOUNDARY_END = "### END - DO NOT EDIT BETWEEN BEGIN AND END ###";
public static final List<String> DB_LIST = Arrays.asList("default",
"postgresql", "oracle", "mysql", "mssql");
public static final String PARAM_WIZARD_DONE = "nuxeo.wizard.done";
public static final String PARAM_WIZARD_RESTART_PARAMS = "wizard.restart.params";
public static final String PARAM_FAKE_WINDOWS = "org.nuxeo.fake.vindoz";
public static final String PARAM_LOOPBACK_URL = "nuxeo.loopback.url";
public static final int MIN_PORT = 1;
public static final int MAX_PORT = 65535;
public static final int ADDRESS_PING_TIMEOUT = 1000;
public static final String PARAM_BIND_ADDRESS = "nuxeo.bind.address";
public static final String PARAM_HTTP_PORT = "nuxeo.server.http.port";
public static final String PARAM_STATUS_KEY = "server.status.key";
public static final String PARAM_CONTEXT_PATH = "org.nuxeo.ecm.contextPath";
public static final String INSTALL_AFTER_RESTART = "installAfterRestart.log";
private final File nuxeoHome;
// User configuration file
private final File nuxeoConf;
// Chosen templates
private final List<File> includedTemplates = new ArrayList<File>();
// Common default configuration file
private File nuxeoDefaultConf;
public boolean isJBoss;
public boolean isJetty;
public boolean isTomcat;
private ServerConfigurator serverConfigurator;
private boolean forceGeneration;
private Properties defaultConfig;
private Properties userConfig;
private boolean configurable = false;
private boolean onceGeneration = false;
private String templates;
// if PARAM_FORCE_GENERATION=once, set to false; else keep current value
private boolean setOnceToFalse = true;
// if PARAM_FORCE_GENERATION=false, set to once; else keep the current value
private boolean setFalseToOnce = false;
public boolean isConfigurable() {
return configurable;
}
public ConfigurationGenerator() {
String nuxeoHomePath = System.getProperty(NUXEO_HOME);
String nuxeoConfPath = System.getProperty(NUXEO_CONF);
if (nuxeoHomePath != null) {
nuxeoHome = new File(nuxeoHomePath);
} else {
File userDir = new File(System.getProperty("user.dir"));
if ("bin".equalsIgnoreCase(userDir.getName())) {
nuxeoHome = userDir.getParentFile();
} else {
nuxeoHome = userDir;
}
}
if (nuxeoConfPath != null) {
nuxeoConf = new File(nuxeoConfPath);
} else {
nuxeoConf = new File(nuxeoHome, "bin" + File.separator
+ "nuxeo.conf");
}
nuxeoDefaultConf = new File(nuxeoHome, TEMPLATES + File.separator
+ NUXEO_DEFAULT_CONF);
// detect server type based on System properties
isJBoss = System.getProperty("jboss.home.dir") != null;
isJetty = System.getProperty("jetty.home") != null;
isTomcat = System.getProperty("tomcat.home") != null;
if (!isJBoss && !isJetty && !isTomcat) {
// fallback on jar detection
isJBoss = new File(nuxeoHome, "bin/run.jar").exists();
isTomcat = new File(nuxeoHome, "bin/bootstrap.jar").exists();
String[] files = nuxeoHome.list();
for (String file : files) {
if (file.startsWith("nuxeo-runtime-launcher")) {
isJetty = true;
break;
}
}
}
if (isJBoss) {
serverConfigurator = new JBossConfigurator(this);
} else if (isTomcat) {
serverConfigurator = new TomcatConfigurator(this);
} else if (isJetty) {
serverConfigurator = new JettyConfigurator(this);
}
if (Logger.getRootLogger().getAllAppenders() instanceof NullEnumeration) {
serverConfigurator.initLogs();
}
log.info("Nuxeo home: " + nuxeoHome.getPath());
log.info("Nuxeo configuration: " + nuxeoConf.getPath());
}
/**
* @see #PARAM_FORCE_GENERATION
* @param forceGeneration
*/
public void setForceGeneration(boolean forceGeneration) {
this.forceGeneration = forceGeneration;
}
/**
* @see #PARAM_FORCE_GENERATION
* @return true if configuration will be generated from templates
* @since 5.4.2
*/
public boolean isForceGeneration() {
return forceGeneration;
}
public Properties getUserConfig() {
return userConfig;
}
/**
* @since 5.4.2
*/
public final ServerConfigurator getServerConfigurator() {
return serverConfigurator;
}
/**
* Runs the configuration files generation.
*/
public void run() throws ConfigurationException {
if (init()) {
if (!serverConfigurator.isConfigured()) {
log.info("No current configuration, generating files...");
generateFiles();
} else if (forceGeneration) {
log.info("Configuration files generation (nuxeo.force.generation="
+ userConfig.getProperty(PARAM_FORCE_GENERATION,
"false") + ")...");
generateFiles();
} else {
log.info("Server already configured (set nuxeo.force.generation=true to force configuration files generation).");
}
}
}
/**
* Initialize configurator, check requirements and load current
* configuration
*
* @return returns true if current install is configurable, else returns
* false
*/
public boolean init() {
if (serverConfigurator == null) {
log.warn("Unrecognized server. Considered as already configured.");
configurable = false;
} else if (!nuxeoConf.exists()) {
log.info("Missing " + nuxeoConf);
configurable = false;
} else if (userConfig == null) {
try {
setBasicConfiguration();
configurable = true;
} catch (ConfigurationException e) {
log.warn("Error reading basic configuration.", e);
configurable = false;
}
} else {
configurable = true;
}
return configurable;
}
public void changeTemplates(String newTemplates) {
try {
includedTemplates.clear();
templates = newTemplates;
setBasicConfiguration();
configurable = true;
} catch (ConfigurationException e) {
log.warn("Error reading basic configuration.", e);
configurable = false;
}
}
/**
* Change templates using given database template
*
* @param dbTemplate new database template
* @since 5.4.2
*/
public void changeDBTemplate(String dbTemplate) {
changeTemplates(rebuildTemplatesStr(dbTemplate));
}
private void setBasicConfiguration() throws ConfigurationException {
try {
// Load default configuration
defaultConfig = new Properties();
defaultConfig.load(new FileInputStream(nuxeoDefaultConf));
userConfig = new Properties(defaultConfig);
// Add useful system properties
userConfig.putAll(System.getProperties());
// If Windows, replace backslashes in paths
if (System.getProperty("os.name").toLowerCase().startsWith("win")) {
replaceBackslashes();
}
// Load user configuration
userConfig.load(new FileInputStream(nuxeoConf));
onceGeneration = "once".equals(userConfig.getProperty(PARAM_FORCE_GENERATION));
forceGeneration = onceGeneration
|| Boolean.parseBoolean(userConfig.getProperty(
PARAM_FORCE_GENERATION, "false"));
// Manage directories set from (or set to) system properties
setDirectoryWithProperty(Environment.NUXEO_DATA_DIR);
setDirectoryWithProperty(Environment.NUXEO_LOG_DIR);
setDirectoryWithProperty(Environment.NUXEO_PID_DIR);
setDirectoryWithProperty(Environment.NUXEO_TMP_DIR);
} catch (NullPointerException e) {
throw new ConfigurationException("Missing file", e);
} catch (FileNotFoundException e) {
throw new ConfigurationException("Missing file: "
+ nuxeoDefaultConf + " or " + nuxeoConf, e);
} catch (IOException e) {
throw new ConfigurationException("Error reading " + nuxeoConf, e);
}
// Override default configuration with specific configuration(s) of
// the chosen template(s) which can be outside of server filesystem
try {
if (templates == null) {
templates = getUserTemplates();
}
extractDatabaseTemplateName();
includeTemplates(templates);
} catch (FileNotFoundException e) {
throw new ConfigurationException("Missing file", e);
} catch (IOException e) {
throw new ConfigurationException("Error reading " + nuxeoConf, e);
}
Map<String, String> newParametersToSave = evalDynamicProperties();
if (newParametersToSave != null && !newParametersToSave.isEmpty()) {
saveConfiguration(newParametersToSave, false, false);
}
}
/**
* Generate properties which values are based on others
*
* @return Map with new parameters to save in {@code nuxeoConf}
*
* @throws ConfigurationException
*
* @since 5.5
*/
protected HashMap<String, String> evalDynamicProperties()
throws ConfigurationException {
HashMap<String, String> newParametersToSave = new HashMap<String, String>();
evalLoopbackURL();
evalServerStatusKey(newParametersToSave);
return newParametersToSave;
}
/**
* Generate a server status key if not already set
*
* @param newParametersToSave
*
* @throws ConfigurationException
*
* @see #PARAM_STATUS_KEY
* @since 5.5
*/
private void evalServerStatusKey(Map<String, String> newParametersToSave)
throws ConfigurationException {
if (userConfig.getProperty(PARAM_STATUS_KEY) == null) {
newParametersToSave.put(PARAM_STATUS_KEY,
UUID.randomUUID().toString().substring(0, 8));
}
}
private void evalLoopbackURL() throws ConfigurationException {
String loopbackURL = userConfig.getProperty(PARAM_LOOPBACK_URL);
if (loopbackURL != null) {
log.debug("Using configured loop back url: " + loopbackURL);
return;
}
InetAddress bindAddress = getBindAddress();
// Address and ports already checked by #checkAddressesAndPorts
try {
if (bindAddress.isAnyLocalAddress()) {
boolean preferIPv6 = "false".equals(System.getProperty("java.net.preferIPv4Stack"))
&& "true".equals(System.getProperty("java.net.preferIPv6Addresses"));
bindAddress = preferIPv6 ? Inet6Address.getByName("::1")
: Inet4Address.getByName("127.0.0.1");
log.debug("Bind address is \"ANY\", using local address instead: "
+ bindAddress);
}
} catch (UnknownHostException e) {
log.error(e);
}
String httpPort = userConfig.getProperty(PARAM_HTTP_PORT);
String contextPath = userConfig.getProperty(PARAM_CONTEXT_PATH);
// Is IPv6 or IPv4 ?
if (bindAddress instanceof Inet6Address) {
loopbackURL = "http://[" + bindAddress.getHostAddress() + "]:"
+ httpPort + contextPath;
} else {
loopbackURL = "http://" + bindAddress.getHostAddress() + ":"
+ httpPort + contextPath;
}
log.debug("Set as loop back URL: " + loopbackURL);
userConfig.setProperty(PARAM_LOOPBACK_URL, loopbackURL);
}
/**
* Read nuxeo.conf, replace backslashes in paths and write new
* nuxeo.conf
*
* @throws ConfigurationException if any error reading or writing
* nuxeo.conf
* @since 5.4.1
*/
protected void replaceBackslashes() throws ConfigurationException {
StringBuffer sb = new StringBuffer();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(nuxeoConf));
String line;
while ((line = reader.readLine()) != null) {
if (line.matches(".*:\\\\.*")) {
line = line.replaceAll("\\\\", "/");
}
sb.append(line + System.getProperty("line.separator"));
}
reader.close();
} catch (IOException e) {
throw new ConfigurationException("Error reading " + nuxeoConf, e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new ConfigurationException(e);
}
}
}
FileWriter writer = null;
try {
writer = new FileWriter(nuxeoConf, false);
// Copy back file content
writer.append(sb.toString());
} catch (IOException e) {
throw new ConfigurationException("Error writing in " + nuxeoConf, e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
throw new ConfigurationException(e);
}
}
}
}
/**
* @since 5.4.2
* @param key Directory system key
* @see Environment
*/
public void setDirectoryWithProperty(String key) {
String directory = userConfig.getProperty(key);
if (directory == null) {
userConfig.setProperty(key,
serverConfigurator.getDirectory(key).getPath());
} else {
serverConfigurator.setDirectory(key, directory);
}
}
private String getUserTemplates() {
String userTemplatesList = userConfig.getProperty(PARAM_TEMPLATES_NAME);
if (userTemplatesList == null) {
// backward compliance: manage parameter for a single
// template
userTemplatesList = userConfig.getProperty(PARAM_TEMPLATE_NAME);
}
if (userTemplatesList == null) {
log.warn("No template found in configuration! Fallback on 'default'.");
userTemplatesList = "default";
}
return userTemplatesList;
}
protected void generateFiles() throws ConfigurationException {
try {
serverConfigurator.parseAndCopy(userConfig);
serverConfigurator.dumpProperties(userConfig);
log.info("Configuration files generated.");
// keep true or false, switch once to false
if (onceGeneration) {
setOnceToFalse = true;
writeConfiguration(loadConfiguration());
}
} catch (FileNotFoundException e) {
throw new ConfigurationException("Missing file", e);
} catch (IOException e) {
throw new ConfigurationException("Configuration failure", e);
}
}
private StringBuffer loadConfiguration() throws ConfigurationException {
return loadConfiguration(null);
}
private void writeConfiguration(StringBuffer configuration)
throws ConfigurationException {
writeConfiguration(configuration, null);
}
private void includeTemplates(String templatesList) throws IOException {
StringTokenizer st = new StringTokenizer(templatesList, ",");
while (st.hasMoreTokens()) {
String nextToken = st.nextToken();
File chosenTemplate = new File(nextToken);
// is it absolute and existing or relative path ?
if (!chosenTemplate.exists()
|| !chosenTemplate.getPath().equals(
chosenTemplate.getAbsolutePath())) {
chosenTemplate = new File(nuxeoDefaultConf.getParentFile(),
nextToken);
}
if (includedTemplates.contains(chosenTemplate)) {
log.debug("Already included " + nextToken);
} else if (chosenTemplate.exists()) {
File chosenTemplateConf = new File(chosenTemplate,
NUXEO_DEFAULT_CONF);
if (chosenTemplateConf.exists()) {
Properties subTemplateConf = new Properties();
subTemplateConf.load(new FileInputStream(chosenTemplateConf));
String subTemplatesList = subTemplateConf.getProperty(PARAM_INCLUDED_TEMPLATES);
if (subTemplatesList != null
&& subTemplatesList.length() > 0) {
includeTemplates(subTemplatesList);
}
// Load configuration from chosen templates
defaultConfig.load(new FileInputStream(chosenTemplateConf));
log.info("Include template: " + chosenTemplate.getPath());
} else {
log.debug("No default configuration for template "
+ nextToken);
}
includedTemplates.add(chosenTemplate);
} else {
log.error(String.format(
"Template '%s' not found with relative or absolute path (%s). "
+ "Check your %s parameter, and %s for included files.",
nextToken, chosenTemplate, PARAM_TEMPLATES_NAME,
PARAM_INCLUDED_TEMPLATES));
}
}
}
public File getNuxeoHome() {
return nuxeoHome;
}
public File getNuxeoDefaultConf() {
return nuxeoDefaultConf;
}
public List<File> getIncludedTemplates() {
return includedTemplates;
}
public static void main(String[] args) throws ConfigurationException {
new ConfigurationGenerator().run();
}
/**
* Save changed parameters in {@code nuxeo.conf}.
* This method does not check values in map. Use
* {@link #saveFilteredConfiguration(Map)} for parameters filtering.
*
* @param changedParameters Map of modified parameters
* @see #saveFilteredConfiguration(Map)
*/
public void saveConfiguration(Map<String, String> changedParameters)
throws ConfigurationException {
// Keep generation true or once; switch false to once
saveConfiguration(changedParameters, false, true);
}
/**
* Save changed parameters in {@code nuxeo.conf}.
* This method does not check values in map. Use
* {@link #saveFilteredConfiguration(Map)} for parameters filtering.
*
* @param changedParameters Map of modified parameters
* @param setGenerationOnceToFalse If generation was on (true or once), then
* set it to false or not?
* @param setGenerationFalseToOnce If generation was off (false), then set
* it to once?
* @see #saveFilteredConfiguration(Map)
* @since 5.5
*/
public void saveConfiguration(Map<String, String> changedParameters,
boolean setGenerationOnceToFalse, boolean setGenerationFalseToOnce)
throws ConfigurationException {
this.setOnceToFalse = setGenerationOnceToFalse;
this.setFalseToOnce = setGenerationFalseToOnce;
writeConfiguration(loadConfiguration(changedParameters),
changedParameters);
for (String key : changedParameters.keySet()) {
if (changedParameters.get(key) != null) {
userConfig.setProperty(key, changedParameters.get(key));
}
}
}
/**
* Save changed parameters in {@code nuxeo.conf}, filtering parameters with
* {@link #getChangedParametersMap(Map, Map)} and calculating templates if
* changedParameters contains a value for {@link #PARAM_TEMPLATE_DBNAME}
*
* @param changedParameters Maps of modified parameters
* @since 5.4.2
* @see #getChangedParameters(Map)
*/
public void saveFilteredConfiguration(Map<String, String> changedParameters)
throws ConfigurationException {
String newDbTemplate = changedParameters.remove(PARAM_TEMPLATE_DBNAME);
if (newDbTemplate != null) {
changedParameters.put(PARAM_TEMPLATES_NAME,
rebuildTemplatesStr(newDbTemplate));
}
saveConfiguration(getChangedParameters(changedParameters));
}
/**
* Filters given parameters including them only if (there was no previous
* value and new value is not empty/null) or (there was a previous value and
* it differs from the new value)
*
* @param changedParameters parameters to be filtered
* @return filtered map
* @since 5.4.2
*/
public Map<String, String> getChangedParameters(
Map<String, String> changedParameters) {
Map<String, String> filteredChangedParameters = new HashMap<String, String>();
for (String key : changedParameters.keySet()) {
String oldParam = userConfig.getProperty(key);
String newParam = changedParameters.get(key);
if (newParam != null) {
newParam = newParam.trim();
}
if (oldParam == null && newParam != null && !newParam.isEmpty()
|| oldParam != null && !oldParam.trim().equals(newParam)) {
filteredChangedParameters.put(key, newParam);
}
}
return filteredChangedParameters;
}
private void writeConfiguration(StringBuffer newContent,
Map<String, String> changedParameters)
throws ConfigurationException {
FileWriter writer = null;
try {
writer = new FileWriter(nuxeoConf, false);
// Copy back file content
writer.append(newContent.toString());
if (changedParameters != null && !changedParameters.isEmpty()) {
// Write changed parameters
writer.write(BOUNDARY_BEGIN + " " + new Date().toString()
+ System.getProperty("line.separator"));
for (String key : changedParameters.keySet()) {
writer.write("#" + key + "="
+ userConfig.getProperty(key, "")
+ System.getProperty("line.separator"));
if (changedParameters.get(key) != null) {
writer.write(key + "=" + changedParameters.get(key)
+ System.getProperty("line.separator"));
}
}
writer.write(BOUNDARY_END
+ System.getProperty("line.separator"));
}
} catch (IOException e) {
throw new ConfigurationException("Error writing in " + nuxeoConf, e);
} finally {
if (writer != null) {
try {
writer.close();
} catch (IOException e) {
throw new ConfigurationException(e);
}
}
}
}
private StringBuffer loadConfiguration(Map<String, String> changedParameters)
throws ConfigurationException {
String wizardParam = null, templatesParam = null;
Integer generationIndex = null, wizardIndex = null, templatesIndex = null;
if (changedParameters != null) {
// Will change wizardParam value instead of appending it
wizardParam = changedParameters.remove(PARAM_WIZARD_DONE);
// Will change templatesParam value instead of appending it
templatesParam = changedParameters.remove(PARAM_TEMPLATES_NAME);
}
ArrayList<String> newLines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(nuxeoConf));
String line;
boolean onConfiguratorContent = false;
while ((line = reader.readLine()) != null) {
if (!onConfiguratorContent) {
if (!line.startsWith(BOUNDARY_BEGIN)) {
if (line.startsWith(PARAM_FORCE_GENERATION)) {
if (setOnceToFalse && onceGeneration) {
line = PARAM_FORCE_GENERATION + "=false";
}
if (setFalseToOnce && !forceGeneration) {
line = PARAM_FORCE_GENERATION + "=once";
}
if (generationIndex == null) {
newLines.add(line);
generationIndex = newLines.size() - 1;
} else {
newLines.set(generationIndex, line);
}
} else if (line.startsWith(PARAM_WIZARD_DONE)) {
if (wizardParam != null) {
line = PARAM_WIZARD_DONE + "="
+ wizardParam;
}
if (wizardIndex == null) {
newLines.add(line);
wizardIndex = newLines.size() -1;
} else {
newLines.set(wizardIndex, line);
}
} else if (line.startsWith(PARAM_TEMPLATES_NAME)) {
if (templatesParam != null) {
line = PARAM_TEMPLATES_NAME + "="
+ templatesParam;
}
if (templatesIndex == null) {
newLines.add(line);
templatesIndex = newLines.size() -1;
} else {
newLines.set(templatesIndex, line);
}
} else if (line != null) {
newLines.add(line);
}
} else {
// What must be written just before the BOUNDARY_BEGIN
if (templatesIndex == null && templatesParam != null) {
newLines.add(PARAM_TEMPLATES_NAME + "="
+ templatesParam);
templatesIndex = newLines.size() -1;
}
if (wizardIndex == null && wizardParam != null) {
newLines.add(PARAM_WIZARD_DONE + "="
+ wizardParam);
wizardIndex = newLines.size() -1;
}
- newLines.add(line);
onConfiguratorContent = true;
}
} else {
if (!line.startsWith(BOUNDARY_END)) {
if (changedParameters == null) {
newLines.add(line);
} else {
int equalIdx = line.indexOf("=");
if (line.startsWith("#" + PARAM_TEMPLATES_NAME)
|| line.startsWith(PARAM_TEMPLATES_NAME)) {
// Backward compliance, it must be ignored
continue;
}
if (line.trim().startsWith("#")) {
String key = line.substring(1, equalIdx).trim();
String value = line.substring(equalIdx + 1).trim();
userConfig.setProperty(key, value);
} else {
String key = line.substring(0, equalIdx).trim();
String value = line.substring(equalIdx + 1).trim();
if (!changedParameters.containsKey(key)) {
changedParameters.put(key, value);
} else if (!value.equals(changedParameters.get(key))) {
userConfig.setProperty(key, value);
}
}
}
} else {
- newLines.add(line);
onConfiguratorContent = false;
}
}
}
reader.close();
} catch (IOException e) {
throw new ConfigurationException("Error reading " + nuxeoConf, e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new ConfigurationException(e);
}
}
}
StringBuffer newContent = new StringBuffer();
for (int i = 0; i < newLines.size(); i++) {
newContent.append(newLines.get(i).trim() + System.getProperty("line.separator"));
}
return newContent;
}
/**
* Extract a database template from a list of templates.
* Return the last one if there are multiples
*
* @see #rebuildTemplatesStr(String)
*/
public String extractDatabaseTemplateName() {
String dbTemplate = "unknown";
String nodbTemplates = "";
StringTokenizer st = new StringTokenizer(templates, ",");
while (st.hasMoreTokens()) {
String template = st.nextToken();
if (DB_LIST.contains(template)) {
dbTemplate = template;
} else {
nodbTemplates += template;
}
}
userConfig.put(PARAM_TEMPLATES_NODB, nodbTemplates);
userConfig.put(PARAM_TEMPLATE_DBNAME, dbTemplate);
return dbTemplate;
}
/**
* @return nuxeo.conf file used
*/
public File getNuxeoConf() {
return nuxeoConf;
}
/**
* Delegate logs initialization to serverConfigurator instance
*
* @since 5.4.2
*/
public void initLogs() {
serverConfigurator.initLogs();
}
/**
* @return log directory
* @since 5.4.2
*/
public File getLogDir() {
return serverConfigurator.getLogDir();
}
/**
* @return pid directory
* @since 5.4.2
*/
public File getPidDir() {
return serverConfigurator.getPidDir();
}
/**
* @return Data directory
* @since 5.4.2
*/
public File getDataDir() {
return serverConfigurator.getDataDir();
}
/**
* Create needed directories.
* Check existence of old paths.
* If old paths have been found and they cannot be upgraded automatically,
* then upgrading message is logged and error thrown.
*
* @throws ConfigurationException If a deprecated directory has been
* detected.
*
* @since 5.4.2
*/
public void verifyInstallation() throws ConfigurationException {
String version = System.getProperty("java.version");
if (!version.startsWith("1.6") && !version.startsWith("1.7")) {
String message = "Nuxeo requires Java 6 or 7 (detected " + version
+ ").";
if ("nofail".equalsIgnoreCase(System.getProperty("jvmcheck", "fail"))) {
log.error(message);
} else {
throw new ConfigurationException(message);
}
}
ifNotExistsAndIsDirectoryThenCreate(getLogDir());
ifNotExistsAndIsDirectoryThenCreate(getPidDir());
ifNotExistsAndIsDirectoryThenCreate(getDataDir());
ifNotExistsAndIsDirectoryThenCreate(getTmpDir());
serverConfigurator.checkPaths();
serverConfigurator.removeExistingLocks();
checkAddressesAndPorts();
}
/**
* Will check the configured addresses are reachable and Nuxeo required
* ports are available on those addresses.
* Server specific implementations should override this method in order to
* check for server specific ports. {@link #bindAddress} must be set
* before.
*
* @throws ConfigurationException
*
* @since 5.5
*/
public void checkAddressesAndPorts() throws ConfigurationException {
InetAddress bindAddress = getBindAddress();
// Sanity check
if (bindAddress.isMulticastAddress()) {
throw new ConfigurationException("Multicast address won't work: "
+ bindAddress);
}
checkAddressReachable(bindAddress);
checkPortAvailable(bindAddress,
Integer.parseInt(userConfig.getProperty(PARAM_HTTP_PORT)));
}
private InetAddress getBindAddress() throws ConfigurationException {
InetAddress bindAddress;
try {
bindAddress = InetAddress.getByName(userConfig.getProperty(PARAM_BIND_ADDRESS));
log.debug("Configured bind address: " + bindAddress);
} catch (UnknownHostException e) {
throw new ConfigurationException(e);
}
return bindAddress;
}
/**
* @param address address to check for availability
* @throws ConfigurationException
* @since 5.5
*/
public static void checkAddressReachable(InetAddress address)
throws ConfigurationException {
try {
log.debug("Checking availability of " + address);
address.isReachable(ADDRESS_PING_TIMEOUT);
} catch (IOException e) {
throw new ConfigurationException("Unreachable bind address "
+ address);
}
}
/**
* Checks if port is available on given address.
*
* @param port port to check for availability
* @throws ConfigurationException Throws an exception if address is
* unavailable.
* @since 5.5
*/
public static void checkPortAvailable(InetAddress address, int port)
throws ConfigurationException {
if (port < MIN_PORT || port > MAX_PORT) {
throw new IllegalArgumentException("Invalid port: " + port);
}
ServerSocket socketTCP = null;
// DatagramSocket socketUDP = null;
try {
log.debug("Checking availability of port " + port + " on address "
+ address);
socketTCP = new ServerSocket(port, 0, address);
socketTCP.setReuseAddress(true);
// socketUDP = new DatagramSocket(port, address);
// socketUDP.setReuseAddress(true);
// return true;
} catch (IOException e) {
throw new ConfigurationException("Port is unavailable: " + port
+ " on address " + address + " (" + e.getMessage() + ")", e);
} finally {
// if (socketUDP != null) {
// socketUDP.close();
// }
if (socketTCP != null) {
try {
socketTCP.close();
} catch (IOException e) {
// Do not throw
}
}
}
}
/**
* @return Temporary directory
*/
public File getTmpDir() {
return serverConfigurator.getTmpDir();
}
private void ifNotExistsAndIsDirectoryThenCreate(File directory) {
if (!directory.isDirectory()) {
directory.mkdirs();
}
}
/**
* @return Log files produced by Log4J configuration without loading this
* configuration instead of current active one.
* @since 5.4.2
*/
public ArrayList<String> getLogFiles() {
File log4jConfFile = serverConfigurator.getLogConfFile();
System.setProperty(Environment.NUXEO_LOG_DIR, getLogDir().getPath());
return Log4JHelper.getFileAppendersFiles(log4jConfFile);
}
/**
* Check if wizard must and can be ran
*
* @return true if configuration wizard is required before starting Nuxeo
* @since 5.4.2
*/
public boolean isWizardRequired() {
return !"true".equalsIgnoreCase(getUserConfig().getProperty(
PARAM_WIZARD_DONE, "true"))
&& serverConfigurator.isWizardAvailable();
}
/**
* Rebuild a templates string for use in nuxeo.conf
*
* @param dbTemplate database template to use instead of current one
* @return new templates string using given dbTemplate
* @since 5.4.2
* @see #extractDatabaseTemplateName()
* @see {@link #changeDBTemplate(String)}
* @see {@link #changeTemplates(String)}
*/
public String rebuildTemplatesStr(String dbTemplate) {
String nodbTemplates = userConfig.getProperty(ConfigurationGenerator.PARAM_TEMPLATES_NODB);
if (nodbTemplates == null) {
extractDatabaseTemplateName();
nodbTemplates = userConfig.getProperty(ConfigurationGenerator.PARAM_TEMPLATES_NODB);
}
String newTemplates = nodbTemplates.isEmpty() ? dbTemplate : dbTemplate
+ "," + nodbTemplates;
return newTemplates;
}
/**
* @return Nuxeo config directory
* @since 5.4.2
*/
public File getConfigDir() {
return serverConfigurator.getConfigDir();
}
/**
* Ensure the server will start only wizard application, not Nuxeo
*
* @since 5.4.2
*/
public void prepareWizardStart() {
serverConfigurator.prepareWizardStart();
}
/**
* Ensure the wizard won't be started and nuxeo is ready for use
*
* @since 5.4.2
*/
public void cleanupPostWizard() {
serverConfigurator.cleanupPostWizard();
}
/**
* @return Nuxeo runtime home
*/
public File getRuntimeHome() {
return serverConfigurator.getRuntimeHome();
}
/**
* @since 5.4.2
* @return true if there's an install in progress
*/
public boolean isInstallInProgress() {
return getInstallFile().exists();
}
/**
* @return Install/upgrade file
* @since 5.4.1
*/
public File getInstallFile() {
return new File(serverConfigurator.getDataDir(), INSTALL_AFTER_RESTART);
}
/**
* Add a template to the {@link #PARAM_TEMPLATES_NAME} list if not already
* present
*
* @param template Template to add
* @throws ConfigurationException
* @since 5.5
*/
public void addTemplate(String template) throws ConfigurationException {
HashMap<String, String> newParametersToSave = new HashMap<String, String>();
String oldTemplates = userConfig.getProperty(PARAM_TEMPLATES_NAME);
String[] oldTemplatesSplit = oldTemplates.split(",");
if (!Arrays.asList(oldTemplatesSplit).contains(template)) {
String newTemplates = oldTemplates
+ (oldTemplates.length() > 0 ? "," : "") + template;
newParametersToSave.put(PARAM_TEMPLATES_NAME, newTemplates);
saveFilteredConfiguration(newParametersToSave);
changeTemplates(newTemplates);
}
}
/**
* Remove a template from the {@link #PARAM_TEMPLATES_NAME} list
*
* @param template
* @throws ConfigurationException
* @since 5.5
*/
public void rmTemplate(String template) throws ConfigurationException {
HashMap<String, String> newParametersToSave = new HashMap<String, String>();
String oldTemplates = userConfig.getProperty(PARAM_TEMPLATES_NAME);
List<String> oldTemplatesSplit = Arrays.asList(oldTemplates.split(","));
if (oldTemplatesSplit.contains(template)) {
String newTemplates = "";
boolean firstIem = true;
for (String templateItem : oldTemplatesSplit) {
if (!template.equals(templateItem)) {
newTemplates += (firstIem ? "" : ",") + templateItem;
firstIem = false;
}
}
newParametersToSave.put(PARAM_TEMPLATES_NAME, newTemplates);
saveFilteredConfiguration(newParametersToSave);
changeTemplates(newTemplates);
}
}
/**
* Set a property in nuxeo configuration
*
* @param key
* @param value
* @throws ConfigurationException
* @return The old value
* @since 5.5
*/
public String setProperty(String key, String value)
throws ConfigurationException {
HashMap<String, String> newParametersToSave = new HashMap<String, String>();
newParametersToSave.put(key, value);
String oldValue = userConfig.getProperty(key);
saveFilteredConfiguration(newParametersToSave);
setBasicConfiguration();
return oldValue;
}
}
| false | true | private StringBuffer loadConfiguration(Map<String, String> changedParameters)
throws ConfigurationException {
String wizardParam = null, templatesParam = null;
Integer generationIndex = null, wizardIndex = null, templatesIndex = null;
if (changedParameters != null) {
// Will change wizardParam value instead of appending it
wizardParam = changedParameters.remove(PARAM_WIZARD_DONE);
// Will change templatesParam value instead of appending it
templatesParam = changedParameters.remove(PARAM_TEMPLATES_NAME);
}
ArrayList<String> newLines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(nuxeoConf));
String line;
boolean onConfiguratorContent = false;
while ((line = reader.readLine()) != null) {
if (!onConfiguratorContent) {
if (!line.startsWith(BOUNDARY_BEGIN)) {
if (line.startsWith(PARAM_FORCE_GENERATION)) {
if (setOnceToFalse && onceGeneration) {
line = PARAM_FORCE_GENERATION + "=false";
}
if (setFalseToOnce && !forceGeneration) {
line = PARAM_FORCE_GENERATION + "=once";
}
if (generationIndex == null) {
newLines.add(line);
generationIndex = newLines.size() - 1;
} else {
newLines.set(generationIndex, line);
}
} else if (line.startsWith(PARAM_WIZARD_DONE)) {
if (wizardParam != null) {
line = PARAM_WIZARD_DONE + "="
+ wizardParam;
}
if (wizardIndex == null) {
newLines.add(line);
wizardIndex = newLines.size() -1;
} else {
newLines.set(wizardIndex, line);
}
} else if (line.startsWith(PARAM_TEMPLATES_NAME)) {
if (templatesParam != null) {
line = PARAM_TEMPLATES_NAME + "="
+ templatesParam;
}
if (templatesIndex == null) {
newLines.add(line);
templatesIndex = newLines.size() -1;
} else {
newLines.set(templatesIndex, line);
}
} else if (line != null) {
newLines.add(line);
}
} else {
// What must be written just before the BOUNDARY_BEGIN
if (templatesIndex == null && templatesParam != null) {
newLines.add(PARAM_TEMPLATES_NAME + "="
+ templatesParam);
templatesIndex = newLines.size() -1;
}
if (wizardIndex == null && wizardParam != null) {
newLines.add(PARAM_WIZARD_DONE + "="
+ wizardParam);
wizardIndex = newLines.size() -1;
}
newLines.add(line);
onConfiguratorContent = true;
}
} else {
if (!line.startsWith(BOUNDARY_END)) {
if (changedParameters == null) {
newLines.add(line);
} else {
int equalIdx = line.indexOf("=");
if (line.startsWith("#" + PARAM_TEMPLATES_NAME)
|| line.startsWith(PARAM_TEMPLATES_NAME)) {
// Backward compliance, it must be ignored
continue;
}
if (line.trim().startsWith("#")) {
String key = line.substring(1, equalIdx).trim();
String value = line.substring(equalIdx + 1).trim();
userConfig.setProperty(key, value);
} else {
String key = line.substring(0, equalIdx).trim();
String value = line.substring(equalIdx + 1).trim();
if (!changedParameters.containsKey(key)) {
changedParameters.put(key, value);
} else if (!value.equals(changedParameters.get(key))) {
userConfig.setProperty(key, value);
}
}
}
} else {
newLines.add(line);
onConfiguratorContent = false;
}
}
}
reader.close();
} catch (IOException e) {
throw new ConfigurationException("Error reading " + nuxeoConf, e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new ConfigurationException(e);
}
}
}
StringBuffer newContent = new StringBuffer();
for (int i = 0; i < newLines.size(); i++) {
newContent.append(newLines.get(i).trim() + System.getProperty("line.separator"));
}
return newContent;
}
| private StringBuffer loadConfiguration(Map<String, String> changedParameters)
throws ConfigurationException {
String wizardParam = null, templatesParam = null;
Integer generationIndex = null, wizardIndex = null, templatesIndex = null;
if (changedParameters != null) {
// Will change wizardParam value instead of appending it
wizardParam = changedParameters.remove(PARAM_WIZARD_DONE);
// Will change templatesParam value instead of appending it
templatesParam = changedParameters.remove(PARAM_TEMPLATES_NAME);
}
ArrayList<String> newLines = new ArrayList<String>();
BufferedReader reader = null;
try {
reader = new BufferedReader(new FileReader(nuxeoConf));
String line;
boolean onConfiguratorContent = false;
while ((line = reader.readLine()) != null) {
if (!onConfiguratorContent) {
if (!line.startsWith(BOUNDARY_BEGIN)) {
if (line.startsWith(PARAM_FORCE_GENERATION)) {
if (setOnceToFalse && onceGeneration) {
line = PARAM_FORCE_GENERATION + "=false";
}
if (setFalseToOnce && !forceGeneration) {
line = PARAM_FORCE_GENERATION + "=once";
}
if (generationIndex == null) {
newLines.add(line);
generationIndex = newLines.size() - 1;
} else {
newLines.set(generationIndex, line);
}
} else if (line.startsWith(PARAM_WIZARD_DONE)) {
if (wizardParam != null) {
line = PARAM_WIZARD_DONE + "="
+ wizardParam;
}
if (wizardIndex == null) {
newLines.add(line);
wizardIndex = newLines.size() -1;
} else {
newLines.set(wizardIndex, line);
}
} else if (line.startsWith(PARAM_TEMPLATES_NAME)) {
if (templatesParam != null) {
line = PARAM_TEMPLATES_NAME + "="
+ templatesParam;
}
if (templatesIndex == null) {
newLines.add(line);
templatesIndex = newLines.size() -1;
} else {
newLines.set(templatesIndex, line);
}
} else if (line != null) {
newLines.add(line);
}
} else {
// What must be written just before the BOUNDARY_BEGIN
if (templatesIndex == null && templatesParam != null) {
newLines.add(PARAM_TEMPLATES_NAME + "="
+ templatesParam);
templatesIndex = newLines.size() -1;
}
if (wizardIndex == null && wizardParam != null) {
newLines.add(PARAM_WIZARD_DONE + "="
+ wizardParam);
wizardIndex = newLines.size() -1;
}
onConfiguratorContent = true;
}
} else {
if (!line.startsWith(BOUNDARY_END)) {
if (changedParameters == null) {
newLines.add(line);
} else {
int equalIdx = line.indexOf("=");
if (line.startsWith("#" + PARAM_TEMPLATES_NAME)
|| line.startsWith(PARAM_TEMPLATES_NAME)) {
// Backward compliance, it must be ignored
continue;
}
if (line.trim().startsWith("#")) {
String key = line.substring(1, equalIdx).trim();
String value = line.substring(equalIdx + 1).trim();
userConfig.setProperty(key, value);
} else {
String key = line.substring(0, equalIdx).trim();
String value = line.substring(equalIdx + 1).trim();
if (!changedParameters.containsKey(key)) {
changedParameters.put(key, value);
} else if (!value.equals(changedParameters.get(key))) {
userConfig.setProperty(key, value);
}
}
}
} else {
onConfiguratorContent = false;
}
}
}
reader.close();
} catch (IOException e) {
throw new ConfigurationException("Error reading " + nuxeoConf, e);
} finally {
if (reader != null) {
try {
reader.close();
} catch (IOException e) {
throw new ConfigurationException(e);
}
}
}
StringBuffer newContent = new StringBuffer();
for (int i = 0; i < newLines.size(); i++) {
newContent.append(newLines.get(i).trim() + System.getProperty("line.separator"));
}
return newContent;
}
|
diff --git a/bpm/bonita-synchro-repository/bonita-synchro-jms/src/main/java/org/bonitasoft/engine/synchro/jms/TaskReadyHandler.java b/bpm/bonita-synchro-repository/bonita-synchro-jms/src/main/java/org/bonitasoft/engine/synchro/jms/TaskReadyHandler.java
index 177a34c973..e297733b19 100644
--- a/bpm/bonita-synchro-repository/bonita-synchro-jms/src/main/java/org/bonitasoft/engine/synchro/jms/TaskReadyHandler.java
+++ b/bpm/bonita-synchro-repository/bonita-synchro-jms/src/main/java/org/bonitasoft/engine/synchro/jms/TaskReadyHandler.java
@@ -1,53 +1,53 @@
/**
* Copyright (C) 2013 BonitaSoft S.A.
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* This library is free software; you can redistribute it and/or modify it under the terms
* of the GNU Lesser General Public License as published by the Free Software Foundation
* version 2.1 of the License.
* This library is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Lesser General Public License for more details.
* You should have received a copy of the GNU Lesser General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 51 Franklin Street, Fifth
* Floor, Boston, MA 02110-1301, USA.
**/
package org.bonitasoft.engine.synchro.jms;
import java.io.Serializable;
import java.util.Map;
import org.bonitasoft.engine.core.process.definition.model.SFlowNodeType;
import org.bonitasoft.engine.core.process.instance.model.SFlowNodeInstance;
import org.bonitasoft.engine.events.model.SEvent;
/**
* @author Baptiste Mesta
*/
public class TaskReadyHandler extends AbstractUpdateHandler {
private static final long serialVersionUID = 1L;
public TaskReadyHandler(final long tenantId, final JMSProducer jmsProducer) {
super(tenantId, jmsProducer);
}
@Override
protected Map<String, Serializable> getEvent(final SEvent sEvent) {
final SFlowNodeInstance flowNodeInstance = (SFlowNodeInstance) sEvent.getObject();
return PerfEventUtil.getReadyTaskEvent(flowNodeInstance.getRootContainerId(), flowNodeInstance.getName());
}
@Override
public boolean isInterested(final SEvent event) {
// the !isStateExecuting avoid having 2 times the same event in case of execution of e.g. connectors
if (event.getObject() instanceof SFlowNodeInstance) {
final SFlowNodeInstance fni = (SFlowNodeInstance) event.getObject();
boolean interested = !fni.isStateExecuting();
interested &= fni.getStateId() == 4;
- interested &= fni.getType() == SFlowNodeType.USER_TASK || fni.getType() == SFlowNodeType.MANUAL_TASK;
+ interested &= (fni.getType() == SFlowNodeType.USER_TASK || fni.getType() == SFlowNodeType.MANUAL_TASK);
return interested;
}
return false;
}
}
| true | true | public boolean isInterested(final SEvent event) {
// the !isStateExecuting avoid having 2 times the same event in case of execution of e.g. connectors
if (event.getObject() instanceof SFlowNodeInstance) {
final SFlowNodeInstance fni = (SFlowNodeInstance) event.getObject();
boolean interested = !fni.isStateExecuting();
interested &= fni.getStateId() == 4;
interested &= fni.getType() == SFlowNodeType.USER_TASK || fni.getType() == SFlowNodeType.MANUAL_TASK;
return interested;
}
return false;
}
| public boolean isInterested(final SEvent event) {
// the !isStateExecuting avoid having 2 times the same event in case of execution of e.g. connectors
if (event.getObject() instanceof SFlowNodeInstance) {
final SFlowNodeInstance fni = (SFlowNodeInstance) event.getObject();
boolean interested = !fni.isStateExecuting();
interested &= fni.getStateId() == 4;
interested &= (fni.getType() == SFlowNodeType.USER_TASK || fni.getType() == SFlowNodeType.MANUAL_TASK);
return interested;
}
return false;
}
|
diff --git a/nexus/nexus-api/src/main/java/org/sonatype/nexus/proxy/item/DefaultRepositoryItemUid.java b/nexus/nexus-api/src/main/java/org/sonatype/nexus/proxy/item/DefaultRepositoryItemUid.java
index 428d4a603..a5b5baf3b 100644
--- a/nexus/nexus-api/src/main/java/org/sonatype/nexus/proxy/item/DefaultRepositoryItemUid.java
+++ b/nexus/nexus-api/src/main/java/org/sonatype/nexus/proxy/item/DefaultRepositoryItemUid.java
@@ -1,281 +1,285 @@
/**
* Sonatype Nexus (TM) Open Source Version.
* Copyright (c) 2008 Sonatype, Inc. All rights reserved.
* Includes the third-party code listed at http://nexus.sonatype.org/dev/attributions.html
* This program is licensed to you under Version 3 only of the GNU General Public License as published by the Free Software Foundation.
* This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY;
* without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU General Public License Version 3 for more details.
* You should have received a copy of the GNU General Public License Version 3 along with this program.
* If not, see http://www.gnu.org/licenses/.
* Sonatype Nexus (TM) Professional Version is available from Sonatype, Inc.
* "Sonatype" and "Sonatype Nexus" are trademarks of Sonatype, Inc.
*/
package org.sonatype.nexus.proxy.item;
import java.util.EmptyStackException;
import java.util.HashMap;
import java.util.Map;
import java.util.Stack;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
import org.sonatype.nexus.proxy.access.Action;
import org.sonatype.nexus.proxy.repository.Repository;
/**
* The Class RepositoryItemUid. This class represents unique and constant label of all items/files originating from a
* Repository, thus backed by some storage (eg. Filesystem).
*/
public class DefaultRepositoryItemUid
implements RepositoryItemUid
{
private static enum LockStep
{
READ, WRITE, READ_WRITE_UPGRADE, SAME_AS_BEFORE;
public boolean isReadLockLastLocked()
{
return READ.equals( this );
}
}
private static final ThreadLocal<Map<String, Stack<LockStep>>> threadCtx =
new ThreadLocal<Map<String, Stack<LockStep>>>()
{
@Override
protected synchronized Map<String, Stack<LockStep>> initialValue()
{
return new HashMap<String, Stack<LockStep>>();
};
};
private final RepositoryItemUidFactory factory;
private final ReentrantReadWriteLock contentLock;
private final ReentrantReadWriteLock attributesLock;
/** The repository. */
private final Repository repository;
/** The path. */
private final String path;
protected DefaultRepositoryItemUid( RepositoryItemUidFactory factory, Repository repository, String path )
{
super();
this.factory = factory;
this.contentLock = new ReentrantReadWriteLock();
this.attributesLock = new ReentrantReadWriteLock();
this.repository = repository;
this.path = path;
}
public RepositoryItemUidFactory getRepositoryItemUidFactory()
{
return factory;
}
public Repository getRepository()
{
return repository;
}
public String getPath()
{
return path;
}
public void lock( Action action )
{
doLock( action, getLockKey(), contentLock );
}
public void unlock()
{
doUnlock( null, getLockKey(), contentLock );
}
public void lockAttributes( Action action )
{
doLock( action, getAttributeLockKey(), attributesLock );
}
public void unlockAttributes()
{
doUnlock( null, getAttributeLockKey(), attributesLock );
}
/**
* toString() will return a "string representation" of this UID in form of repoId + ":" + path
*/
@Override
public String toString()
{
return getRepository().getId() + ":" + getPath();
}
// ==
protected LockStep getLastStep( String lockKey )
{
Map<String, Stack<LockStep>> threadMap = threadCtx.get();
if ( !threadMap.containsKey( lockKey ) )
{
return null;
}
else
{
try
{
return threadMap.get( lockKey ).peek();
}
catch ( EmptyStackException e )
{
return null;
}
}
}
protected void putLastStep( String lockKey, LockStep lock )
{
Map<String, Stack<LockStep>> threadMap = threadCtx.get();
if ( lock != null )
{
if ( !threadMap.containsKey( lockKey ) )
{
threadMap.put( lockKey, new Stack<LockStep>() );
}
threadMap.get( lockKey ).push( lock );
}
else
{
Stack<LockStep> stack = threadMap.get( lockKey );
stack.pop();
// cleanup if stack is empty
if ( stack.isEmpty() )
{
threadMap.remove( lockKey );
}
}
}
protected void doLock( Action action, String lockKey, ReentrantReadWriteLock rwLock )
{
// we always go from "weaker" to "stronger" lock (read is shared, while write is exclusive lock)
// because of Nexus nature (wrong nature?), the calls are heavily boxed, hence a thread once acquired write
// may re-lock with read action. In this case, we keep the write lock, since it is "stronger"
// The proper downgrade of locks happens in unlock method, while unraveling the stack of locking steps.
LockStep step = getLastStep( lockKey );
if ( step != null && step.isReadLockLastLocked() && !action.isReadAction() )
{
// we need lock upgrade (r->w)
try
{
getActionLock( rwLock, true ).unlock();
}
catch ( IllegalMonitorStateException e )
{
- throw new IllegalMonitorStateException( "Unable to upgrade lock for: '" + lockKey + "' caused by: "
- + e.getMessage() );
+ // increasing the details level
+ IllegalMonitorStateException ie =
+ new IllegalMonitorStateException( "Unable to upgrade lock for: '" + lockKey + "' caused by: "
+ + e.getMessage() );
+ ie.initCause( e );
+ throw ie;
}
getActionLock( rwLock, action.isReadAction() ).lock();
step = LockStep.READ_WRITE_UPGRADE;
}
else if ( step == null )
{
// just lock it, this is first timer
getActionLock( rwLock, action.isReadAction() ).lock();
step = action.isReadAction() ? LockStep.READ : LockStep.WRITE;
}
else
{
// just DO NOT lock it, we already own the needed lock, and upgrade/dowgrade
// becomes unmaneagable if we have reentrant locks!
//
// example code (the call tree actually, this code may be in multiple, even recursive calls):
//
// lock(read);
// ...
// lock(read);
// ...
// lock(write); <- This call will stumble and lockup on itself, see above about upgrade
// ...
// ...
// unlock();
// ...
// unlock();
// ...
// unlock();
step = LockStep.SAME_AS_BEFORE;
}
putLastStep( lockKey, step );
}
protected void doUnlock( Action action, String lockKey, ReentrantReadWriteLock rwLock )
{
LockStep step = getLastStep( lockKey );
if ( LockStep.READ.equals( step ) )
{
getActionLock( rwLock, true ).unlock();
}
else if ( LockStep.WRITE.equals( step ) )
{
getActionLock( rwLock, false ).unlock();
}
else if ( LockStep.READ_WRITE_UPGRADE.equals( step ) )
{
// now we need to downgrade (w->r)
getActionLock( rwLock, true ).lock();
getActionLock( rwLock, false ).unlock();
}
else if ( LockStep.SAME_AS_BEFORE.equals( step ) )
{
// simply do nothing
}
putLastStep( lockKey, null );
}
private Lock getActionLock( ReadWriteLock rwLock, boolean isReadAction )
{
if ( isReadAction )
{
return rwLock.readLock();
}
else
{
return rwLock.writeLock();
}
}
private String getLockKey()
{
return toString() + " : itemlock";
}
private String getAttributeLockKey()
{
return toString() + " : attrlock";
}
}
| true | true | protected void doLock( Action action, String lockKey, ReentrantReadWriteLock rwLock )
{
// we always go from "weaker" to "stronger" lock (read is shared, while write is exclusive lock)
// because of Nexus nature (wrong nature?), the calls are heavily boxed, hence a thread once acquired write
// may re-lock with read action. In this case, we keep the write lock, since it is "stronger"
// The proper downgrade of locks happens in unlock method, while unraveling the stack of locking steps.
LockStep step = getLastStep( lockKey );
if ( step != null && step.isReadLockLastLocked() && !action.isReadAction() )
{
// we need lock upgrade (r->w)
try
{
getActionLock( rwLock, true ).unlock();
}
catch ( IllegalMonitorStateException e )
{
throw new IllegalMonitorStateException( "Unable to upgrade lock for: '" + lockKey + "' caused by: "
+ e.getMessage() );
}
getActionLock( rwLock, action.isReadAction() ).lock();
step = LockStep.READ_WRITE_UPGRADE;
}
else if ( step == null )
{
// just lock it, this is first timer
getActionLock( rwLock, action.isReadAction() ).lock();
step = action.isReadAction() ? LockStep.READ : LockStep.WRITE;
}
else
{
// just DO NOT lock it, we already own the needed lock, and upgrade/dowgrade
// becomes unmaneagable if we have reentrant locks!
//
// example code (the call tree actually, this code may be in multiple, even recursive calls):
//
// lock(read);
// ...
// lock(read);
// ...
// lock(write); <- This call will stumble and lockup on itself, see above about upgrade
// ...
// ...
// unlock();
// ...
// unlock();
// ...
// unlock();
step = LockStep.SAME_AS_BEFORE;
}
putLastStep( lockKey, step );
}
| protected void doLock( Action action, String lockKey, ReentrantReadWriteLock rwLock )
{
// we always go from "weaker" to "stronger" lock (read is shared, while write is exclusive lock)
// because of Nexus nature (wrong nature?), the calls are heavily boxed, hence a thread once acquired write
// may re-lock with read action. In this case, we keep the write lock, since it is "stronger"
// The proper downgrade of locks happens in unlock method, while unraveling the stack of locking steps.
LockStep step = getLastStep( lockKey );
if ( step != null && step.isReadLockLastLocked() && !action.isReadAction() )
{
// we need lock upgrade (r->w)
try
{
getActionLock( rwLock, true ).unlock();
}
catch ( IllegalMonitorStateException e )
{
// increasing the details level
IllegalMonitorStateException ie =
new IllegalMonitorStateException( "Unable to upgrade lock for: '" + lockKey + "' caused by: "
+ e.getMessage() );
ie.initCause( e );
throw ie;
}
getActionLock( rwLock, action.isReadAction() ).lock();
step = LockStep.READ_WRITE_UPGRADE;
}
else if ( step == null )
{
// just lock it, this is first timer
getActionLock( rwLock, action.isReadAction() ).lock();
step = action.isReadAction() ? LockStep.READ : LockStep.WRITE;
}
else
{
// just DO NOT lock it, we already own the needed lock, and upgrade/dowgrade
// becomes unmaneagable if we have reentrant locks!
//
// example code (the call tree actually, this code may be in multiple, even recursive calls):
//
// lock(read);
// ...
// lock(read);
// ...
// lock(write); <- This call will stumble and lockup on itself, see above about upgrade
// ...
// ...
// unlock();
// ...
// unlock();
// ...
// unlock();
step = LockStep.SAME_AS_BEFORE;
}
putLastStep( lockKey, step );
}
|
diff --git a/src/com/digitallizard/bbcnewsreader/data/DatabaseHandler.java b/src/com/digitallizard/bbcnewsreader/data/DatabaseHandler.java
index df19eab..5d01262 100644
--- a/src/com/digitallizard/bbcnewsreader/data/DatabaseHandler.java
+++ b/src/com/digitallizard/bbcnewsreader/data/DatabaseHandler.java
@@ -1,527 +1,524 @@
/*******************************************************************************
* BBC News Reader
* Released under the BSD License. See README or LICENSE.
* Copyright (c) 2011, Digital Lizard (Oscar Key, Thomas Boby)
* All rights reserved.
******************************************************************************/
package com.digitallizard.bbcnewsreader.data;
import java.util.ArrayList;
import java.util.Date;
import android.content.ContentResolver;
import android.content.ContentValues;
import android.content.Context;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.database.sqlite.SQLiteQueryBuilder;
import android.net.Uri;
import android.text.method.MovementMethod;
import com.digitallizard.bbcnewsreader.NewsItem;
import com.digitallizard.bbcnewsreader.R;
public class DatabaseHandler extends SQLiteOpenHelper {
private static final String DATABASE_NAME = "bbcnewsreader.db";
private static final int DATABASE_VERSION = 2;
private static final String ITEM_TABLE = "items";
private static final String CATEGORY_TABLE = "categories";
private static final String ITEM_CATEGORY_TABLE = "categories_items";
private static final String CREATE_ITEM_TABLE = "CREATE TABLE " + ITEM_TABLE + "(item_Id integer PRIMARY KEY," + "title varchar(255), "
+ "description varchar(255), " + "link varchar(255) UNIQUE, " + "pubdate int, " + "html blob, " + "image blob, " + "thumbnail blob,"
+ "thumbnailurl varchar(255))";
private static final String CREATE_CATEGORY_TABLE = "CREATE TABLE " + CATEGORY_TABLE + "(category_Id integer PRIMARY KEY," + "name varchar(255),"
+ "enabled int," + "url varchar(255))";
private static final String CREATE_RELATIONSHIP_TABLE = "CREATE TABLE " + ITEM_CATEGORY_TABLE + "(categoryName varchar(255), " + "itemId INT,"
+ "priority int," + "PRIMARY KEY (categoryName, itemId))";
public static final String COLUMN_HTML = "html";
public static final String COLUMN_THUMBNAIL = "thumbnail";
public static final String COLUMN_IMAGE = "image";
private Context context;
private SQLiteDatabase db;
private long clearOutAgeMilliSecs; // the number of days to keep news items
private boolean methodInsertWithConflictExists; // used to determine if the required method exists
private ContentResolver contentResolver;
/**
* Inserts an RSSItem into the items table, then creates an entry in the relationship table between it and its category, ONLY if it is more recent
* than a month.
*
* @param title
* News item's Title as String
* @param description
* News item's Description as String
* @param link
* News item's link as String
* @param pubdate
* News item's published data as String
* @param category
* News item's category as String
*/
public void insertItem(String title, String description, String category, Date pubdate, String url, String thumbnailUrl, int priority) {
// convert the date into a timestamp
long timestamp = pubdate.getTime();
Date now = new Date();
// check if this news is older than we want to store
if (timestamp < (now.getTime() - clearOutAgeMilliSecs)) {
// bail here, don't insert it
return;
}
// request an insert
Uri uri = Uri.withAppendedPath(DatabaseProvider.CONTENT_URI_ITEMS_BY_CATEGORY, category);
ContentValues values = new ContentValues(5);
values.put(DatabaseHelper.COLUMN_ITEM_TITLE, title);
values.put(DatabaseHelper.COLUMN_ITEM_PUBDATE, timestamp);
values.put(DatabaseHelper.COLUMN_ITEM_URL, url);
values.put(DatabaseHelper.COLUMN_ITEM_THUMBNAIL_URL, thumbnailUrl);
values.put(DatabaseHelper.COLUMN_RELATIONSHIP_PRIORITY, priority);
contentResolver.insert(uri, values);
}
public void addHtml(int itemId, byte[] html) {
Uri uri = Uri.withAppendedPath(DatabaseProvider.CONTENT_URI_ITEMS, Integer.toString(itemId));
ContentValues values = new ContentValues(1);
values.put(DatabaseHelper.COLUMN_ITEM_HTML, html);
contentResolver.update(uri, values, null, null);
}
public byte[] getHtml(int itemId) {
Uri uri = Uri.withAppendedPath(DatabaseProvider.CONTENT_URI_ITEMS, Integer.toString(itemId));
Cursor cursor = contentResolver.query(uri, new String[] { DatabaseHelper.COLUMN_ITEM_HTML }, null, null, null);
cursor.moveToFirst();
byte[] html = cursor.getBlob(0);
cursor.close();
return html;
}
public void addImage(int itemId, byte[] image) {
// currently does nothing
}
public byte[] getImage(int itemId) {
// currently does nothing
return null;
}
public void addThumbnail(int itemId, byte[] thumbnail) {
Uri uri = Uri.withAppendedPath(DatabaseProvider.CONTENT_URI_ITEMS, Integer.toString(itemId));
ContentValues values = new ContentValues(1);
values.put(DatabaseHelper.COLUMN_ITEM_THUMBNAIL, thumbnail);
contentResolver.update(uri, values, null, null);
}
public byte[] getThumbnail(int itemId) {
Uri uri = Uri.withAppendedPath(DatabaseProvider.CONTENT_URI_ITEMS, Integer.toString(itemId));
Cursor cursor = contentResolver.query(uri, new String[] { DatabaseHelper.COLUMN_ITEM_THUMBNAIL }, null, null, null);
cursor.moveToFirst();
byte[] thumbnail = cursor.getBlob(0);
cursor.close();
return thumbnail;
}
public String getUrl(int itemId) {
Uri uri = Uri.withAppendedPath(DatabaseProvider.CONTENT_URI_ITEMS, Integer.toString(itemId));
Cursor cursor = contentResolver.query(uri, new String[] { DatabaseHelper.COLUMN_ITEM_URL }, null, null, null);
cursor.moveToFirst();
String url = cursor.getString(0);
cursor.close();
return url;
}
public String getThumbnailUrl(int itemId) {
Uri uri = Uri.withAppendedPath(DatabaseProvider.CONTENT_URI_ITEMS, Integer.toString(itemId));
Cursor cursor = contentResolver.query(uri, new String[] { DatabaseHelper.COLUMN_ITEM_THUMBNAIL_URL }, null, null, null);
cursor.moveToFirst();
String url = cursor.getString(0);
cursor.close();
return url;
}
/**
* Fetches all the undownloaded items from the last "days" days. Returns an array containing the item Ids of all these items
*
* @param days
* Number of days into the past to return undownloaded items for (Using timestamp from entry)
* @return A 2d int[3][n], where 3 is the type of item and n is the number of undownloaded items of that type. type is either 0, 1 or 2 for html,
* thumbnail or image respectively.
*/
public Integer[][] getUndownloaded(int days) {
Date now = new Date();
long curTime = now.getTime();
long timeComparison = curTime - 86400000L * days;
String timeComparisonS = Long.toString(timeComparison);
Cursor cursorArticles = db.query(ITEM_TABLE, new String[] { "item_Id" }, "html IS NULL AND pubdate>?", new String[] { timeComparisonS },
null, null, null);
Cursor cursorThumbnails = db.query(ITEM_TABLE, new String[] { "item_Id" }, "thumbnail IS NULL AND pubdate>?",
new String[] { timeComparisonS }, null, null, null);
Cursor cursorImages = db.query(ITEM_TABLE, new String[] { "item_Id" }, "image IS NULL AND pubdate>?", new String[] { timeComparisonS }, null,
null, null);
ArrayList<Integer> unloadedArticles = new ArrayList<Integer>();
ArrayList<Integer> unloadedThumbnails = new ArrayList<Integer>();
ArrayList<Integer> unloadedImages = new ArrayList<Integer>();
// loop through and store the ids of the articles that need to be loaded
for (int i = 0; i < cursorArticles.getCount(); i++) {
cursorArticles.moveToNext();
unloadedArticles.add(cursorArticles.getInt(0));
}
// loop through and store the ids of the thumbnails that need to be loaded
for (int i = 0; i < cursorThumbnails.getCount(); i++) {
cursorThumbnails.moveToNext();
unloadedThumbnails.add(cursorThumbnails.getInt(0));
}
// loop through and store the ids of the images that need to be loaded
for (int i = 0; i < cursorImages.getCount(); i++) {
cursorImages.moveToNext();
unloadedImages.add(cursorImages.getInt(0));
}
cursorArticles.close();
cursorThumbnails.close();
cursorImages.close();
Integer[][] values = new Integer[3][];
values[0] = unloadedArticles.toArray(new Integer[unloadedArticles.size()]);
values[1] = unloadedThumbnails.toArray(new Integer[unloadedThumbnails.size()]);
values[2] = unloadedImages.toArray(new Integer[unloadedImages.size()]);
return values;
}
/**
* Fetches all the undownloaded items from the last "days" days. Returns an array containing the item Ids of all these items
*
* @param category
* The category to retrieve undownloaded items from
* @param days
* Number of days into the past to return undownloaded items for (Using timestamp from entry)
* @return A 2d int[n], where n is the number of undownloaded items.
*/
public Integer[] getUndownloaded(String category, String column, int numItems) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setDistinct(true);
queryBuilder.setTables("items JOIN categories_items ON items.item_Id=categories_items.itemId");
String[] selectionArgs = new String[] { "item_Id", "items." + column };
String whereStatement = "categories_items.categoryName=?";
String[] whereArgs = new String[] { category };
Cursor cursor = queryBuilder.query(db, selectionArgs, whereStatement, whereArgs, null, null, "categories_items.priority ASC",
Integer.toString(numItems));
// Log.v("database", "query: "+queryBuilder.buildQuery(selectionArgs, whereStatement, whereArgs, null, null, "pubdate DESC",
// Integer.toString(numItems)));
ArrayList<Integer> unloadedItems = new ArrayList<Integer>();
// loop through and store the ids of the articles that need to be loaded
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToNext();
// check if we need to download this
if (cursor.isNull(1)) {
unloadedItems.add(cursor.getInt(0));
}
}
cursor.close();
return unloadedItems.toArray(new Integer[unloadedItems.size()]);
}
/**
* Inserts a category into the category table.
*
* @param name
* Name of the category as String
* @param enabled
* Whether the RSSFeed should be fetched as Boolean
*/
public void insertCategory(String name, boolean enabled, String url) {
Uri uri = DatabaseProvider.CONTENT_URI_CATEGORIES;
int enabledInt = (enabled) ? 1 : 0;
ContentValues values = new ContentValues(3);
values.put(DatabaseHelper.COLUMN_CATEGORY_NAME, name);
values.put(DatabaseHelper.COLUMN_CATEGORY_ENABLED, enabledInt);
values.put(DatabaseHelper.COLUMN_CATEGORY_URL, url);
contentResolver.insert(uri, values);
db.insert(CATEGORY_TABLE, null, values);
}
/**
* Takes a category and returns all the title, description ,link and item_Id of all the items related to it. Returns null if no items exists
*
* @param category
* The Case-sensitive name of the category
* @param limit
* for the number of items to return
* @return NewsItem[]
*/
public NewsItem[] getItems(String category, int limit) {
// ask the content provider for the items
Uri uri = DatabaseProvider.CONTENT_URI_ITEMS;
String[] projection = new String[] {DatabaseHelper.COLUMN_ITEM_ID, DatabaseHelper.COLUMN_ITEM_TITLE, DatabaseHelper.COLUMN_ITEM_DESCRIPTION,
DatabaseHelper.COLUMN_ITEM_URL, DatabaseHelper.COLUMN_ITEM_THUMBNAIL};
String sortOrder = DatabaseHelper.RELATIONSHIP_TABLE + "." + DatabaseHelper.COLUMN_RELATIONSHIP_PRIORITY + " ASC";
Cursor cursor = contentResolver.query(uri, projection, null, null, sortOrder);
// load the column names
int id = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_ID);
int title = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_TITLE);
int description = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_DESCRIPTION);
int url = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_URL);
int thumbnail = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_THUMBNAIL);
// load the items into an array
NewsItem[] items = new NewsItem[cursor.getCount()];
- cursor.moveToFirst();
while(cursor.moveToNext() && cursor.getPosition() < limit){
NewsItem item = new NewsItem(); // initialize a new item
item.setId(cursor.getInt(id));
item.setTitle(cursor.getString(title));
item.setDescription(cursor.getString(description));
item.setUrl(cursor.getString(url));
item.setThumbnailBytes(cursor.getBlob(thumbnail));
items[cursor.getCount()] = item; // add this item to the array
}
cursor.close();
return items;
}
/**
* Queries the categories table for the enabled column of all rows, returning an array of booleans representing whether categories are enabled or
* not, sorted by category_Id.
*
* @return boolean[] containing enabled column from categories table.
*/
public boolean[] getCategoryBooleans() {
Uri uri = DatabaseProvider.CONTENT_URI_CATEGORIES;
String[] projection = new String[] { DatabaseHelper.COLUMN_CATEGORY_ENABLED };
Cursor cursor = contentResolver.query(uri, projection, null, null, DatabaseHelper.COLUMN_CATEGORY_ID);
boolean[] enabledCategories = new boolean[cursor.getCount()];
- cursor.moveToFirst();
while (cursor.moveToNext()) {
if (cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_CATEGORY_ENABLED)) == 0) {
enabledCategories[cursor.getPosition() - 1] = false;
}
else {
enabledCategories[cursor.getPosition() - 1] = true;
}
}
cursor.close();
return enabledCategories;
}
/**
* Returns the links and names of all the categories that are enabled.
*
* @return A string[][] containing the String urls in [0] and String names in [1].
*/
public String[][] getEnabledCategories() {
Uri uri = DatabaseProvider.CONTENT_URI_ENABLED_CATEGORIES; // uri for enabled categories
String[] projection = new String[] { DatabaseHelper.COLUMN_CATEGORY_URL, DatabaseHelper.COLUMN_CATEGORY_NAME };
Cursor cursor = contentResolver.query(uri, projection, null, null, DatabaseHelper.COLUMN_CATEGORY_ID);
String[][] categories = new String[2][cursor.getCount()];
- cursor.moveToFirst();
while (cursor.moveToNext()) {
categories[0][cursor.getPosition() - 1] = cursor.getString(0);
categories[1][cursor.getPosition() - 1] = cursor.getString(1);
}
cursor.close();
return categories;
}
/**
* Sets the given category to the given boolean
*
* @param category
* The String category you wish to change.
* @param enabled
* The boolean value you wish to set it to.
*/
public void setCategoryEnabled(String category, boolean enabled) {
// update this category
ContentValues values = new ContentValues(1);
if (enabled) {
values.put("enabled", 1);
}
else {
values.put("enabled", 0);
}
// update the database with these values
db.update(CATEGORY_TABLE, values, "name=?", new String[] { category });
}
/**
* Takes an array of booleans and sets the first n categories to those values. Where n is length of array
*
* @param enabled
* A boolean array of "enabled" values
*/
public void setEnabledCategories(boolean[] enabled) throws NullPointerException {
ContentValues values = new ContentValues(1);
for (int i = 0; i < enabled.length; i++) {
if (enabled[i]) {
values.put("enabled", 1);
}
else {
values.put("enabled", 0);
}
db.update(CATEGORY_TABLE, values, "category_Id=?", new String[] { Integer.toString(i + 1) });
values.clear();
}
}
/**
* When called will remove all articles that are over the threshold to the second old. Then cleans up the relationship table. Possibly resource
* intensive.
*/
public void clearOld() {
// delete items older than the threshold
Date now = new Date();
long cutoffTime = (now.getTime() - clearOutAgeMilliSecs);
/*// FIXME Optimise?
// Creates a java.util date object with current time
// Subtracts one month in milliseconds and deletes all
// items with a pubdate less than that value.
Date now = new Date();
long oldTime = (now.getTime() - clearOutAgeMilliSecs);
Cursor cursor = db.query(ITEM_TABLE, new String[] { "item_Id" }, "pubdate<?", new String[] { Long.toString(oldTime) }, null, null, null);
for (int i = 1; i <= cursor.getCount(); i++) {
cursor.moveToNext();
db.delete(ITEM_CATEGORY_TABLE, "itemId=?", new String[] { Integer.toString(cursor.getInt(0)) });
}
db.delete(ITEM_TABLE, "pubdate<?", new String[] { Long.toString(oldTime) });
cursor.close();*/
}
/**
* Adds all the start categories from the XML
*/
public void addCategoriesFromXml() {
try {
String[] categoryNames = context.getResources().getStringArray(R.array.category_names);
String[] categoryUrls = context.getResources().getStringArray(R.array.catergory_rss_urls);
int[] categoryBooleans = context.getResources().getIntArray(R.array.category_default_booleans);
for (int i = 0; i < categoryNames.length; i++) {
boolean enabled = true;
if (categoryBooleans[i] == 0) {
enabled = false;
}
insertCategory(categoryNames[i], enabled, categoryUrls[i]);
}
} catch (NullPointerException e) {
// Log.e("Database", "Categories XML is broken.");
}
}
/**
* Checks whether there are any records in category
*
* @return true or false
*/
public boolean isCreated() {
try {
getCategoryBooleans()[0] = true;
return true;
} catch (Exception e) {
return false;
}
}
/**
* Drops the entire database.
*/
public void dropTables() {
db.execSQL("DROP TABLE " + ITEM_TABLE);
db.execSQL("DROP TABLE " + CATEGORY_TABLE);
db.execSQL("DROP TABLE " + ITEM_CATEGORY_TABLE);
}
/**
* Attempts to create the tables.
*/
public void createTables() {
db.execSQL(CREATE_ITEM_TABLE);
db.execSQL(CREATE_CATEGORY_TABLE);
db.execSQL(CREATE_RELATIONSHIP_TABLE);
}
@Override
public void onCreate(SQLiteDatabase db) {
// nothing to do
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// check what version to version upgrade we are performing
if (oldVersion == 1 && newVersion == 2) {
// drop tables
db.execSQL("DROP TABLE " + ITEM_TABLE);
db.execSQL("DROP TABLE " + ITEM_CATEGORY_TABLE);
// create tables
db.execSQL(CREATE_ITEM_TABLE);
db.execSQL(CREATE_RELATIONSHIP_TABLE);
}
else {
// reset everything to be sure
dropTables();
createTables();
}
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// reset the database
dropTables();
createTables();
}
public void finish() {
// close the database
db.close();
db = null;
}
void checkCompatibilty() {
// check if the insertWithOnConflict exists
try {
SQLiteDatabase.class.getMethod("insertWithOnConflict", new Class[] { String.class, String.class, ContentValues.class, Integer.TYPE });
// success, this method exists, set the boolean
methodInsertWithConflictExists = true;
} catch (NoSuchMethodException e) {
// failure, set the boolean
methodInsertWithConflictExists = false;
}
}
@Override
protected void finalize() throws Throwable {
// use try-catch to make sure we do not break super
try {
// make sure the database has been shutdown
if (db != null) {
db.close();
db = null;
}
} finally {
super.finalize();
}
}
public DatabaseHandler(Context context, int clearOutAgeDays) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
this.contentResolver = context.getContentResolver();
this.clearOutAgeMilliSecs = (clearOutAgeDays * 24 * 60 * 60 * 1000);
this.db = this.getWritableDatabase();
// check compatibility with this version of Android
checkCompatibilty();
}
}
| false | true | public Integer[][] getUndownloaded(int days) {
Date now = new Date();
long curTime = now.getTime();
long timeComparison = curTime - 86400000L * days;
String timeComparisonS = Long.toString(timeComparison);
Cursor cursorArticles = db.query(ITEM_TABLE, new String[] { "item_Id" }, "html IS NULL AND pubdate>?", new String[] { timeComparisonS },
null, null, null);
Cursor cursorThumbnails = db.query(ITEM_TABLE, new String[] { "item_Id" }, "thumbnail IS NULL AND pubdate>?",
new String[] { timeComparisonS }, null, null, null);
Cursor cursorImages = db.query(ITEM_TABLE, new String[] { "item_Id" }, "image IS NULL AND pubdate>?", new String[] { timeComparisonS }, null,
null, null);
ArrayList<Integer> unloadedArticles = new ArrayList<Integer>();
ArrayList<Integer> unloadedThumbnails = new ArrayList<Integer>();
ArrayList<Integer> unloadedImages = new ArrayList<Integer>();
// loop through and store the ids of the articles that need to be loaded
for (int i = 0; i < cursorArticles.getCount(); i++) {
cursorArticles.moveToNext();
unloadedArticles.add(cursorArticles.getInt(0));
}
// loop through and store the ids of the thumbnails that need to be loaded
for (int i = 0; i < cursorThumbnails.getCount(); i++) {
cursorThumbnails.moveToNext();
unloadedThumbnails.add(cursorThumbnails.getInt(0));
}
// loop through and store the ids of the images that need to be loaded
for (int i = 0; i < cursorImages.getCount(); i++) {
cursorImages.moveToNext();
unloadedImages.add(cursorImages.getInt(0));
}
cursorArticles.close();
cursorThumbnails.close();
cursorImages.close();
Integer[][] values = new Integer[3][];
values[0] = unloadedArticles.toArray(new Integer[unloadedArticles.size()]);
values[1] = unloadedThumbnails.toArray(new Integer[unloadedThumbnails.size()]);
values[2] = unloadedImages.toArray(new Integer[unloadedImages.size()]);
return values;
}
/**
* Fetches all the undownloaded items from the last "days" days. Returns an array containing the item Ids of all these items
*
* @param category
* The category to retrieve undownloaded items from
* @param days
* Number of days into the past to return undownloaded items for (Using timestamp from entry)
* @return A 2d int[n], where n is the number of undownloaded items.
*/
public Integer[] getUndownloaded(String category, String column, int numItems) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setDistinct(true);
queryBuilder.setTables("items JOIN categories_items ON items.item_Id=categories_items.itemId");
String[] selectionArgs = new String[] { "item_Id", "items." + column };
String whereStatement = "categories_items.categoryName=?";
String[] whereArgs = new String[] { category };
Cursor cursor = queryBuilder.query(db, selectionArgs, whereStatement, whereArgs, null, null, "categories_items.priority ASC",
Integer.toString(numItems));
// Log.v("database", "query: "+queryBuilder.buildQuery(selectionArgs, whereStatement, whereArgs, null, null, "pubdate DESC",
// Integer.toString(numItems)));
ArrayList<Integer> unloadedItems = new ArrayList<Integer>();
// loop through and store the ids of the articles that need to be loaded
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToNext();
// check if we need to download this
if (cursor.isNull(1)) {
unloadedItems.add(cursor.getInt(0));
}
}
cursor.close();
return unloadedItems.toArray(new Integer[unloadedItems.size()]);
}
/**
* Inserts a category into the category table.
*
* @param name
* Name of the category as String
* @param enabled
* Whether the RSSFeed should be fetched as Boolean
*/
public void insertCategory(String name, boolean enabled, String url) {
Uri uri = DatabaseProvider.CONTENT_URI_CATEGORIES;
int enabledInt = (enabled) ? 1 : 0;
ContentValues values = new ContentValues(3);
values.put(DatabaseHelper.COLUMN_CATEGORY_NAME, name);
values.put(DatabaseHelper.COLUMN_CATEGORY_ENABLED, enabledInt);
values.put(DatabaseHelper.COLUMN_CATEGORY_URL, url);
contentResolver.insert(uri, values);
db.insert(CATEGORY_TABLE, null, values);
}
/**
* Takes a category and returns all the title, description ,link and item_Id of all the items related to it. Returns null if no items exists
*
* @param category
* The Case-sensitive name of the category
* @param limit
* for the number of items to return
* @return NewsItem[]
*/
public NewsItem[] getItems(String category, int limit) {
// ask the content provider for the items
Uri uri = DatabaseProvider.CONTENT_URI_ITEMS;
String[] projection = new String[] {DatabaseHelper.COLUMN_ITEM_ID, DatabaseHelper.COLUMN_ITEM_TITLE, DatabaseHelper.COLUMN_ITEM_DESCRIPTION,
DatabaseHelper.COLUMN_ITEM_URL, DatabaseHelper.COLUMN_ITEM_THUMBNAIL};
String sortOrder = DatabaseHelper.RELATIONSHIP_TABLE + "." + DatabaseHelper.COLUMN_RELATIONSHIP_PRIORITY + " ASC";
Cursor cursor = contentResolver.query(uri, projection, null, null, sortOrder);
// load the column names
int id = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_ID);
int title = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_TITLE);
int description = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_DESCRIPTION);
int url = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_URL);
int thumbnail = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_THUMBNAIL);
// load the items into an array
NewsItem[] items = new NewsItem[cursor.getCount()];
cursor.moveToFirst();
while(cursor.moveToNext() && cursor.getPosition() < limit){
NewsItem item = new NewsItem(); // initialize a new item
item.setId(cursor.getInt(id));
item.setTitle(cursor.getString(title));
item.setDescription(cursor.getString(description));
item.setUrl(cursor.getString(url));
item.setThumbnailBytes(cursor.getBlob(thumbnail));
items[cursor.getCount()] = item; // add this item to the array
}
cursor.close();
return items;
}
/**
* Queries the categories table for the enabled column of all rows, returning an array of booleans representing whether categories are enabled or
* not, sorted by category_Id.
*
* @return boolean[] containing enabled column from categories table.
*/
public boolean[] getCategoryBooleans() {
Uri uri = DatabaseProvider.CONTENT_URI_CATEGORIES;
String[] projection = new String[] { DatabaseHelper.COLUMN_CATEGORY_ENABLED };
Cursor cursor = contentResolver.query(uri, projection, null, null, DatabaseHelper.COLUMN_CATEGORY_ID);
boolean[] enabledCategories = new boolean[cursor.getCount()];
cursor.moveToFirst();
while (cursor.moveToNext()) {
if (cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_CATEGORY_ENABLED)) == 0) {
enabledCategories[cursor.getPosition() - 1] = false;
}
else {
enabledCategories[cursor.getPosition() - 1] = true;
}
}
cursor.close();
return enabledCategories;
}
/**
* Returns the links and names of all the categories that are enabled.
*
* @return A string[][] containing the String urls in [0] and String names in [1].
*/
public String[][] getEnabledCategories() {
Uri uri = DatabaseProvider.CONTENT_URI_ENABLED_CATEGORIES; // uri for enabled categories
String[] projection = new String[] { DatabaseHelper.COLUMN_CATEGORY_URL, DatabaseHelper.COLUMN_CATEGORY_NAME };
Cursor cursor = contentResolver.query(uri, projection, null, null, DatabaseHelper.COLUMN_CATEGORY_ID);
String[][] categories = new String[2][cursor.getCount()];
cursor.moveToFirst();
while (cursor.moveToNext()) {
categories[0][cursor.getPosition() - 1] = cursor.getString(0);
categories[1][cursor.getPosition() - 1] = cursor.getString(1);
}
cursor.close();
return categories;
}
/**
* Sets the given category to the given boolean
*
* @param category
* The String category you wish to change.
* @param enabled
* The boolean value you wish to set it to.
*/
public void setCategoryEnabled(String category, boolean enabled) {
// update this category
ContentValues values = new ContentValues(1);
if (enabled) {
values.put("enabled", 1);
}
else {
values.put("enabled", 0);
}
// update the database with these values
db.update(CATEGORY_TABLE, values, "name=?", new String[] { category });
}
/**
* Takes an array of booleans and sets the first n categories to those values. Where n is length of array
*
* @param enabled
* A boolean array of "enabled" values
*/
public void setEnabledCategories(boolean[] enabled) throws NullPointerException {
ContentValues values = new ContentValues(1);
for (int i = 0; i < enabled.length; i++) {
if (enabled[i]) {
values.put("enabled", 1);
}
else {
values.put("enabled", 0);
}
db.update(CATEGORY_TABLE, values, "category_Id=?", new String[] { Integer.toString(i + 1) });
values.clear();
}
}
/**
* When called will remove all articles that are over the threshold to the second old. Then cleans up the relationship table. Possibly resource
* intensive.
*/
public void clearOld() {
// delete items older than the threshold
Date now = new Date();
long cutoffTime = (now.getTime() - clearOutAgeMilliSecs);
/*// FIXME Optimise?
// Creates a java.util date object with current time
// Subtracts one month in milliseconds and deletes all
// items with a pubdate less than that value.
Date now = new Date();
long oldTime = (now.getTime() - clearOutAgeMilliSecs);
Cursor cursor = db.query(ITEM_TABLE, new String[] { "item_Id" }, "pubdate<?", new String[] { Long.toString(oldTime) }, null, null, null);
for (int i = 1; i <= cursor.getCount(); i++) {
cursor.moveToNext();
db.delete(ITEM_CATEGORY_TABLE, "itemId=?", new String[] { Integer.toString(cursor.getInt(0)) });
}
db.delete(ITEM_TABLE, "pubdate<?", new String[] { Long.toString(oldTime) });
cursor.close();*/
}
/**
* Adds all the start categories from the XML
*/
public void addCategoriesFromXml() {
try {
String[] categoryNames = context.getResources().getStringArray(R.array.category_names);
String[] categoryUrls = context.getResources().getStringArray(R.array.catergory_rss_urls);
int[] categoryBooleans = context.getResources().getIntArray(R.array.category_default_booleans);
for (int i = 0; i < categoryNames.length; i++) {
boolean enabled = true;
if (categoryBooleans[i] == 0) {
enabled = false;
}
insertCategory(categoryNames[i], enabled, categoryUrls[i]);
}
} catch (NullPointerException e) {
// Log.e("Database", "Categories XML is broken.");
}
}
/**
* Checks whether there are any records in category
*
* @return true or false
*/
public boolean isCreated() {
try {
getCategoryBooleans()[0] = true;
return true;
} catch (Exception e) {
return false;
}
}
/**
* Drops the entire database.
*/
public void dropTables() {
db.execSQL("DROP TABLE " + ITEM_TABLE);
db.execSQL("DROP TABLE " + CATEGORY_TABLE);
db.execSQL("DROP TABLE " + ITEM_CATEGORY_TABLE);
}
/**
* Attempts to create the tables.
*/
public void createTables() {
db.execSQL(CREATE_ITEM_TABLE);
db.execSQL(CREATE_CATEGORY_TABLE);
db.execSQL(CREATE_RELATIONSHIP_TABLE);
}
@Override
public void onCreate(SQLiteDatabase db) {
// nothing to do
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// check what version to version upgrade we are performing
if (oldVersion == 1 && newVersion == 2) {
// drop tables
db.execSQL("DROP TABLE " + ITEM_TABLE);
db.execSQL("DROP TABLE " + ITEM_CATEGORY_TABLE);
// create tables
db.execSQL(CREATE_ITEM_TABLE);
db.execSQL(CREATE_RELATIONSHIP_TABLE);
}
else {
// reset everything to be sure
dropTables();
createTables();
}
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// reset the database
dropTables();
createTables();
}
public void finish() {
// close the database
db.close();
db = null;
}
void checkCompatibilty() {
// check if the insertWithOnConflict exists
try {
SQLiteDatabase.class.getMethod("insertWithOnConflict", new Class[] { String.class, String.class, ContentValues.class, Integer.TYPE });
// success, this method exists, set the boolean
methodInsertWithConflictExists = true;
} catch (NoSuchMethodException e) {
// failure, set the boolean
methodInsertWithConflictExists = false;
}
}
@Override
protected void finalize() throws Throwable {
// use try-catch to make sure we do not break super
try {
// make sure the database has been shutdown
if (db != null) {
db.close();
db = null;
}
} finally {
super.finalize();
}
}
public DatabaseHandler(Context context, int clearOutAgeDays) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
this.contentResolver = context.getContentResolver();
this.clearOutAgeMilliSecs = (clearOutAgeDays * 24 * 60 * 60 * 1000);
this.db = this.getWritableDatabase();
// check compatibility with this version of Android
checkCompatibilty();
}
}
| public Integer[][] getUndownloaded(int days) {
Date now = new Date();
long curTime = now.getTime();
long timeComparison = curTime - 86400000L * days;
String timeComparisonS = Long.toString(timeComparison);
Cursor cursorArticles = db.query(ITEM_TABLE, new String[] { "item_Id" }, "html IS NULL AND pubdate>?", new String[] { timeComparisonS },
null, null, null);
Cursor cursorThumbnails = db.query(ITEM_TABLE, new String[] { "item_Id" }, "thumbnail IS NULL AND pubdate>?",
new String[] { timeComparisonS }, null, null, null);
Cursor cursorImages = db.query(ITEM_TABLE, new String[] { "item_Id" }, "image IS NULL AND pubdate>?", new String[] { timeComparisonS }, null,
null, null);
ArrayList<Integer> unloadedArticles = new ArrayList<Integer>();
ArrayList<Integer> unloadedThumbnails = new ArrayList<Integer>();
ArrayList<Integer> unloadedImages = new ArrayList<Integer>();
// loop through and store the ids of the articles that need to be loaded
for (int i = 0; i < cursorArticles.getCount(); i++) {
cursorArticles.moveToNext();
unloadedArticles.add(cursorArticles.getInt(0));
}
// loop through and store the ids of the thumbnails that need to be loaded
for (int i = 0; i < cursorThumbnails.getCount(); i++) {
cursorThumbnails.moveToNext();
unloadedThumbnails.add(cursorThumbnails.getInt(0));
}
// loop through and store the ids of the images that need to be loaded
for (int i = 0; i < cursorImages.getCount(); i++) {
cursorImages.moveToNext();
unloadedImages.add(cursorImages.getInt(0));
}
cursorArticles.close();
cursorThumbnails.close();
cursorImages.close();
Integer[][] values = new Integer[3][];
values[0] = unloadedArticles.toArray(new Integer[unloadedArticles.size()]);
values[1] = unloadedThumbnails.toArray(new Integer[unloadedThumbnails.size()]);
values[2] = unloadedImages.toArray(new Integer[unloadedImages.size()]);
return values;
}
/**
* Fetches all the undownloaded items from the last "days" days. Returns an array containing the item Ids of all these items
*
* @param category
* The category to retrieve undownloaded items from
* @param days
* Number of days into the past to return undownloaded items for (Using timestamp from entry)
* @return A 2d int[n], where n is the number of undownloaded items.
*/
public Integer[] getUndownloaded(String category, String column, int numItems) {
SQLiteQueryBuilder queryBuilder = new SQLiteQueryBuilder();
queryBuilder.setDistinct(true);
queryBuilder.setTables("items JOIN categories_items ON items.item_Id=categories_items.itemId");
String[] selectionArgs = new String[] { "item_Id", "items." + column };
String whereStatement = "categories_items.categoryName=?";
String[] whereArgs = new String[] { category };
Cursor cursor = queryBuilder.query(db, selectionArgs, whereStatement, whereArgs, null, null, "categories_items.priority ASC",
Integer.toString(numItems));
// Log.v("database", "query: "+queryBuilder.buildQuery(selectionArgs, whereStatement, whereArgs, null, null, "pubdate DESC",
// Integer.toString(numItems)));
ArrayList<Integer> unloadedItems = new ArrayList<Integer>();
// loop through and store the ids of the articles that need to be loaded
for (int i = 0; i < cursor.getCount(); i++) {
cursor.moveToNext();
// check if we need to download this
if (cursor.isNull(1)) {
unloadedItems.add(cursor.getInt(0));
}
}
cursor.close();
return unloadedItems.toArray(new Integer[unloadedItems.size()]);
}
/**
* Inserts a category into the category table.
*
* @param name
* Name of the category as String
* @param enabled
* Whether the RSSFeed should be fetched as Boolean
*/
public void insertCategory(String name, boolean enabled, String url) {
Uri uri = DatabaseProvider.CONTENT_URI_CATEGORIES;
int enabledInt = (enabled) ? 1 : 0;
ContentValues values = new ContentValues(3);
values.put(DatabaseHelper.COLUMN_CATEGORY_NAME, name);
values.put(DatabaseHelper.COLUMN_CATEGORY_ENABLED, enabledInt);
values.put(DatabaseHelper.COLUMN_CATEGORY_URL, url);
contentResolver.insert(uri, values);
db.insert(CATEGORY_TABLE, null, values);
}
/**
* Takes a category and returns all the title, description ,link and item_Id of all the items related to it. Returns null if no items exists
*
* @param category
* The Case-sensitive name of the category
* @param limit
* for the number of items to return
* @return NewsItem[]
*/
public NewsItem[] getItems(String category, int limit) {
// ask the content provider for the items
Uri uri = DatabaseProvider.CONTENT_URI_ITEMS;
String[] projection = new String[] {DatabaseHelper.COLUMN_ITEM_ID, DatabaseHelper.COLUMN_ITEM_TITLE, DatabaseHelper.COLUMN_ITEM_DESCRIPTION,
DatabaseHelper.COLUMN_ITEM_URL, DatabaseHelper.COLUMN_ITEM_THUMBNAIL};
String sortOrder = DatabaseHelper.RELATIONSHIP_TABLE + "." + DatabaseHelper.COLUMN_RELATIONSHIP_PRIORITY + " ASC";
Cursor cursor = contentResolver.query(uri, projection, null, null, sortOrder);
// load the column names
int id = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_ID);
int title = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_TITLE);
int description = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_DESCRIPTION);
int url = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_URL);
int thumbnail = cursor.getColumnIndex(DatabaseHelper.COLUMN_ITEM_THUMBNAIL);
// load the items into an array
NewsItem[] items = new NewsItem[cursor.getCount()];
while(cursor.moveToNext() && cursor.getPosition() < limit){
NewsItem item = new NewsItem(); // initialize a new item
item.setId(cursor.getInt(id));
item.setTitle(cursor.getString(title));
item.setDescription(cursor.getString(description));
item.setUrl(cursor.getString(url));
item.setThumbnailBytes(cursor.getBlob(thumbnail));
items[cursor.getCount()] = item; // add this item to the array
}
cursor.close();
return items;
}
/**
* Queries the categories table for the enabled column of all rows, returning an array of booleans representing whether categories are enabled or
* not, sorted by category_Id.
*
* @return boolean[] containing enabled column from categories table.
*/
public boolean[] getCategoryBooleans() {
Uri uri = DatabaseProvider.CONTENT_URI_CATEGORIES;
String[] projection = new String[] { DatabaseHelper.COLUMN_CATEGORY_ENABLED };
Cursor cursor = contentResolver.query(uri, projection, null, null, DatabaseHelper.COLUMN_CATEGORY_ID);
boolean[] enabledCategories = new boolean[cursor.getCount()];
while (cursor.moveToNext()) {
if (cursor.getInt(cursor.getColumnIndex(DatabaseHelper.COLUMN_CATEGORY_ENABLED)) == 0) {
enabledCategories[cursor.getPosition() - 1] = false;
}
else {
enabledCategories[cursor.getPosition() - 1] = true;
}
}
cursor.close();
return enabledCategories;
}
/**
* Returns the links and names of all the categories that are enabled.
*
* @return A string[][] containing the String urls in [0] and String names in [1].
*/
public String[][] getEnabledCategories() {
Uri uri = DatabaseProvider.CONTENT_URI_ENABLED_CATEGORIES; // uri for enabled categories
String[] projection = new String[] { DatabaseHelper.COLUMN_CATEGORY_URL, DatabaseHelper.COLUMN_CATEGORY_NAME };
Cursor cursor = contentResolver.query(uri, projection, null, null, DatabaseHelper.COLUMN_CATEGORY_ID);
String[][] categories = new String[2][cursor.getCount()];
while (cursor.moveToNext()) {
categories[0][cursor.getPosition() - 1] = cursor.getString(0);
categories[1][cursor.getPosition() - 1] = cursor.getString(1);
}
cursor.close();
return categories;
}
/**
* Sets the given category to the given boolean
*
* @param category
* The String category you wish to change.
* @param enabled
* The boolean value you wish to set it to.
*/
public void setCategoryEnabled(String category, boolean enabled) {
// update this category
ContentValues values = new ContentValues(1);
if (enabled) {
values.put("enabled", 1);
}
else {
values.put("enabled", 0);
}
// update the database with these values
db.update(CATEGORY_TABLE, values, "name=?", new String[] { category });
}
/**
* Takes an array of booleans and sets the first n categories to those values. Where n is length of array
*
* @param enabled
* A boolean array of "enabled" values
*/
public void setEnabledCategories(boolean[] enabled) throws NullPointerException {
ContentValues values = new ContentValues(1);
for (int i = 0; i < enabled.length; i++) {
if (enabled[i]) {
values.put("enabled", 1);
}
else {
values.put("enabled", 0);
}
db.update(CATEGORY_TABLE, values, "category_Id=?", new String[] { Integer.toString(i + 1) });
values.clear();
}
}
/**
* When called will remove all articles that are over the threshold to the second old. Then cleans up the relationship table. Possibly resource
* intensive.
*/
public void clearOld() {
// delete items older than the threshold
Date now = new Date();
long cutoffTime = (now.getTime() - clearOutAgeMilliSecs);
/*// FIXME Optimise?
// Creates a java.util date object with current time
// Subtracts one month in milliseconds and deletes all
// items with a pubdate less than that value.
Date now = new Date();
long oldTime = (now.getTime() - clearOutAgeMilliSecs);
Cursor cursor = db.query(ITEM_TABLE, new String[] { "item_Id" }, "pubdate<?", new String[] { Long.toString(oldTime) }, null, null, null);
for (int i = 1; i <= cursor.getCount(); i++) {
cursor.moveToNext();
db.delete(ITEM_CATEGORY_TABLE, "itemId=?", new String[] { Integer.toString(cursor.getInt(0)) });
}
db.delete(ITEM_TABLE, "pubdate<?", new String[] { Long.toString(oldTime) });
cursor.close();*/
}
/**
* Adds all the start categories from the XML
*/
public void addCategoriesFromXml() {
try {
String[] categoryNames = context.getResources().getStringArray(R.array.category_names);
String[] categoryUrls = context.getResources().getStringArray(R.array.catergory_rss_urls);
int[] categoryBooleans = context.getResources().getIntArray(R.array.category_default_booleans);
for (int i = 0; i < categoryNames.length; i++) {
boolean enabled = true;
if (categoryBooleans[i] == 0) {
enabled = false;
}
insertCategory(categoryNames[i], enabled, categoryUrls[i]);
}
} catch (NullPointerException e) {
// Log.e("Database", "Categories XML is broken.");
}
}
/**
* Checks whether there are any records in category
*
* @return true or false
*/
public boolean isCreated() {
try {
getCategoryBooleans()[0] = true;
return true;
} catch (Exception e) {
return false;
}
}
/**
* Drops the entire database.
*/
public void dropTables() {
db.execSQL("DROP TABLE " + ITEM_TABLE);
db.execSQL("DROP TABLE " + CATEGORY_TABLE);
db.execSQL("DROP TABLE " + ITEM_CATEGORY_TABLE);
}
/**
* Attempts to create the tables.
*/
public void createTables() {
db.execSQL(CREATE_ITEM_TABLE);
db.execSQL(CREATE_CATEGORY_TABLE);
db.execSQL(CREATE_RELATIONSHIP_TABLE);
}
@Override
public void onCreate(SQLiteDatabase db) {
// nothing to do
}
@Override
public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// check what version to version upgrade we are performing
if (oldVersion == 1 && newVersion == 2) {
// drop tables
db.execSQL("DROP TABLE " + ITEM_TABLE);
db.execSQL("DROP TABLE " + ITEM_CATEGORY_TABLE);
// create tables
db.execSQL(CREATE_ITEM_TABLE);
db.execSQL(CREATE_RELATIONSHIP_TABLE);
}
else {
// reset everything to be sure
dropTables();
createTables();
}
}
public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
// reset the database
dropTables();
createTables();
}
public void finish() {
// close the database
db.close();
db = null;
}
void checkCompatibilty() {
// check if the insertWithOnConflict exists
try {
SQLiteDatabase.class.getMethod("insertWithOnConflict", new Class[] { String.class, String.class, ContentValues.class, Integer.TYPE });
// success, this method exists, set the boolean
methodInsertWithConflictExists = true;
} catch (NoSuchMethodException e) {
// failure, set the boolean
methodInsertWithConflictExists = false;
}
}
@Override
protected void finalize() throws Throwable {
// use try-catch to make sure we do not break super
try {
// make sure the database has been shutdown
if (db != null) {
db.close();
db = null;
}
} finally {
super.finalize();
}
}
public DatabaseHandler(Context context, int clearOutAgeDays) {
super(context, DATABASE_NAME, null, DATABASE_VERSION);
this.context = context;
this.contentResolver = context.getContentResolver();
this.clearOutAgeMilliSecs = (clearOutAgeDays * 24 * 60 * 60 * 1000);
this.db = this.getWritableDatabase();
// check compatibility with this version of Android
checkCompatibilty();
}
}
|
diff --git a/src/main/java/lcmc/gui/dialog/drbdConfig/CreateFS.java b/src/main/java/lcmc/gui/dialog/drbdConfig/CreateFS.java
index 37490c83..51a04b4b 100644
--- a/src/main/java/lcmc/gui/dialog/drbdConfig/CreateFS.java
+++ b/src/main/java/lcmc/gui/dialog/drbdConfig/CreateFS.java
@@ -1,422 +1,422 @@
/*
* This file is part of DRBD Management Console by LINBIT HA-Solutions GmbH
* written by Rasto Levrinc.
*
* Copyright (C) 2009, LINBIT HA-Solutions GmbH.
* Copyright (C) 2011-2012, Rastislav Levrinc.
*
* DRBD Management Console 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, or (at your option)
* any later version.
*
* DRBD Management Console 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 drbd; see the file COPYING. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
*/
package lcmc.gui.dialog.drbdConfig;
import lcmc.Exceptions;
import lcmc.utilities.Tools;
import lcmc.data.Host;
import lcmc.data.ConfigData;
import lcmc.data.AccessMode;
import lcmc.gui.SpringUtilities;
import lcmc.gui.resources.BlockDevInfo;
import lcmc.gui.resources.DrbdVolumeInfo;
import lcmc.gui.widget.Widget;
import lcmc.gui.widget.WidgetFactory;
import lcmc.gui.dialog.WizardDialog;
import lcmc.utilities.MyButton;
import lcmc.utilities.WidgetListener;
import javax.swing.JLabel;
import javax.swing.SpringLayout;
import javax.swing.JPanel;
import javax.swing.JComponent;
import java.awt.event.ActionListener;
import java.awt.event.ActionEvent;
import lcmc.data.StringValue;
import lcmc.data.Value;
import lcmc.utilities.Logger;
import lcmc.utilities.LoggerFactory;
/**
* An implementation of a dialog where drbd block devices are initialized.
* information.
*
* @author Rasto Levrinc
* @version $Id$
*
*/
final class CreateFS extends DrbdConfig {
/** Logger. */
private static final Logger LOG = LoggerFactory.getLogger(CreateFS.class);
/** Serial Version UID. */
private static final long serialVersionUID = 1L;
/** Pull down menu with hosts (or no host). */
private Widget hostW;
/** Pull down menu with file systems. */
private Widget filesystemW;
/** Whether to skip the initial full sync. */
private Widget skipSyncW;
/** Whether to skip the initial full sync label. */
private JLabel skipSyncLabel;
/** Make file system button. */
private final MyButton makeFsButton = new MyButton(
Tools.getString("Dialog.DrbdConfig.CreateFS.CreateFsButton"));
/** No host string. (none) */
private static final Value NO_HOST_STRING =
new StringValue(Tools.getString("Dialog.DrbdConfig.CreateFS.NoHostString"));
/** No file system (use existing data). */
private static final Value NO_FILESYSTEM_STRING =
new StringValue(Tools.getString("Dialog.DrbdConfig.CreateFS.SelectFilesystem"));
/** Width of the combo boxes. */
private static final int COMBOBOX_WIDTH = 250;
/** Skip sync false. */
private static final Value SKIP_SYNC_FALSE = new StringValue("false");
/** Skip sync true. */
private static final Value SKIP_SYNC_TRUE = new StringValue("true");
/** Prepares a new <code>CreateFS</code> object. */
CreateFS(final WizardDialog previousDialog,
final DrbdVolumeInfo drbdVolumeInfo) {
super(previousDialog, drbdVolumeInfo);
}
/**
* Finishes the dialog. If primary bd was choosen it is forced to be a
* primary.
*/
@Override
protected void finishDialog() {
final BlockDevInfo bdiPri = getPrimaryBD();
if (bdiPri != null) {
final boolean testOnly = false;
if (SKIP_SYNC_TRUE.equals(skipSyncW.getValue())) {
bdiPri.skipInitialFullSync(testOnly);
}
bdiPri.forcePrimary(testOnly);
}
}
/** Returns the primary block device. */
protected BlockDevInfo getPrimaryBD() {
final BlockDevInfo bdi1 = getDrbdVolumeInfo().getFirstBlockDevInfo();
final BlockDevInfo bdi2 = getDrbdVolumeInfo().getSecondBlockDevInfo();
final String h = hostW.getStringValue();
if (h.equals(bdi1.getHost().getName())) {
return bdi1;
} else if (h.equals(bdi2.getHost().getName())) {
return bdi2;
} else {
return null;
}
}
/** Returns the secondary block device. */
protected BlockDevInfo getSecondaryBD() {
final BlockDevInfo bdi1 = getDrbdVolumeInfo().getFirstBlockDevInfo();
final BlockDevInfo bdi2 = getDrbdVolumeInfo().getSecondBlockDevInfo();
final String h = hostW.getStringValue();
if (h.equals(bdi1.getHost().getName())) {
return bdi2;
} else if (h.equals(bdi2.getHost().getName())) {
return bdi1;
} else {
LOG.appError("getSecondaryBD: unknown host: " + h);
return null;
}
}
/** Creates the file system. */
protected void createFilesystem() {
final Runnable runnable = new Runnable() {
@Override
public void run() {
getProgressBar().start(1);
answerPaneSetText(
Tools.getString("Dialog.DrbdConfig.CreateFS.MakeFS"));
Tools.invokeLater(new Runnable() {
@Override
public void run() {
buttonClass(finishButton()).setEnabled(false);
makeFsButton.setEnabled(false);
}
});
BlockDevInfo bdiPri = getPrimaryBD();
BlockDevInfo bdiSec = getSecondaryBD();
final boolean testOnly = false;
if (SKIP_SYNC_TRUE.equals(skipSyncW.getValue())) {
bdiPri.skipInitialFullSync(testOnly);
}
bdiPri.forcePrimary(testOnly);
final String fs = filesystemW.getStringValue();
bdiPri.makeFilesystem(fs, testOnly);
if (bdiPri.getDrbdVolumeInfo() != null) {
/* could be canceled */
getDrbdVolumeInfo().setCreatedFs(fs);
bdiPri.setSecondary(testOnly);
hostW.setValue(NO_HOST_STRING);
filesystemW.setValue(NO_FILESYSTEM_STRING);
answerPaneSetText(
Tools.getString("Dialog.DrbdConfig.CreateFS.MakeFS.Done"));
}
progressBarDone();
}
};
final Thread thread = new Thread(runnable);
thread.start();
}
/** Returns the next dialog, null in this dialog. */
@Override
public WizardDialog nextDialog() {
return null;
}
/**
* Returns title of the dialog.
* It is defined in TextResources as "Dialog.DrbdConfig.CreateFS.Title"
*/
@Override
protected String getDialogTitle() {
return Tools.getString("Dialog.DrbdConfig.CreateFS.Title");
}
/**
* Returns description of the dialog.
* It is defined in TextResources as
* "Dialog.DrbdConfig.CreateFS.Description"
*/
@Override
protected String getDescription() {
return Tools.getString("Dialog.DrbdConfig.CreateFS.Description");
}
/** Inits dialog. */
@Override
protected void initDialogBeforeVisible() {
super.initDialogBeforeVisible();
makeFsButton.setBackgroundColor(
Tools.getDefaultColor("ConfigDialog.Button"));
enableComponentsLater(new JComponent[]{buttonClass(finishButton())});
}
/** Inits the dialog after it becomes visible. */
@Override
protected void initDialogAfterVisible() {
enableComponents();
if (Tools.getConfigData().getAutoOptionGlobal("autodrbd") != null) {
Tools.invokeLater(new Runnable() {
@Override
public void run() {
makeFsButton.pressButton();
}
});
}
}
/**
* Enables and disables the make fs and finish buttons depending on what
* was chosen by user.
*/
protected void checkButtons() {
final boolean noHost = hostW.getValue().equals(NO_HOST_STRING);
final boolean noFileSystem = filesystemW.getValue().equals(
NO_FILESYSTEM_STRING);
Tools.invokeLater(new Runnable() {
@Override
public void run() {
if (noHost) {
skipSyncW.setEnabled(false);
skipSyncLabel.setEnabled(false);
skipSyncW.setValue(SKIP_SYNC_FALSE);
} else {
if (skipSyncAvailable()) {
skipSyncW.setEnabled(true);
skipSyncLabel.setEnabled(true);
}
}
}
});
if (noFileSystem) {
Tools.invokeLater(new Runnable() {
@Override
public void run() {
buttonClass(finishButton()).setEnabled(true);
makeFsButton.setEnabled(false);
skipSyncW.setValue(SKIP_SYNC_FALSE);
}
});
} else if (noHost) {
Tools.invokeLater(new Runnable() {
@Override
public void run() {
buttonClass(finishButton()).setEnabled(false);
}
});
makeFsButton.setEnabled(false);
} else {
Tools.invokeLater(new Runnable() {
@Override
public void run() {
buttonClass(finishButton()).setEnabled(false);
makeFsButton.setEnabled(true);
if (skipSyncAvailable()) {
skipSyncW.setValue(SKIP_SYNC_TRUE);
skipSyncW.setEnabled(true);
}
}
});
}
}
/**
* Returns input pane, where file system can be created on the selected
* host.
*/
@Override
protected JComponent getInputPane() {
makeFsButton.setEnabled(false);
final JPanel pane = new JPanel(new SpringLayout());
final JPanel inputPane = new JPanel(new SpringLayout());
/* host */
final Value[] hosts = new Value[3];
hosts[0] = NO_HOST_STRING;
int i = 1;
for (final Host host : getDrbdVolumeInfo().getHosts()) {
hosts[i] = host;
i++;
}
final JLabel hostLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.ChooseHost"));
Value defaultHost = NO_HOST_STRING;
if (Tools.getConfigData().getAutoOptionGlobal("autodrbd") != null) {
defaultHost = hosts[1];
}
hostW = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultHost,
hosts,
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
hostW.addListeners(new WidgetListener() {
@Override
public void check(final Value value) {
checkButtons();
}
});
inputPane.add(hostLabel);
inputPane.add(hostW.getComponent());
inputPane.add(new JLabel(""));
/* Filesystem */
final JLabel filesystemLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.Filesystem"));
- Value defaultValue = NO_FILESYSTEM_STRING;
- if (Tools.getConfigData().getAutoOptionGlobal("autodrbd") != null) {
- defaultValue = new StringValue("ext3");
- }
+ final Value defaultValue = NO_FILESYSTEM_STRING;
final Value[] filesystems =
getDrbdVolumeInfo().getDrbdResourceInfo().getCommonFileSystems(
defaultValue);
filesystemW = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultValue,
filesystems,
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
+ if (Tools.getConfigData().getAutoOptionGlobal("autodrbd") != null) {
+ filesystemW.setValueAndWait(new StringValue("ext3"));
+ }
inputPane.add(filesystemLabel);
inputPane.add(filesystemW.getComponent());
filesystemW.addListeners(new WidgetListener() {
@Override
public void check(final Value value) {
if (NO_HOST_STRING.equals(
hostW.getValue())
&& !NO_FILESYSTEM_STRING.equals(
filesystemW.getValue())) {
hostW.setValue(hosts[1]);
} else {
checkButtons();
}
}
});
makeFsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
createFilesystem();
}
});
inputPane.add(makeFsButton);
/* skip initial full sync */
skipSyncLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.SkipSync"));
skipSyncLabel.setEnabled(false);
skipSyncW = WidgetFactory.createInstance(
Widget.Type.CHECKBOX,
SKIP_SYNC_FALSE,
new Value[]{SKIP_SYNC_TRUE,
SKIP_SYNC_FALSE},
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
skipSyncW.setEnabled(false);
skipSyncW.setBackgroundColor(
Tools.getDefaultColor("ConfigDialog.Background.Light"));
inputPane.add(skipSyncLabel);
inputPane.add(skipSyncW.getComponent());
inputPane.add(new JLabel(""));
SpringUtilities.makeCompactGrid(inputPane, 3, 3, // rows, cols
1, 1, // initX, initY
1, 1); // xPad, yPad
pane.add(inputPane);
pane.add(getProgressBarPane(null));
pane.add(getAnswerPane(""));
SpringUtilities.makeCompactGrid(pane, 3, 1, // rows, cols
0, 0, // initX, initY
0, 0); // xPad, yPad
return pane;
}
/** Returns whether skip sync is available. */
private boolean skipSyncAvailable() {
final BlockDevInfo bdi1 = getDrbdVolumeInfo().getFirstBlockDevInfo();
final BlockDevInfo bdi2 = getDrbdVolumeInfo().getSecondBlockDevInfo();
try {
return Tools.compareVersions(
bdi1.getHost().getDrbdVersion(), "8.3.2") >= 0
&& Tools.compareVersions(
bdi2.getHost().getDrbdVersion(), "8.3.2") >= 0;
} catch (Exceptions.IllegalVersionException e) {
LOG.appWarning("skipSyncAvailable: " + e.getMessage(), e);
return false;
}
}
}
| false | true | protected JComponent getInputPane() {
makeFsButton.setEnabled(false);
final JPanel pane = new JPanel(new SpringLayout());
final JPanel inputPane = new JPanel(new SpringLayout());
/* host */
final Value[] hosts = new Value[3];
hosts[0] = NO_HOST_STRING;
int i = 1;
for (final Host host : getDrbdVolumeInfo().getHosts()) {
hosts[i] = host;
i++;
}
final JLabel hostLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.ChooseHost"));
Value defaultHost = NO_HOST_STRING;
if (Tools.getConfigData().getAutoOptionGlobal("autodrbd") != null) {
defaultHost = hosts[1];
}
hostW = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultHost,
hosts,
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
hostW.addListeners(new WidgetListener() {
@Override
public void check(final Value value) {
checkButtons();
}
});
inputPane.add(hostLabel);
inputPane.add(hostW.getComponent());
inputPane.add(new JLabel(""));
/* Filesystem */
final JLabel filesystemLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.Filesystem"));
Value defaultValue = NO_FILESYSTEM_STRING;
if (Tools.getConfigData().getAutoOptionGlobal("autodrbd") != null) {
defaultValue = new StringValue("ext3");
}
final Value[] filesystems =
getDrbdVolumeInfo().getDrbdResourceInfo().getCommonFileSystems(
defaultValue);
filesystemW = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultValue,
filesystems,
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
inputPane.add(filesystemLabel);
inputPane.add(filesystemW.getComponent());
filesystemW.addListeners(new WidgetListener() {
@Override
public void check(final Value value) {
if (NO_HOST_STRING.equals(
hostW.getValue())
&& !NO_FILESYSTEM_STRING.equals(
filesystemW.getValue())) {
hostW.setValue(hosts[1]);
} else {
checkButtons();
}
}
});
makeFsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
createFilesystem();
}
});
inputPane.add(makeFsButton);
/* skip initial full sync */
skipSyncLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.SkipSync"));
skipSyncLabel.setEnabled(false);
skipSyncW = WidgetFactory.createInstance(
Widget.Type.CHECKBOX,
SKIP_SYNC_FALSE,
new Value[]{SKIP_SYNC_TRUE,
SKIP_SYNC_FALSE},
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
skipSyncW.setEnabled(false);
skipSyncW.setBackgroundColor(
Tools.getDefaultColor("ConfigDialog.Background.Light"));
inputPane.add(skipSyncLabel);
inputPane.add(skipSyncW.getComponent());
inputPane.add(new JLabel(""));
SpringUtilities.makeCompactGrid(inputPane, 3, 3, // rows, cols
1, 1, // initX, initY
1, 1); // xPad, yPad
pane.add(inputPane);
pane.add(getProgressBarPane(null));
pane.add(getAnswerPane(""));
SpringUtilities.makeCompactGrid(pane, 3, 1, // rows, cols
0, 0, // initX, initY
0, 0); // xPad, yPad
return pane;
}
| protected JComponent getInputPane() {
makeFsButton.setEnabled(false);
final JPanel pane = new JPanel(new SpringLayout());
final JPanel inputPane = new JPanel(new SpringLayout());
/* host */
final Value[] hosts = new Value[3];
hosts[0] = NO_HOST_STRING;
int i = 1;
for (final Host host : getDrbdVolumeInfo().getHosts()) {
hosts[i] = host;
i++;
}
final JLabel hostLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.ChooseHost"));
Value defaultHost = NO_HOST_STRING;
if (Tools.getConfigData().getAutoOptionGlobal("autodrbd") != null) {
defaultHost = hosts[1];
}
hostW = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultHost,
hosts,
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
hostW.addListeners(new WidgetListener() {
@Override
public void check(final Value value) {
checkButtons();
}
});
inputPane.add(hostLabel);
inputPane.add(hostW.getComponent());
inputPane.add(new JLabel(""));
/* Filesystem */
final JLabel filesystemLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.Filesystem"));
final Value defaultValue = NO_FILESYSTEM_STRING;
final Value[] filesystems =
getDrbdVolumeInfo().getDrbdResourceInfo().getCommonFileSystems(
defaultValue);
filesystemW = WidgetFactory.createInstance(
Widget.Type.COMBOBOX,
defaultValue,
filesystems,
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
if (Tools.getConfigData().getAutoOptionGlobal("autodrbd") != null) {
filesystemW.setValueAndWait(new StringValue("ext3"));
}
inputPane.add(filesystemLabel);
inputPane.add(filesystemW.getComponent());
filesystemW.addListeners(new WidgetListener() {
@Override
public void check(final Value value) {
if (NO_HOST_STRING.equals(
hostW.getValue())
&& !NO_FILESYSTEM_STRING.equals(
filesystemW.getValue())) {
hostW.setValue(hosts[1]);
} else {
checkButtons();
}
}
});
makeFsButton.addActionListener(new ActionListener() {
@Override
public void actionPerformed(final ActionEvent e) {
createFilesystem();
}
});
inputPane.add(makeFsButton);
/* skip initial full sync */
skipSyncLabel = new JLabel(
Tools.getString("Dialog.DrbdConfig.CreateFS.SkipSync"));
skipSyncLabel.setEnabled(false);
skipSyncW = WidgetFactory.createInstance(
Widget.Type.CHECKBOX,
SKIP_SYNC_FALSE,
new Value[]{SKIP_SYNC_TRUE,
SKIP_SYNC_FALSE},
Widget.NO_REGEXP,
COMBOBOX_WIDTH,
Widget.NO_ABBRV,
new AccessMode(ConfigData.AccessType.RO,
!AccessMode.ADVANCED),
Widget.NO_BUTTON);
skipSyncW.setEnabled(false);
skipSyncW.setBackgroundColor(
Tools.getDefaultColor("ConfigDialog.Background.Light"));
inputPane.add(skipSyncLabel);
inputPane.add(skipSyncW.getComponent());
inputPane.add(new JLabel(""));
SpringUtilities.makeCompactGrid(inputPane, 3, 3, // rows, cols
1, 1, // initX, initY
1, 1); // xPad, yPad
pane.add(inputPane);
pane.add(getProgressBarPane(null));
pane.add(getAnswerPane(""));
SpringUtilities.makeCompactGrid(pane, 3, 1, // rows, cols
0, 0, // initX, initY
0, 0); // xPad, yPad
return pane;
}
|
diff --git a/app/src/main/java/org/xbmc/android/app/ui/fragment/AlbumCompactFragment.java b/app/src/main/java/org/xbmc/android/app/ui/fragment/AlbumCompactFragment.java
index e511811..3449b7f 100644
--- a/app/src/main/java/org/xbmc/android/app/ui/fragment/AlbumCompactFragment.java
+++ b/app/src/main/java/org/xbmc/android/app/ui/fragment/AlbumCompactFragment.java
@@ -1,214 +1,214 @@
/*
* Copyright (C) 2005-2015 Team XBMC
* http://xbmc.org
*
* This Program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation; either version 2, 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 XBMC Remote; see the file license. If not, write to
* the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
* http://www.gnu.org/copyleft/gpl.html
*
*/
package org.xbmc.android.app.ui.fragment;
import android.content.Context;
import android.database.Cursor;
import android.net.Uri;
import android.os.Bundle;
import android.provider.BaseColumns;
import android.provider.ContactsContract;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.widget.CursorAdapter;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import com.bumptech.glide.Glide;
import de.greenrobot.event.EventBus;
import org.xbmc.android.app.event.HostSwitched;
import org.xbmc.android.app.manager.HostManager;
import org.xbmc.android.app.provider.AudioContract;
import org.xbmc.android.app.provider.AudioDatabase;
import org.xbmc.android.remotesandbox.R;
import org.xbmc.android.app.event.DataItemSynced;
import org.xbmc.android.app.injection.Injector;
import javax.inject.Inject;
import java.io.UnsupportedEncodingException;
import java.net.URLEncoder;
/**
* Lists albums in grid using the compact view.
*
* @author freezy <[email protected]>
*/
public class AlbumCompactFragment extends GridFragment implements LoaderManager.LoaderCallbacks<Cursor> {
private final static String TAG = AlbumCompactFragment.class.getSimpleName();
@Inject protected EventBus bus;
@Inject protected HostManager hostManager;
private CursorAdapter adapter;
private String hostUri;
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_home_grid, container);
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Injector.inject(this);
bus.register(this);
hostUri = hostManager.getActiveUri();
}
@Override
public void onDestroy() {
bus.unregister(this);
super.onDestroy();
}
@Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
adapter = new AlbumsAdapter(getActivity());
setGridAdapter(adapter);
// prepare the loader. Either re-connect with an existing one, or start a new one.
getLoaderManager().initLoader(0, null, this);
}
/**
* Event bus callback. Called when either video or audio sync completed.
*
* Refreshes data of the fragment.
*
* @param event Event data
*/
public void onEvent(DataItemSynced event) {
if (event.audioSynced()) {
getLoaderManager().restartLoader(0, null, this);
}
}
/**
* Event bus callback. Called when XBMC host was switched by the user (or
* by adding a new host).
*
* Refreshes data of the fragment.
*
* @param event Event data
*/
public void onEvent(HostSwitched event) {
hostUri = event.getHost().getUri();
getLoaderManager().restartLoader(0, null, this);
}
@Override
public Loader<Cursor> onCreateLoader(int i, Bundle bundle) {
// This is called when a new Loader needs to be created. This
// sample only has one Loader, so we don't care about the ID.
// First, pick the base URI to use depending on whether we are
// currently filtering.
Uri baseUri;
baseUri = ContactsContract.Contacts.CONTENT_URI;
return new CursorLoader(getActivity(), AudioContract.Albums.CONTENT_URI, AlbumsQuery.PROJECTION, null, null,
AudioContract.Albums.sortLatest(getResources().getInteger(R.integer.home_numrows)));
}
@Override
public void onLoadFinished(Loader<Cursor> cursorLoader, Cursor cursor) {
// Swap the new cursor in. (The framework will take care of closing the
// old cursor once we return.)
adapter.swapCursor(cursor);
}
@Override
public void onLoaderReset(Loader<Cursor> cursorLoader) {
// This is called when the last Cursor provided to onLoadFinished()
// above is about to be closed. We need to make sure we are no
// longer using it.
adapter.swapCursor(null);
}
/**
* {@link android.support.v4.widget.CursorAdapter} that renders a {@link AlbumsQuery}.
*/
private class AlbumsAdapter extends CursorAdapter {
public AlbumsAdapter(Context context) {
super(context, null, false);
}
/** {@inheritDoc} */
@Override
public View newView(Context context, Cursor cursor, ViewGroup parent) {
return getActivity().getLayoutInflater().inflate(R.layout.list_item_album_compact, parent, false);
}
/** {@inheritDoc} */
@Override
public void bindView(View view, Context context, Cursor cursor) {
- final TextView titleView = (TextView) view.findViewById(R.id.title_album);
- final TextView subtitleView = (TextView) view.findViewById(R.id.title_artist);
+ final TextView titleView = (TextView) view.findViewById(R.id.album);
+ final TextView subtitleView = (TextView) view.findViewById(R.id.artist);
final ImageView imageView = (ImageView) view.findViewById(R.id.list_album_cover);
try {
final String url = hostUri + "/image/" + URLEncoder.encode(cursor.getString(AlbumsQuery.THUMBNAIL), "UTF-8");
Glide.load(url)
.centerCrop()
.animate(android.R.anim.fade_in)
.into(imageView);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Cannot encode " + cursor.getString(AlbumsQuery.THUMBNAIL) + " from UTF-8.");
}
titleView.setText(cursor.getString(AlbumsQuery.TITLE));
subtitleView.setText(cursor.getString(AlbumsQuery.ARTIST));
}
}
/**
* {@link org.xbmc.android.app.provider.AudioContract.Albums}
* query parameters.
*/
private interface AlbumsQuery {
// int _TOKEN = 0x1;
String[] PROJECTION = {
AudioDatabase.Tables.ALBUMS + "." + BaseColumns._ID,
AudioContract.Albums.ID,
AudioContract.Albums.TITLE,
AudioContract.Albums.YEAR,
AudioContract.Artists.NAME,
AudioContract.Albums.THUMBNAIL
};
// int _ID = 0;
// int ID = 1;
int TITLE = 2;
int YEAR = 3;
int ARTIST = 4;
int THUMBNAIL = 5;
}
}
| true | true | public void bindView(View view, Context context, Cursor cursor) {
final TextView titleView = (TextView) view.findViewById(R.id.title_album);
final TextView subtitleView = (TextView) view.findViewById(R.id.title_artist);
final ImageView imageView = (ImageView) view.findViewById(R.id.list_album_cover);
try {
final String url = hostUri + "/image/" + URLEncoder.encode(cursor.getString(AlbumsQuery.THUMBNAIL), "UTF-8");
Glide.load(url)
.centerCrop()
.animate(android.R.anim.fade_in)
.into(imageView);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Cannot encode " + cursor.getString(AlbumsQuery.THUMBNAIL) + " from UTF-8.");
}
titleView.setText(cursor.getString(AlbumsQuery.TITLE));
subtitleView.setText(cursor.getString(AlbumsQuery.ARTIST));
}
| public void bindView(View view, Context context, Cursor cursor) {
final TextView titleView = (TextView) view.findViewById(R.id.album);
final TextView subtitleView = (TextView) view.findViewById(R.id.artist);
final ImageView imageView = (ImageView) view.findViewById(R.id.list_album_cover);
try {
final String url = hostUri + "/image/" + URLEncoder.encode(cursor.getString(AlbumsQuery.THUMBNAIL), "UTF-8");
Glide.load(url)
.centerCrop()
.animate(android.R.anim.fade_in)
.into(imageView);
} catch (UnsupportedEncodingException e) {
Log.e(TAG, "Cannot encode " + cursor.getString(AlbumsQuery.THUMBNAIL) + " from UTF-8.");
}
titleView.setText(cursor.getString(AlbumsQuery.TITLE));
subtitleView.setText(cursor.getString(AlbumsQuery.ARTIST));
}
|
diff --git a/src/com/fourisland/frigidearth/MapViewGameState.java b/src/com/fourisland/frigidearth/MapViewGameState.java
index 5e16219..65bfbe7 100644
--- a/src/com/fourisland/frigidearth/MapViewGameState.java
+++ b/src/com/fourisland/frigidearth/MapViewGameState.java
@@ -1,926 +1,926 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.fourisland.frigidearth;
import com.fourisland.frigidearth.mobs.Mouse;
import com.fourisland.frigidearth.mobs.Rat;
import java.awt.Color;
import java.awt.Graphics2D;
import java.awt.Point;
import java.awt.event.KeyEvent;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;
/**
*
* @author hatkirby
*/
public class MapViewGameState implements GameState
{
private final int TILE_WIDTH = 12;
private final int TILE_HEIGHT = 12;
private final int MAP_WIDTH = 100;
private final int MAP_HEIGHT = 100;
private final int MESSAGE_HEIGHT = 6;
private final int VIEWPORT_WIDTH = Main.CANVAS_WIDTH / TILE_WIDTH;
private final int VIEWPORT_HEIGHT = Main.CANVAS_HEIGHT / TILE_HEIGHT - MESSAGE_HEIGHT;
private final int MAX_ROOM_WIDTH = 13;
private final int MIN_ROOM_WIDTH = 7;
private final int MAX_ROOM_HEIGHT = 13;
private final int MIN_ROOM_HEIGHT = 7;
private final int MAX_CORRIDOR_LENGTH = 6;
private final int MIN_CORRIDOR_LENGTH = 2;
private final int[][] OCTET_MULTIPLIERS = new int[][] {new int[] {1,0,0,-1,-1,0,0,1}, new int[] {0,1,-1,0,0,-1,1,0}, new int[] {0,1,1,0,0,-1,-1,0}, new int[] {1,0,0,1,-1,0,0,-1}};
private Tile[][] grid;
private boolean[][] gridLighting;
private String[] messages = new String[MESSAGE_HEIGHT];
private List<Room> rooms = new ArrayList<Room>();
private List<Mob> mobs = new ArrayList<Mob>();
private int playerx = 4;
private int playery = 4;
private int viewportx = 0;
private int viewporty = 0;
private int health = 15;
private int maxHealth = 15;
private int defense = 0;
public MapViewGameState()
{
grid = new Tile[MAP_WIDTH][MAP_HEIGHT];
gridLighting = new boolean[MAP_WIDTH][MAP_HEIGHT];
for (int x=0; x<MAP_WIDTH; x++)
{
for (int y=0; y<MAP_HEIGHT; y++)
{
if ((x == 0) || (x == MAP_WIDTH-1) || (y == 0) || (y == MAP_HEIGHT-1))
{
grid[x][y] = Tile.StoneWall;
} else {
grid[x][y] = Tile.Unused;
}
}
}
makeRoom(MAP_WIDTH/2, MAP_HEIGHT/2, Direction.getRandomDirection());
int currentFeatures = 1;
int objects = 300;
for (int countingTries = 0; countingTries < 1000; countingTries++)
{
if (currentFeatures == objects)
{
break;
}
int newx = 0;
int xmod = 0;
int newy = 0;
int ymod = 0;
Direction validTile = null;
for (int testing = 0; testing < 1000; testing++)
{
newx = Functions.random(1, MAP_WIDTH-1);
newy = Functions.random(1, MAP_HEIGHT-1);
validTile = null;
if ((grid[newx][newy] == Tile.DirtWall) || (grid[newx][newy] == Tile.Corridor))
{
if ((grid[newx][newy+1] == Tile.DirtFloor) || (grid[newx][newy+1] == Tile.Corridor))
{
validTile = Direction.North;
xmod = 0;
ymod = -1;
} else if ((grid[newx-1][newy] == Tile.DirtFloor) || (grid[newx-1][newy] == Tile.Corridor))
{
validTile = Direction.East;
xmod = 1;
ymod = 0;
} else if ((grid[newx][newy-1] == Tile.DirtFloor) || (grid[newx][newy-1] == Tile.Corridor))
{
validTile = Direction.South;
xmod = 0;
ymod = 1;
} else if ((grid[newx+1][newy] == Tile.DirtFloor) || (grid[newx+1][newy] == Tile.Corridor))
{
validTile = Direction.West;
xmod = -1;
ymod = 0;
}
if (validTile != null)
{
if (grid[newx][newy+1] == Tile.Door)
{
validTile = null;
} else if (grid[newx-1][newy] == Tile.Door)
{
validTile = null;
} else if (grid[newx][newy-1] == Tile.Door)
{
validTile = null;
} else if (grid[newx+1][newy] == Tile.Door)
{
validTile = null;
}
}
if (validTile != null)
{
break;
}
}
}
if (validTile != null)
{
if (Functions.random(0, 100) <= 75)
{
if (makeRoom(newx+xmod, newy+ymod, validTile))
{
currentFeatures++;
grid[newx][newy] = Tile.Door;
grid[newx+xmod][newy+ymod] = Tile.DirtFloor;
}
} else {
if (makeCorridor(newx+xmod, newy+ymod, validTile))
{
currentFeatures++;
grid[newx][newy] = Tile.Door;
}
}
}
}
int newx = 0;
int newy = 0;
int ways = 0;
int state = 0;
while (state != 10)
{
for (int testing = 0; testing < 1000; testing++)
{
newx = Functions.random(1, MAP_WIDTH-1);
newy = Functions.random(1, MAP_HEIGHT-2);
ways = 4;
for (Direction dir : Direction.values())
{
Point to = dir.to(new Point(newx, newy));
- if ((isValidPosition(newx, newy)) && (grid[to.x][to.y] == Tile.DirtFloor) || (grid[to.x][to.y] == Tile.Corridor))
+ if ((isValidPosition(to.x, to.y)) && (grid[to.x][to.y] == Tile.DirtFloor) || (grid[to.x][to.y] == Tile.Corridor))
{
ways--;
}
}
if (state == 0)
{
if (ways == 0)
{
grid[newx][newy] = Tile.UpStairs;
state = 1;
break;
}
} else if (state == 1)
{
if (ways == 0)
{
grid[newx][newy] = Tile.DownStairs;
playerx=newx+1;
playery=newy;
state = 10;
break;
}
}
}
}
adjustViewport();
calculateFieldOfView();
}
private boolean makeRoom(int x, int y, Direction direction)
{
int width = Functions.random(MIN_ROOM_WIDTH, MAX_ROOM_WIDTH);
int height = Functions.random(MIN_ROOM_HEIGHT, MAX_ROOM_HEIGHT);
Tile floor = Tile.DirtFloor;
Tile wall = Tile.DirtWall;
Room room = null;
switch (direction)
{
case North:
room = new Room(x-width/2, y-height, width+1, height+1, true);
break;
case East:
room = new Room(x, y-height/2, width+1, height+1, true);
break;
case South:
room = new Room(x-width/2, y, width+1, height+1, true);
break;
case West:
room = new Room(x-width, y-height/2, width+1, height+1, true);
break;
}
for (int ytemp=room.getY(); ytemp < room.getY()+room.getHeight(); ytemp++)
{
if ((ytemp < 0) || (ytemp > MAP_HEIGHT))
{
return false;
}
for (int xtemp=room.getX(); xtemp < room.getX()+room.getWidth(); xtemp++)
{
if ((xtemp < 0) || (xtemp > MAP_WIDTH))
{
return false;
}
if (grid[xtemp][ytemp] != Tile.Unused)
{
return false;
}
}
}
for (int ytemp=room.getY(); ytemp < room.getY()+room.getHeight(); ytemp++)
{
for (int xtemp=room.getX(); xtemp < room.getX()+room.getWidth(); xtemp++)
{
if (xtemp == room.getX())
{
grid[xtemp][ytemp] = wall;
} else if (xtemp == room.getX()+room.getWidth()-1)
{
grid[xtemp][ytemp] = wall;
} else if (ytemp == room.getY())
{
grid[xtemp][ytemp] = wall;
} else if (ytemp == room.getY()+room.getHeight()-1)
{
grid[xtemp][ytemp] = wall;
} else {
grid[xtemp][ytemp] = floor;
}
}
}
rooms.add(room);
// Place mice in random rooms because yolo
int random = Functions.random(0,100);
if (random < 25)
{
Mob mob = new Mouse(Functions.random(room.getX()+1, room.getX()+room.getWidth()-2), Functions.random(room.getY()+1, room.getY()+room.getHeight()-2));
mobs.add(mob);
} else if (random < 50)
{
Mob mob = new Rat(Functions.random(room.getX()+1, room.getX()+room.getWidth()-2), Functions.random(room.getY()+1, room.getY()+room.getHeight()-2));
mobs.add(mob);
}
return true;
}
private boolean makeCorridor(int x, int y, Direction direction)
{
int length = Functions.random(MIN_CORRIDOR_LENGTH, MAX_CORRIDOR_LENGTH);
Tile floor = Tile.Corridor;
int xtemp = 0;
int ytemp = 0;
switch (direction)
{
case North:
if ((x < 0) || (x > MAP_WIDTH))
{
return false;
} else {
xtemp = x;
}
for (ytemp = y; ytemp > (y-length); ytemp--)
{
if ((ytemp < 0) || (ytemp > MAP_HEIGHT))
{
return false;
}
if (grid[xtemp][ytemp] != Tile.Unused)
{
return false;
}
}
for (ytemp = y; ytemp > (y-length); ytemp--)
{
grid[xtemp][ytemp] = floor;
}
break;
case East:
if ((y < 0) || (y > MAP_HEIGHT))
{
return false;
} else {
ytemp = y;
}
for (xtemp = x; xtemp < (x+length); xtemp++)
{
if ((xtemp < 0) || (xtemp > MAP_WIDTH))
{
return false;
}
if (grid[xtemp][ytemp] != Tile.Unused)
{
return false;
}
}
for (xtemp = x; xtemp < (x+length); xtemp++)
{
grid[xtemp][ytemp] = floor;
}
break;
case South:
if ((x < 0) || (x > MAP_WIDTH))
{
return false;
} else {
xtemp = x;
}
for (ytemp = y; ytemp < (y+length); ytemp++)
{
if ((ytemp < 0) || (ytemp > MAP_HEIGHT))
{
return false;
}
if (grid[xtemp][ytemp] != Tile.Unused)
{
return false;
}
}
for (ytemp = y; ytemp < (y+length); ytemp++)
{
grid[xtemp][ytemp] = floor;
}
break;
case West:
if ((y < 0) || (y > MAP_HEIGHT))
{
return false;
} else {
ytemp = y;
}
for (xtemp = x; xtemp > (x-length); xtemp--)
{
if ((xtemp < 0) || (xtemp > MAP_WIDTH))
{
return false;
}
if (grid[xtemp][ytemp] != Tile.Unused)
{
return false;
}
}
for (xtemp = x; xtemp > (x-length); xtemp--)
{
grid[xtemp][ytemp] = floor;
}
break;
}
return true;
}
private void calculateFieldOfView()
{
for (int x=0; x<MAP_WIDTH; x++)
{
for (int y=0; y<MAP_HEIGHT; y++)
{
gridLighting[x][y] = false;
}
}
for (int i=0; i<8; i++)
{
castLight(playerx, playery, 1, 1.0, 0.0, Math.max(VIEWPORT_WIDTH/2, VIEWPORT_HEIGHT/2), OCTET_MULTIPLIERS[0][i], OCTET_MULTIPLIERS[1][i], OCTET_MULTIPLIERS[2][i], OCTET_MULTIPLIERS[3][i], 0);
}
}
private void castLight(int cx, int cy, int row, double start, double end, int radius, int xx, int xy, int yx, int yy, int id)
{
if (start < end)
{
return;
}
int r2 = radius * radius;
for (int j=row; j<radius+1; j++)
{
int dx = -j-1;
int dy = -j;
boolean blocked = false;
double newStart = 0.0;
while (dx <= 0)
{
dx++;
int x = cx + dx*xx + dy*xy;
int y = cy + dx*yx + dy*yy;
double l_slope = ((double)dx-0.5)/((double)dy+0.5);
double r_slope = ((double)dx+0.5)/((double)dy-0.5);
if (start < r_slope)
{
continue;
} else if (end > l_slope)
{
break;
} else {
if ((dx*dx + dy*dy) < r2)
{
gridLighting[x][y] = true;
}
if (blocked)
{
if (grid[x][y].isBlocked())
{
newStart = r_slope;
continue;
} else {
blocked = false;
start = newStart;
}
} else {
if ((grid[x][y].isBlocked()) && (j < radius))
{
blocked = true;
castLight(cx, cy, j+1, start, l_slope, radius, xx, xy, yx, yy, id+1);
newStart = r_slope;
}
}
}
}
if (blocked)
{
break;
}
}
}
public void render(Graphics2D g)
{
// Render tiles
for (int x=viewportx; x<viewportx+VIEWPORT_WIDTH; x++)
{
for (int y=viewporty; y<viewporty+VIEWPORT_HEIGHT; y++)
{
if (gridLighting[x][y])
{
char displayChar = grid[x][y].getDisplayCharacter();
Color displayColor = grid[x][y].getBackgroundColor();
if (!displayColor.equals(Color.BLACK))
{
g.setColor(displayColor);
g.fillRect((x-viewportx)*TILE_WIDTH, (y-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT);
}
if (displayChar != ' ')
{
g.drawImage(SystemFont.getCharacter(grid[x][y].getDisplayCharacter(), Color.WHITE), (x-viewportx)*TILE_WIDTH, (y-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null);
}
}
}
}
// Render mobs
for (Mob mob : mobs)
{
if ((gridLighting[mob.x][mob.y]) && (isInViewport(mob.x, mob.y)))
{
g.drawImage(SystemFont.getCharacter(mob.getDisplayCharacter(), mob.getDisplayColor()), (mob.x-viewportx)*TILE_WIDTH, (mob.y-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null);
}
}
// Render player
g.drawImage(SystemFont.getCharacter('@', Color.WHITE), (playerx-viewportx)*TILE_WIDTH, (playery-viewporty)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null);
// Render messages
g.setColor(new Color(53, 63, 62));
g.fillRect(0, VIEWPORT_HEIGHT*TILE_HEIGHT, Main.CANVAS_WIDTH, TILE_HEIGHT*MESSAGE_HEIGHT);
for (int i=0; i<MESSAGE_HEIGHT; i++)
{
if (messages[i] != null)
{
for (int j=0; j<messages[i].length(); j++)
{
g.drawImage(SystemFont.getCharacter(messages[i].charAt(j), Color.WHITE), j*TILE_WIDTH, (VIEWPORT_HEIGHT+i)*TILE_HEIGHT, TILE_WIDTH, TILE_HEIGHT, null);
}
}
}
// Render status bar
g.drawImage(SystemFont.getCharacter((char) 3, Color.RED), TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null);
String healthText = Integer.toString(health);
double healthPercentage = ((double) health) / ((double) maxHealth);
Color healthColor = Color.WHITE;
if (healthPercentage < 0.2)
{
healthColor = Color.RED;
} else if (healthPercentage < 0.55)
{
healthColor = Color.YELLOW;
} else if (healthPercentage < 1)
{
healthColor = Color.GREEN;
}
for (int i=0; i<healthText.length(); i++)
{
g.drawImage(SystemFont.getCharacter(healthText.charAt(i), healthColor), (i+2)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null);
}
g.drawImage(SystemFont.getCharacter((char) 5, Color.GRAY), (healthText.length()+3)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null);
int b = healthText.length()+4;
String defenseText = Integer.toBinaryString(defense);
for (int i=0; i<defenseText.length(); i++)
{
g.drawImage(SystemFont.getCharacter(defenseText.charAt(i), Color.WHITE), (i+b)*TILE_WIDTH, 0, TILE_WIDTH, TILE_HEIGHT, null);
}
}
public void processInput(KeyEvent e)
{
switch (e.getKeyCode())
{
case KeyEvent.VK_LEFT:
case KeyEvent.VK_RIGHT:
case KeyEvent.VK_UP:
case KeyEvent.VK_DOWN:
Direction dir = Direction.fromKeyEvent(e);
Point to = dir.to(new Point(playerx, playery));
if ((isValidPosition(to.x,to.y)) && (!grid[to.x][to.y].isBlocked()))
{
// Check for mobs
boolean foundMob = false;
for (Mob mob : mobs)
{
if (mob.getPosition().equals(to))
{
printMessage("You hit the " + mob.getName().toLowerCase());
mob.health--;
if (mob.health <= 0)
{
printMessage("You killed the " + mob.getName().toLowerCase() + "!");
mobs.remove(mob);
}
foundMob = true;
break;
}
}
if (!foundMob)
{
playerx = to.x;
playery = to.y;
}
} else {
printMessage("Blocked: " + dir.name());
return;
}
break;
default:
return;
}
// Move mobs
for (Mob mob : mobs)
{
// If the mob is hostile, it should move toward the player IF IT CAN SEE the player
// Also, if it is adjacent to the player, it should attack
if ((mob.hostile) && (canSeePlayer(mob.x, mob.y)))
{
if (arePointsAdjacent(playerx, playery, mob.x, mob.y))
{
// Attack!
health -= (mob.power - defense);
printMessage(mob.getBattleMessage());
} else {
List<Direction> path = findPath(mob.getPosition(), new Point(playerx, playery));
if (path != null)
{
mob.moveInDirection(path.get(0));
}
}
} else {
// If the mob isn't hostile, it should just move around randomly
Direction toDir = null;
for (int i=0; i<10; i++)
{
toDir = Direction.getRandomDirection();
Point to = toDir.to(mob.getPosition());
if ((isValidPosition(to.x,to.y)) && (!grid[to.x][to.y].isBlocked()) && (!to.equals(new Point(playerx, playery))))
{
mob.moveInDirection(toDir);
break;
}
}
}
}
adjustViewport();
calculateFieldOfView();
}
private void adjustViewport()
{
if (playerx > (VIEWPORT_WIDTH/2))
{
if (playerx < (MAP_WIDTH - (VIEWPORT_WIDTH/2-1)))
{
viewportx = playerx - (VIEWPORT_WIDTH/2);
} else {
viewportx = MAP_WIDTH - VIEWPORT_WIDTH;
}
} else {
viewportx = 0;
}
if (playery > (VIEWPORT_HEIGHT/2))
{
if (playery < (MAP_HEIGHT - (VIEWPORT_HEIGHT/2-1)))
{
viewporty = playery - (VIEWPORT_HEIGHT/2);
} else {
viewporty = MAP_HEIGHT - VIEWPORT_HEIGHT;
}
} else {
viewporty = 0;
}
}
private boolean isValidPosition(int x, int y)
{
if (x < 0) return false;
if (x > MAP_WIDTH) return false;
if (y < 0) return false;
if (y > MAP_HEIGHT) return false;
return true;
}
private boolean isInViewport(int x, int y)
{
if (x < viewportx) return false;
if (x > viewportx+VIEWPORT_WIDTH) return false;
if (y < viewporty) return false;
if (y > viewporty+VIEWPORT_HEIGHT) return false;
return true;
}
private void printMessage(String message)
{
String temp = message;
while (temp.length() > VIEWPORT_WIDTH)
{
String shortm = temp.substring(0, VIEWPORT_WIDTH);
if ((temp.charAt(VIEWPORT_WIDTH) == ' ') || (shortm.endsWith(" ")))
{
pushUpMessages(shortm);
temp = temp.substring(VIEWPORT_WIDTH);
} else {
int lastSpace = shortm.lastIndexOf(" ");
pushUpMessages(shortm.substring(0, lastSpace));
temp = temp.substring(lastSpace);
}
}
pushUpMessages(temp);
}
private void pushUpMessages(String message)
{
for (int i=1; i<MESSAGE_HEIGHT; i++)
{
messages[i-1] = messages[i];
}
messages[MESSAGE_HEIGHT-1] = message;
}
private boolean canSeePlayer(int mx, int my)
{
int dx = playerx - mx;
int dy = playery - my;
int ax = Math.abs(dx) << 1;
int ay = Math.abs(dy) << 1;
int sx = (int) Math.signum(dx);
int sy = (int) Math.signum(dy);
int x = mx;
int y = my;
if (ax > ay)
{
int t = ay - (ax >> 1);
do
{
if (t >= 0)
{
y += sy;
t -= ax;
}
x += sx;
t += ay;
if ((x == playerx) && (y == playery))
{
return true;
}
} while (!grid[x][y].isBlocked());
return false;
} else {
int t = ax - (ay >> 1);
do
{
if (t >= 0)
{
x += sx;
t -= ay;
}
y += sy;
t += ax;
if ((x == playerx) && (y == playery))
{
return true;
}
} while (!grid[x][y].isBlocked());
return false;
}
}
private boolean arePointsAdjacent(int px, int py, int mx, int my)
{
if (mx == (px-1))
{
if (my == (py-1)) return true;
if (my == py) return true;
if (my == (py+1)) return true;
} else if (mx == px)
{
if (my == (py-1)) return true;
if (my == (py+1)) return true;
} else if (mx == (px+1))
{
if (my == (py-1)) return true;
if (my == py) return true;
if (my == (py+1)) return true;
}
return false;
}
private List<Direction> findPath(Point from, Point to)
{
return findPath(from, to, new ArrayList<Point>());
}
private List<Direction> findPath(Point from, Point to, List<Point> attempts)
{
/* Iterate over all of the directions and check if moving in that
* direction would result in the destination position. If so, the
* correct path has been acquired and thus we can return. */
for (Direction d : Direction.values())
{
Point loc = d.to(from);
if (to.equals(loc))
{
List<Direction> moves = new ArrayList<Direction>();
moves.add(d);
return moves;
}
}
/* Calculate the directions to attempt and the order in which to do so
* based on proximity to the destination */
List<Direction> ds = new ArrayList<Direction>();
for (Direction d : Direction.values())
{
Point loc = d.to(from);
if ((isValidPosition(loc.x, loc.y)) && (!grid[loc.x][loc.y].isBlocked()))
{
ds.add(d);
}
}
List<Direction> tempd = new ArrayList<Direction>();
if (to.x < from.x)
{
tempd.add(Direction.West);
} else if (to.x > from.x)
{
tempd.add(Direction.East);
} else {
if (!ds.contains(Direction.North) || !ds.contains(Direction.South))
{
tempd.add(Direction.West);
tempd.add(Direction.East);
}
}
if (to.y < from.y)
{
tempd.add(Direction.North);
} else if (to.y > from.y)
{
tempd.add(Direction.South);
} else {
if (!ds.contains(Direction.West) || !ds.contains(Direction.East))
{
tempd.add(Direction.North);
tempd.add(Direction.South);
}
}
// Remove calculated directions that aren't legal movements
tempd.retainAll(ds);
// Randomize directions so movement is more fluid
Collections.shuffle(tempd);
// Iterate over the suggested directions
for (Direction d : tempd)
{
/* If the position in the suggested direction has not already been
* covered, recursively search from the new position */
Point loc = d.to(from);
if (!attempts.contains(loc))
{
attempts.add(loc);
List<Direction> moves = findPath(loc, to, attempts);
if (moves != null)
{
moves.add(0, d);
return moves;
}
}
}
return null;
}
}
| true | true | public MapViewGameState()
{
grid = new Tile[MAP_WIDTH][MAP_HEIGHT];
gridLighting = new boolean[MAP_WIDTH][MAP_HEIGHT];
for (int x=0; x<MAP_WIDTH; x++)
{
for (int y=0; y<MAP_HEIGHT; y++)
{
if ((x == 0) || (x == MAP_WIDTH-1) || (y == 0) || (y == MAP_HEIGHT-1))
{
grid[x][y] = Tile.StoneWall;
} else {
grid[x][y] = Tile.Unused;
}
}
}
makeRoom(MAP_WIDTH/2, MAP_HEIGHT/2, Direction.getRandomDirection());
int currentFeatures = 1;
int objects = 300;
for (int countingTries = 0; countingTries < 1000; countingTries++)
{
if (currentFeatures == objects)
{
break;
}
int newx = 0;
int xmod = 0;
int newy = 0;
int ymod = 0;
Direction validTile = null;
for (int testing = 0; testing < 1000; testing++)
{
newx = Functions.random(1, MAP_WIDTH-1);
newy = Functions.random(1, MAP_HEIGHT-1);
validTile = null;
if ((grid[newx][newy] == Tile.DirtWall) || (grid[newx][newy] == Tile.Corridor))
{
if ((grid[newx][newy+1] == Tile.DirtFloor) || (grid[newx][newy+1] == Tile.Corridor))
{
validTile = Direction.North;
xmod = 0;
ymod = -1;
} else if ((grid[newx-1][newy] == Tile.DirtFloor) || (grid[newx-1][newy] == Tile.Corridor))
{
validTile = Direction.East;
xmod = 1;
ymod = 0;
} else if ((grid[newx][newy-1] == Tile.DirtFloor) || (grid[newx][newy-1] == Tile.Corridor))
{
validTile = Direction.South;
xmod = 0;
ymod = 1;
} else if ((grid[newx+1][newy] == Tile.DirtFloor) || (grid[newx+1][newy] == Tile.Corridor))
{
validTile = Direction.West;
xmod = -1;
ymod = 0;
}
if (validTile != null)
{
if (grid[newx][newy+1] == Tile.Door)
{
validTile = null;
} else if (grid[newx-1][newy] == Tile.Door)
{
validTile = null;
} else if (grid[newx][newy-1] == Tile.Door)
{
validTile = null;
} else if (grid[newx+1][newy] == Tile.Door)
{
validTile = null;
}
}
if (validTile != null)
{
break;
}
}
}
if (validTile != null)
{
if (Functions.random(0, 100) <= 75)
{
if (makeRoom(newx+xmod, newy+ymod, validTile))
{
currentFeatures++;
grid[newx][newy] = Tile.Door;
grid[newx+xmod][newy+ymod] = Tile.DirtFloor;
}
} else {
if (makeCorridor(newx+xmod, newy+ymod, validTile))
{
currentFeatures++;
grid[newx][newy] = Tile.Door;
}
}
}
}
int newx = 0;
int newy = 0;
int ways = 0;
int state = 0;
while (state != 10)
{
for (int testing = 0; testing < 1000; testing++)
{
newx = Functions.random(1, MAP_WIDTH-1);
newy = Functions.random(1, MAP_HEIGHT-2);
ways = 4;
for (Direction dir : Direction.values())
{
Point to = dir.to(new Point(newx, newy));
if ((isValidPosition(newx, newy)) && (grid[to.x][to.y] == Tile.DirtFloor) || (grid[to.x][to.y] == Tile.Corridor))
{
ways--;
}
}
if (state == 0)
{
if (ways == 0)
{
grid[newx][newy] = Tile.UpStairs;
state = 1;
break;
}
} else if (state == 1)
{
if (ways == 0)
{
grid[newx][newy] = Tile.DownStairs;
playerx=newx+1;
playery=newy;
state = 10;
break;
}
}
}
}
adjustViewport();
calculateFieldOfView();
}
| public MapViewGameState()
{
grid = new Tile[MAP_WIDTH][MAP_HEIGHT];
gridLighting = new boolean[MAP_WIDTH][MAP_HEIGHT];
for (int x=0; x<MAP_WIDTH; x++)
{
for (int y=0; y<MAP_HEIGHT; y++)
{
if ((x == 0) || (x == MAP_WIDTH-1) || (y == 0) || (y == MAP_HEIGHT-1))
{
grid[x][y] = Tile.StoneWall;
} else {
grid[x][y] = Tile.Unused;
}
}
}
makeRoom(MAP_WIDTH/2, MAP_HEIGHT/2, Direction.getRandomDirection());
int currentFeatures = 1;
int objects = 300;
for (int countingTries = 0; countingTries < 1000; countingTries++)
{
if (currentFeatures == objects)
{
break;
}
int newx = 0;
int xmod = 0;
int newy = 0;
int ymod = 0;
Direction validTile = null;
for (int testing = 0; testing < 1000; testing++)
{
newx = Functions.random(1, MAP_WIDTH-1);
newy = Functions.random(1, MAP_HEIGHT-1);
validTile = null;
if ((grid[newx][newy] == Tile.DirtWall) || (grid[newx][newy] == Tile.Corridor))
{
if ((grid[newx][newy+1] == Tile.DirtFloor) || (grid[newx][newy+1] == Tile.Corridor))
{
validTile = Direction.North;
xmod = 0;
ymod = -1;
} else if ((grid[newx-1][newy] == Tile.DirtFloor) || (grid[newx-1][newy] == Tile.Corridor))
{
validTile = Direction.East;
xmod = 1;
ymod = 0;
} else if ((grid[newx][newy-1] == Tile.DirtFloor) || (grid[newx][newy-1] == Tile.Corridor))
{
validTile = Direction.South;
xmod = 0;
ymod = 1;
} else if ((grid[newx+1][newy] == Tile.DirtFloor) || (grid[newx+1][newy] == Tile.Corridor))
{
validTile = Direction.West;
xmod = -1;
ymod = 0;
}
if (validTile != null)
{
if (grid[newx][newy+1] == Tile.Door)
{
validTile = null;
} else if (grid[newx-1][newy] == Tile.Door)
{
validTile = null;
} else if (grid[newx][newy-1] == Tile.Door)
{
validTile = null;
} else if (grid[newx+1][newy] == Tile.Door)
{
validTile = null;
}
}
if (validTile != null)
{
break;
}
}
}
if (validTile != null)
{
if (Functions.random(0, 100) <= 75)
{
if (makeRoom(newx+xmod, newy+ymod, validTile))
{
currentFeatures++;
grid[newx][newy] = Tile.Door;
grid[newx+xmod][newy+ymod] = Tile.DirtFloor;
}
} else {
if (makeCorridor(newx+xmod, newy+ymod, validTile))
{
currentFeatures++;
grid[newx][newy] = Tile.Door;
}
}
}
}
int newx = 0;
int newy = 0;
int ways = 0;
int state = 0;
while (state != 10)
{
for (int testing = 0; testing < 1000; testing++)
{
newx = Functions.random(1, MAP_WIDTH-1);
newy = Functions.random(1, MAP_HEIGHT-2);
ways = 4;
for (Direction dir : Direction.values())
{
Point to = dir.to(new Point(newx, newy));
if ((isValidPosition(to.x, to.y)) && (grid[to.x][to.y] == Tile.DirtFloor) || (grid[to.x][to.y] == Tile.Corridor))
{
ways--;
}
}
if (state == 0)
{
if (ways == 0)
{
grid[newx][newy] = Tile.UpStairs;
state = 1;
break;
}
} else if (state == 1)
{
if (ways == 0)
{
grid[newx][newy] = Tile.DownStairs;
playerx=newx+1;
playery=newy;
state = 10;
break;
}
}
}
}
adjustViewport();
calculateFieldOfView();
}
|
diff --git a/core/src/main/java/org/apache/ldap/server/jndi/DefaultContextFactoryService.java b/core/src/main/java/org/apache/ldap/server/jndi/DefaultContextFactoryService.java
index 9e79910bf2..247f316122 100644
--- a/core/src/main/java/org/apache/ldap/server/jndi/DefaultContextFactoryService.java
+++ b/core/src/main/java/org/apache/ldap/server/jndi/DefaultContextFactoryService.java
@@ -1,617 +1,617 @@
/*
* Copyright 2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
package org.apache.ldap.server.jndi;
import java.util.Hashtable;
import java.util.Iterator;
import javax.naming.Context;
import javax.naming.Name;
import javax.naming.NamingException;
import javax.naming.NoPermissionException;
import javax.naming.directory.Attribute;
import javax.naming.directory.Attributes;
import org.apache.ldap.common.exception.LdapAuthenticationNotSupportedException;
import org.apache.ldap.common.exception.LdapConfigurationException;
import org.apache.ldap.common.exception.LdapNoPermissionException;
import org.apache.ldap.common.message.LockableAttributesImpl;
import org.apache.ldap.common.message.ResultCodeEnum;
import org.apache.ldap.common.name.DnParser;
import org.apache.ldap.common.name.LdapName;
import org.apache.ldap.common.name.NameComponentNormalizer;
import org.apache.ldap.common.util.DateUtils;
import org.apache.ldap.server.configuration.Configuration;
import org.apache.ldap.server.configuration.ConfigurationException;
import org.apache.ldap.server.configuration.StartupConfiguration;
import org.apache.ldap.server.interceptor.InterceptorChain;
import org.apache.ldap.server.partition.ContextPartitionNexus;
import org.apache.ldap.server.partition.DefaultContextPartitionNexus;
import org.apache.ldap.server.schema.AttributeTypeRegistry;
import org.apache.ldap.server.schema.ConcreteNameComponentNormalizer;
import org.apache.ldap.server.schema.GlobalRegistries;
import org.apache.ldap.server.schema.bootstrap.BootstrapRegistries;
import org.apache.ldap.server.schema.bootstrap.BootstrapSchemaLoader;
/**
* Default implementation of {@link ContextFactoryService}.
*
* @author <a href="mailto:[email protected]">Apache Directory Project</a>
* @version $Rev$
*/
class DefaultContextFactoryService extends ContextFactoryService
{
private final String instanceId;
private final ContextFactoryConfiguration configuration = new DefaultContextFactoryConfiguration( this );
private ContextFactoryServiceListener serviceListener;
/** the initial context environment that fired up the backend subsystem */
private Hashtable environment;
/** the configuration */
private StartupConfiguration startupConfiguration;
/** the registries for system schema objects */
private GlobalRegistries globalRegistries;
/** the root nexus */
private DefaultContextPartitionNexus partitionNexus;
/** whether or not server is started for the first time */
private boolean firstStart;
/** The interceptor (or interceptor chain) for this service */
private InterceptorChain interceptorChain;
/** whether or not this instance has been shutdown */
private boolean started = false;
// ------------------------------------------------------------------------
// Constructor
// ------------------------------------------------------------------------
/**
* Creates a new instance.
*/
public DefaultContextFactoryService( String instanceId )
{
if( instanceId == null )
{
throw new NullPointerException( "instanceId" );
}
this.instanceId = instanceId;
// Register shutdown hook.
Runtime.getRuntime().addShutdownHook( new Thread( new Runnable() {
public void run()
{
try
{
shutdown();
}
catch( NamingException e )
{
e.printStackTrace();
}
}
}, "ApacheDS Shutdown Hook" ) );
}
// ------------------------------------------------------------------------
// BackendSubsystem Interface Method Implemetations
// ------------------------------------------------------------------------
public Context getJndiContext( String rootDN ) throws NamingException
{
return this.getJndiContext( null, null, "none", rootDN );
}
public synchronized Context getJndiContext( String principal, byte[] credential, String authentication, String rootDN ) throws NamingException
{
checkSecuritySettings( principal, credential, authentication );
if ( !started )
{
return new DeadContext();
}
Hashtable environment = getEnvironment();
environment.remove( Context.SECURITY_PRINCIPAL );
environment.remove( Context.SECURITY_CREDENTIALS );
environment.remove( Context.SECURITY_AUTHENTICATION );
if( principal != null )
{
environment.put( Context.SECURITY_PRINCIPAL, principal );
}
if( credential != null )
{
environment.put( Context.SECURITY_CREDENTIALS, credential );
}
if( authentication != null )
{
environment.put( Context.SECURITY_AUTHENTICATION, authentication );
}
if( rootDN == null )
{
rootDN = "";
}
environment.put( Context.PROVIDER_URL, rootDN );
return new ServerLdapContext( this, environment );
}
public synchronized void startup( ContextFactoryServiceListener listener, Hashtable env ) throws NamingException
{
Hashtable envCopy = ( Hashtable ) env.clone();
if( started )
{
return;
}
StartupConfiguration cfg = ( StartupConfiguration ) Configuration.toConfiguration( env );
envCopy.put( Context.PROVIDER_URL, "" );
try
{
cfg.validate();
}
catch( ConfigurationException e )
{
NamingException ne = new LdapConfigurationException( "Invalid configuration." );
ne.initCause( e );
throw ne;
}
this.environment = envCopy;
this.startupConfiguration = cfg;
listener.beforeStartup( this );
try
{
initialize();
firstStart = createBootstrapEntries();
createTestEntries();
this.serviceListener = listener;
started = true;
}
finally
{
listener.afterStartup( this );
}
}
public synchronized void sync() throws NamingException
{
if ( !started )
{
return;
}
serviceListener.beforeSync( this );
try
{
this.partitionNexus.sync();
}
finally
{
serviceListener.afterSync( this );
}
}
public synchronized void shutdown() throws NamingException
{
if ( !started )
{
return;
}
serviceListener.beforeShutdown( this );
try
{
this.partitionNexus.sync();
this.partitionNexus.destroy();
this.interceptorChain.destroy();
this.started = false;
}
finally
{
environment = null;
interceptorChain = null;
startupConfiguration = null;
serviceListener.afterShutdown( this );
}
}
public String getInstanceId()
{
return instanceId;
}
public ContextFactoryConfiguration getConfiguration()
{
return configuration;
}
public Hashtable getEnvironment()
{
return ( Hashtable ) environment.clone();
}
public ContextFactoryServiceListener getServiceListener()
{
return serviceListener;
}
public StartupConfiguration getStartupConfiguration()
{
return startupConfiguration;
}
public GlobalRegistries getGlobalRegistries()
{
return globalRegistries;
}
public ContextPartitionNexus getPartitionNexus()
{
return partitionNexus;
}
public InterceptorChain getInterceptorChain()
{
return interceptorChain;
}
public boolean isFirstStart()
{
return firstStart;
}
public boolean isStarted()
{
return started;
}
/**
* Checks to make sure security environment parameters are set correctly.
*
* @throws javax.naming.NamingException if the security settings are not correctly configured.
*/
private void checkSecuritySettings( String principal, byte[] credential, String authentication ) throws NamingException
{
if( authentication == null )
{
authentication = "";
}
/*
* If bind is simple make sure we have the credentials and the
* principal name set within the environment, otherwise complain
*/
if ( "simple".equalsIgnoreCase( authentication ) )
{
if ( credential == null )
{
throw new LdapConfigurationException( "missing required "
+ Context.SECURITY_CREDENTIALS + " property for simple authentication" );
}
if ( principal == null )
{
throw new LdapConfigurationException( "missing required "
+ Context.SECURITY_PRINCIPAL + " property for simple authentication" );
}
}
/*
* If bind is none make sure credentials and the principal
* name are NOT set within the environment, otherwise complain
*/
else if ( "none".equalsIgnoreCase( authentication ) )
{
if ( credential != null )
{
throw new LdapConfigurationException( "ambiguous bind "
+ "settings encountered where bind is anonymous yet "
+ Context.SECURITY_CREDENTIALS + " property is set" );
}
if ( principal != null )
{
throw new LdapConfigurationException( "ambiguous bind "
+ "settings encountered where bind is anonymous yet "
+ Context.SECURITY_PRINCIPAL + " property is set" );
}
if( !startupConfiguration.isAllowAnonymousAccess() )
{
throw new LdapNoPermissionException( "Anonymous access disabled." );
}
}
else
{
/*
* If bind is anything other than simple or none we need to
* complain because SASL is not a supported auth method yet
*/
throw new LdapAuthenticationNotSupportedException( "Unknown authentication type: '" + authentication + "'", ResultCodeEnum.AUTHMETHODNOTSUPPORTED );
}
}
/**
* Returns true if we had to create the bootstrap entries on the first
* start of the server. Otherwise if all entries exist, meaning none
* had to be created, then we are not starting for the first time.
*
* @throws javax.naming.NamingException
*/
private boolean createBootstrapEntries() throws NamingException
{
boolean firstStart = false;
// -------------------------------------------------------------------
// create admin entry
// -------------------------------------------------------------------
/*
* If the admin entry is there, then the database was already created
*/
if ( !partitionNexus.hasEntry( ContextPartitionNexus.getAdminName() ) )
{
checkPermissionToCreateBootstrapEntries();
firstStart = true;
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "person" );
attributes.put( "objectClass", "organizationalPerson" );
attributes.put( "objectClass", "inetOrgPerson" );
attributes.put( "uid", ContextPartitionNexus.ADMIN_UID );
attributes.put( "userPassword", environment.get( Context.SECURITY_CREDENTIALS ) );
attributes.put( "displayName", "Directory Superuser" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
attributes.put( "displayName", "Directory Superuser" );
partitionNexus.add( ContextPartitionNexus.ADMIN_PRINCIPAL, ContextPartitionNexus.getAdminName(), attributes );
}
// -------------------------------------------------------------------
// create system users area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=users,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "users" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=users,ou=system", new LdapName( "ou=users,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system groups area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=groups,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "groups" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=groups,ou=system", new LdapName( "ou=groups,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "configuration" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=configuration,ou=system", new LdapName( "ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for partition information
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=partitions,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "partitions" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=partitions,ou=configuration,ou=system",
new LdapName( "ou=partitions,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for services
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=services,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "services" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=services,ou=configuration,ou=system",
new LdapName( "ou=services,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for interceptors
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=interceptors,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
- attributes.put( "ou", "configuration" );
+ attributes.put( "ou", "interceptors" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=interceptors,ou=configuration,ou=system",
new LdapName( "ou=interceptors,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system preferences area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "prefNodeName=sysPrefRoot,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "prefNode" );
attributes.put( "objectClass", "extensibleObject" );
attributes.put( "prefNodeName", "sysPrefRoot" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
LdapName dn = new LdapName( "prefNodeName=sysPrefRoot,ou=system" );
partitionNexus.add( "prefNodeName=sysPrefRoot,ou=system", dn, attributes );
}
return firstStart;
}
private void checkPermissionToCreateBootstrapEntries() throws NamingException
{
String principal = ( String ) environment.get( Context.SECURITY_PRINCIPAL );
if( principal == null || !ContextPartitionNexus.ADMIN_PRINCIPAL.equals( principal ) )
{
throw new NoPermissionException(
"Only '" + ContextPartitionNexus.ADMIN_PRINCIPAL + "' can initiate the first run." );
}
}
private void createTestEntries() throws NamingException
{
/*
* Unfortunately to test non-root user startup of the core and make sure
* all the appropriate functionality is there we need to load more user
* entries at startup due to a chicken and egg like problem. The value
* of this property is a list of attributes to be added.
*/
Iterator i = startupConfiguration.getTestEntries().iterator();
while( i.hasNext() )
{
Attributes entry = ( Attributes ) i.next();
entry.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
entry.put( "createTimestamp", DateUtils.getGeneralizedTime() );
Attribute dn = ( Attribute ) entry.get( "dn" ).clone();
AttributeTypeRegistry registry = globalRegistries.getAttributeTypeRegistry();
NameComponentNormalizer ncn = new ConcreteNameComponentNormalizer( registry );
DnParser parser = new DnParser( ncn );
Name ndn = parser.parse( ( String ) dn.get() );
partitionNexus.add( ( String ) dn.get(), ndn, entry );
}
}
/**
* Kicks off the initialization of the entire system.
*
* @throws javax.naming.NamingException if there are problems along the way
*/
private void initialize() throws NamingException
{
// --------------------------------------------------------------------
// Load the schema here and check that it is ok!
// --------------------------------------------------------------------
BootstrapRegistries bootstrapRegistries = new BootstrapRegistries();
BootstrapSchemaLoader loader = new BootstrapSchemaLoader();
loader.load( startupConfiguration.getBootstrapSchemas(), bootstrapRegistries );
java.util.List errors = bootstrapRegistries.checkRefInteg();
if ( !errors.isEmpty() )
{
NamingException e = new NamingException();
e.setRootCause( ( Throwable ) errors.get( 0 ) );
throw e;
}
globalRegistries = new GlobalRegistries( bootstrapRegistries );
partitionNexus = new DefaultContextPartitionNexus( new LockableAttributesImpl() );
partitionNexus.init( configuration, null );
interceptorChain = new InterceptorChain();
interceptorChain.init( configuration );
}
}
| true | true | private boolean createBootstrapEntries() throws NamingException
{
boolean firstStart = false;
// -------------------------------------------------------------------
// create admin entry
// -------------------------------------------------------------------
/*
* If the admin entry is there, then the database was already created
*/
if ( !partitionNexus.hasEntry( ContextPartitionNexus.getAdminName() ) )
{
checkPermissionToCreateBootstrapEntries();
firstStart = true;
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "person" );
attributes.put( "objectClass", "organizationalPerson" );
attributes.put( "objectClass", "inetOrgPerson" );
attributes.put( "uid", ContextPartitionNexus.ADMIN_UID );
attributes.put( "userPassword", environment.get( Context.SECURITY_CREDENTIALS ) );
attributes.put( "displayName", "Directory Superuser" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
attributes.put( "displayName", "Directory Superuser" );
partitionNexus.add( ContextPartitionNexus.ADMIN_PRINCIPAL, ContextPartitionNexus.getAdminName(), attributes );
}
// -------------------------------------------------------------------
// create system users area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=users,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "users" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=users,ou=system", new LdapName( "ou=users,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system groups area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=groups,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "groups" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=groups,ou=system", new LdapName( "ou=groups,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "configuration" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=configuration,ou=system", new LdapName( "ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for partition information
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=partitions,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "partitions" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=partitions,ou=configuration,ou=system",
new LdapName( "ou=partitions,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for services
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=services,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "services" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=services,ou=configuration,ou=system",
new LdapName( "ou=services,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for interceptors
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=interceptors,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "configuration" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=interceptors,ou=configuration,ou=system",
new LdapName( "ou=interceptors,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system preferences area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "prefNodeName=sysPrefRoot,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "prefNode" );
attributes.put( "objectClass", "extensibleObject" );
attributes.put( "prefNodeName", "sysPrefRoot" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
LdapName dn = new LdapName( "prefNodeName=sysPrefRoot,ou=system" );
partitionNexus.add( "prefNodeName=sysPrefRoot,ou=system", dn, attributes );
}
return firstStart;
}
| private boolean createBootstrapEntries() throws NamingException
{
boolean firstStart = false;
// -------------------------------------------------------------------
// create admin entry
// -------------------------------------------------------------------
/*
* If the admin entry is there, then the database was already created
*/
if ( !partitionNexus.hasEntry( ContextPartitionNexus.getAdminName() ) )
{
checkPermissionToCreateBootstrapEntries();
firstStart = true;
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "person" );
attributes.put( "objectClass", "organizationalPerson" );
attributes.put( "objectClass", "inetOrgPerson" );
attributes.put( "uid", ContextPartitionNexus.ADMIN_UID );
attributes.put( "userPassword", environment.get( Context.SECURITY_CREDENTIALS ) );
attributes.put( "displayName", "Directory Superuser" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
attributes.put( "displayName", "Directory Superuser" );
partitionNexus.add( ContextPartitionNexus.ADMIN_PRINCIPAL, ContextPartitionNexus.getAdminName(), attributes );
}
// -------------------------------------------------------------------
// create system users area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=users,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "users" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=users,ou=system", new LdapName( "ou=users,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system groups area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=groups,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "groups" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=groups,ou=system", new LdapName( "ou=groups,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "configuration" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=configuration,ou=system", new LdapName( "ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for partition information
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=partitions,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "partitions" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=partitions,ou=configuration,ou=system",
new LdapName( "ou=partitions,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for services
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=services,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "services" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=services,ou=configuration,ou=system",
new LdapName( "ou=services,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system configuration area for interceptors
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "ou=interceptors,ou=configuration,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "organizationalUnit" );
attributes.put( "ou", "interceptors" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
partitionNexus.add( "ou=interceptors,ou=configuration,ou=system",
new LdapName( "ou=interceptors,ou=configuration,ou=system" ), attributes );
}
// -------------------------------------------------------------------
// create system preferences area
// -------------------------------------------------------------------
if ( !partitionNexus.hasEntry( new LdapName( "prefNodeName=sysPrefRoot,ou=system" ) ) )
{
firstStart = true;
checkPermissionToCreateBootstrapEntries();
Attributes attributes = new LockableAttributesImpl();
attributes.put( "objectClass", "top" );
attributes.put( "objectClass", "prefNode" );
attributes.put( "objectClass", "extensibleObject" );
attributes.put( "prefNodeName", "sysPrefRoot" );
attributes.put( "creatorsName", ContextPartitionNexus.ADMIN_PRINCIPAL );
attributes.put( "createTimestamp", DateUtils.getGeneralizedTime() );
LdapName dn = new LdapName( "prefNodeName=sysPrefRoot,ou=system" );
partitionNexus.add( "prefNodeName=sysPrefRoot,ou=system", dn, attributes );
}
return firstStart;
}
|
diff --git a/src/checkstyle/com/puppycrawl/tools/checkstyle/CheckStyleTask.java b/src/checkstyle/com/puppycrawl/tools/checkstyle/CheckStyleTask.java
index 37a71b03..c669e339 100644
--- a/src/checkstyle/com/puppycrawl/tools/checkstyle/CheckStyleTask.java
+++ b/src/checkstyle/com/puppycrawl/tools/checkstyle/CheckStyleTask.java
@@ -1,445 +1,445 @@
////////////////////////////////////////////////////////////////////////////////
// checkstyle: Checks Java source code for adherence to a set of rules.
// Copyright (C) 2001 Oliver Burn
//
// 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.puppycrawl.tools.checkstyle;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.List;
import org.apache.regexp.RESyntaxException;
import org.apache.tools.ant.BuildException;
import org.apache.tools.ant.DirectoryScanner;
import org.apache.tools.ant.Project;
import org.apache.tools.ant.Task;
import org.apache.tools.ant.taskdefs.LogOutputStream;
import org.apache.tools.ant.types.EnumeratedAttribute;
import org.apache.tools.ant.types.FileSet;
/**
* An implementation of a ANT task for calling checkstyle. See the documentation
* of the task for usage.
* @author <a href="mailto:[email protected]">Oliver Burn</a>
**/
public class CheckStyleTask
extends Task
{
/** poor man's enum for an xml formatter **/
private static final String E_XML = "xml";
/** poor man's enum for an plain formatter **/
private static final String E_PLAIN = "plain";
/** name of file to check **/
private String mFileName;
/** whether to fail build on violations **/
private boolean mFailOnViolation = true;
/** contains the filesets to process **/
private final List mFileSets = new ArrayList();
/** contains the formatters to log to **/
private final List mFormatters = new ArrayList();
/** the configuration to pass to the checker **/
private final Configuration mConfig = new Configuration();
////////////////////////////////////////////////////////////////////////////
// Setters for attributes
////////////////////////////////////////////////////////////////////////////
/**
* Adds a set of files (nested fileset attribute).
* @param aFS the file set to add
*/
public void addFileset(FileSet aFS)
{
mFileSets.add(aFS);
}
/**
* Add a formatter
* @param aFormatter the formatter to add for logging.
*/
public void addFormatter(Formatter aFormatter)
{
mFormatters.add(aFormatter);
}
/** @param aFile the file to be checked **/
public void setFile(File aFile)
{
mFileName = aFile.getAbsolutePath();
}
/** @param aAllowed whether tabs are allowed **/
public void setAllowTabs(boolean aAllowed)
{
mConfig.setAllowTabs(aAllowed);
}
/** @param aAllowed whether protected data is allowed **/
public void setAllowProtected(boolean aAllowed)
{
mConfig.setAllowProtected(aAllowed);
}
/** @param aAllowed whether allow having no author **/
public void setAllowNoAuthor(boolean aAllowed)
{
mConfig.setAllowNoAuthor(aAllowed);
}
/** @param aLen max allowed line length **/
public void setMaxLineLen(int aLen)
{
mConfig.setMaxLineLength(aLen);
}
/** @param aPat pattern for member variables **/
public void setMemberPattern(String aPat)
{
try {
mConfig.setMemberPat(aPat);
}
catch (RESyntaxException ex) {
throw new BuildException("Unable to parse memberPattern - ", ex);
}
}
/** @param aPat pattern for public member variables **/
public void setPublicMemberPattern(String aPat)
{
try {
mConfig.setPublicMemberPat(aPat);
}
catch (RESyntaxException ex) {
throw new BuildException(
"Unable to parse publicMemberPattern - ", ex);
}
}
/** @param aPat pattern for parameters **/
public void setParamPattern(String aPat)
{
try {
mConfig.setParamPat(aPat);
}
catch (RESyntaxException ex) {
throw new BuildException("Unable to parse paramPattern - ", ex);
}
}
/** @param aPat pattern for constant variables **/
public void setConstPattern(String aPat)
{
try {
mConfig.setStaticFinalPat(aPat);
}
catch (RESyntaxException ex) {
throw new BuildException("Unable to parse constPattern - " , ex);
}
}
/** @param aPat pattern for static variables **/
public void setStaticPattern(String aPat)
{
try {
mConfig.setStaticPat(aPat);
}
catch (RESyntaxException ex) {
throw new BuildException("Unable to parse staticPattern - ", ex);
}
}
/** @param aPat pattern for type names **/
public void setTypePattern(String aPat)
{
try {
mConfig.setTypePat(aPat);
}
catch (RESyntaxException ex) {
throw new BuildException("Unable to parse typePattern - ", ex);
}
}
/** @param aName header file name **/
public void setHeaderFile(File aName)
{
try {
mConfig.setHeaderFile(aName.getAbsolutePath());
}
catch (IOException ex) {
throw new BuildException("Unable to read headerfile - ", ex);
}
}
/** @param aFail whether to fail if a violation is found **/
public void setFailOnViolation(boolean aFail)
{
mFailOnViolation = aFail;
}
/** @param aNum **/
public void setHeaderIgnoreLine(int aNum)
{
mConfig.setHeaderIgnoreLineNo(aNum);
}
/** @param aRelax whether to be relaxed on Javadoc **/
public void setRelaxJavadoc(boolean aRelax)
{
mConfig.setRelaxJavadoc(aRelax);
}
/** @param aIgnore whether to ignore import statements **/
public void setIgnoreImports(boolean aIgnore)
{
mConfig.setIgnoreImports(aIgnore);
}
/** @param aIgnore whether to ignore whitespace **/
public void setIgnoreWhitespace(boolean aIgnore)
{
mConfig.setIgnoreWhitespace(aIgnore);
}
/** @param aIgnore whether to ignore braces **/
public void setIgnoreBraces(boolean aIgnore)
{
mConfig.setIgnoreBraces(aIgnore);
}
/** @param aCacheFile the file to cache which files have been checked **/
public void setCacheFile(File aCacheFile)
{
mConfig.setCacheFile(aCacheFile.getAbsolutePath());
}
////////////////////////////////////////////////////////////////////////////
// The doers
////////////////////////////////////////////////////////////////////////////
/**
* Actually checks the files specified. All errors are reported to
* System.out. Will fail if any errors occurred.
* @throws BuildException an error occurred
**/
public void execute()
throws BuildException
{
// Check for no arguments
if ((mFileName == null) && (mFileSets.size() == 0)) {
throw new BuildException("Must specify atleast one of 'file' " +
"or nested 'fileset'.", location);
}
// Create the checker
final int numErrs;
Checker c = null;
try {
c = new Checker(mConfig, System.out);
AuditListener[] listeners = getListeners();
for (int i = 0; i < listeners.length; i++) {
- c.addListener( listeners[i] );
+ c.addListener(listeners[i]);
}
final String[] files = scanFileSets();
numErrs = c.process(files);
}
catch (Exception e) {
throw new BuildException("Unable to create a Checker", e);
}
finally {
if (c != null) {
c.destroy();
}
}
if ((numErrs > 0) && mFailOnViolation) {
throw new BuildException("Got " + numErrs + " errors.", location);
}
}
/**
* Return the list of listeners set in this task.
* @return the list of listeners.
* @throws ClassNotFoundException if an error occurs
* @throws InstantiationException if an error occurs
* @throws IllegalAccessException if an error occurs
* @throws IOException if an error occurs
*/
protected AuditListener[] getListeners()
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, IOException
{
// @todo should we add a default plain stdout
// formatter ?
if (mFormatters.size() == 0) {
final Formatter f = new Formatter();
final FormatterType type = new FormatterType();
type.setValue(E_PLAIN);
f.setType(type);
mFormatters.add(f);
}
final AuditListener[] listeners = new AuditListener[mFormatters.size()];
for (int i = 0; i < listeners.length; i++) {
final Formatter f = (Formatter) mFormatters.get(i);
listeners[i] = f.createListener(this);
}
return listeners;
}
/**
* returns the list of files (full path name) to process.
* @return the list of files included via the filesets.
*/
protected String[] scanFileSets()
{
final ArrayList list = new ArrayList();
if (mFileName != null) {
// oops we've got an additional one to process, don't
// forget it. No sweat, it's fully resolved via the setter.
log("Adding standalone file for audit", Project.MSG_VERBOSE);
list.add(mFileName);
}
for (int i = 0; i < mFileSets.size(); i++) {
final FileSet fs = (FileSet) mFileSets.get(i);
final DirectoryScanner ds = fs.getDirectoryScanner(project);
ds.scan();
final String[] names = ds.getIncludedFiles();
log(i + ") Adding " + names.length + " files from directory " +
ds.getBasedir(), Project.MSG_VERBOSE);
for (int j = 0; j < names.length; j++) {
final String pathname =
ds.getBasedir() + File.separator + names[j];
list.add(pathname);
}
}
return (String[]) list.toArray(new String[0]);
}
/**
* Poor mans enumeration for the formatter types.
* @author <a href="mailto:[email protected]">Oliver Burn</a>
*/
public static class FormatterType
extends EnumeratedAttribute
{
/** my possible values **/
private static final String[] VALUES = {E_XML, E_PLAIN};
/** @see EnumeratedAttribute **/
public String[] getValues()
{
return VALUES;
}
}
/**
* Details about a formatter to be used.
* @author <a href="mailto:[email protected]">Oliver Burn</a>
*/
public static class Formatter
{
/** class name of formatter **/
private String mClassName = null;
/** whether formatter users a file **/
private boolean mUseFile = true;
/** the file to output to **/
private File mToFile = null;
/**
* Set the type of the formatter.
* @param aType the type
*/
public void setType(FormatterType aType)
{
final String val = aType.getValue();
if (E_XML.equals(val)) {
setClassname(XMLLogger.class.getName());
}
else if (E_PLAIN.equals(val)) {
setClassname(DefaultLogger.class.getName());
}
else {
throw new BuildException("Invalid formatter type: " + val);
}
}
/**
* Set the class name of the formatter.
* @param aTo the formatter class name
*/
public void setClassname(String aTo)
{
mClassName = aTo;
}
/**
* Set the file to output to.
* @param aTo the file to output to
*/
public void setTofile(File aTo)
{
mToFile = aTo;
}
/**
* Creates a listener for the formatter.
* @param aTask the task running
* @return a listener
* @throws ClassNotFoundException if an error occurs
* @throws InstantiationException if an error occurs
* @throws IllegalAccessException if an error occurs
* @throws IOException if an error occurs
*/
public AuditListener createListener(Task aTask)
throws ClassNotFoundException, InstantiationException,
IllegalAccessException, IOException
{
final Class clazz = Class.forName(mClassName);
final AuditListener listener = (AuditListener) clazz.newInstance();
if (listener instanceof Streamable) {
final Streamable o = (Streamable) listener;
o.setOutputStream(createOutputStream(aTask));
}
return listener;
}
/**
* @return an output stream to log with
* @param aTask the task to possibly log to
* @throws IOException if an error occurs
*/
protected OutputStream createOutputStream(Task aTask)
throws IOException
{
if (mToFile == null) {
return new LogOutputStream(aTask, Project.MSG_INFO);
}
return new FileOutputStream(mToFile);
}
}
}
| true | true | public void execute()
throws BuildException
{
// Check for no arguments
if ((mFileName == null) && (mFileSets.size() == 0)) {
throw new BuildException("Must specify atleast one of 'file' " +
"or nested 'fileset'.", location);
}
// Create the checker
final int numErrs;
Checker c = null;
try {
c = new Checker(mConfig, System.out);
AuditListener[] listeners = getListeners();
for (int i = 0; i < listeners.length; i++) {
c.addListener( listeners[i] );
}
final String[] files = scanFileSets();
numErrs = c.process(files);
}
catch (Exception e) {
throw new BuildException("Unable to create a Checker", e);
}
finally {
if (c != null) {
c.destroy();
}
}
if ((numErrs > 0) && mFailOnViolation) {
throw new BuildException("Got " + numErrs + " errors.", location);
}
}
| public void execute()
throws BuildException
{
// Check for no arguments
if ((mFileName == null) && (mFileSets.size() == 0)) {
throw new BuildException("Must specify atleast one of 'file' " +
"or nested 'fileset'.", location);
}
// Create the checker
final int numErrs;
Checker c = null;
try {
c = new Checker(mConfig, System.out);
AuditListener[] listeners = getListeners();
for (int i = 0; i < listeners.length; i++) {
c.addListener(listeners[i]);
}
final String[] files = scanFileSets();
numErrs = c.process(files);
}
catch (Exception e) {
throw new BuildException("Unable to create a Checker", e);
}
finally {
if (c != null) {
c.destroy();
}
}
if ((numErrs > 0) && mFailOnViolation) {
throw new BuildException("Got " + numErrs + " errors.", location);
}
}
|
diff --git a/web/src/sirius/web/http/MimeHelper.java b/web/src/sirius/web/http/MimeHelper.java
index c3c900e..c197ad6 100644
--- a/web/src/sirius/web/http/MimeHelper.java
+++ b/web/src/sirius/web/http/MimeHelper.java
@@ -1,282 +1,282 @@
/*
* Made with all the love in the world
* by scireum in Remshalden, Germany
*
* Copyright by scireum GmbH
* http://www.scireum.de - [email protected]
*/
package sirius.web.http;
import com.google.common.io.Files;
import sirius.kernel.commons.Strings;
import java.util.Map;
import java.util.TreeMap;
/**
* Guesses mime types based on file extensions.
* <p>
* Contains an internal table of the most common file extensions along with their mime type.
* </p>
*
* @author Andreas Haufler ([email protected])
* @since 2013/08
*/
public class MimeHelper {
/**
* Mime type of flash (swf) files.
*/
public static final String APPLICATION_X_SHOCKWAVE_FLASH = "application/x-shockwave-flash";
/**
* Mime type of PNG images
*/
public static final String IMAGE_PNG = "image/png";
/**
* Mime type of JPEG images
*/
public static final String IMAGE_JPEG = "image/jpeg";
/**
* Mime type of PDF files
*/
public static final String APPLICATION_PDF = "application/pdf".intern();
/**
* Mime type of CSS files
*/
public static final String TEXT_CSS = "text/css".intern();
/**
* Mime type of javascript (JS) files
*/
public static final String TEXT_JAVASCRIPT = "text/javascript".intern();
private static final Map<String, String> mimeTable = new TreeMap<String, String>();
static {
mimeTable.put("ai", "application/postscript");
mimeTable.put("aif", "audio/x-aiff");
mimeTable.put("aifc", "audio/x-aiff");
mimeTable.put("aiff", "audio/x-aiff");
mimeTable.put("asc", "text/plain");
mimeTable.put("atom", "application/atom+xml");
mimeTable.put("au", "audio/basic");
mimeTable.put("avi", "video/x-msvideo");
mimeTable.put("bcpio", "application/x-bcpio");
mimeTable.put("bin", "application/octet-stream");
mimeTable.put("bmp", "image/bmp");
mimeTable.put("cdf", "application/x-netcdf");
mimeTable.put("cgm", "image/cgm");
mimeTable.put("class", "application/octet-stream");
mimeTable.put("cpio", "application/x-cpio");
mimeTable.put("cpt", "application/mac-compactpro");
mimeTable.put("csh", "application/x-csh");
mimeTable.put("css", TEXT_CSS);
mimeTable.put("csv", "text/comma-separated-values");
mimeTable.put("dcr", "application/x-director");
mimeTable.put("dif", "video/x-dv");
mimeTable.put("dir", "application/x-director");
mimeTable.put("djv", "image/vnd.djvu");
mimeTable.put("djvu", "image/vnd.djvu");
mimeTable.put("dll", "application/octet-stream");
mimeTable.put("dmg", "application/octet-stream");
mimeTable.put("dms", "application/octet-stream");
mimeTable.put("doc", "application/msword");
mimeTable.put("dtd", "application/xml-dtd");
mimeTable.put("dv", "video/x-dv");
mimeTable.put("dvi", "application/x-dvi");
mimeTable.put("dxr", "application/x-director");
mimeTable.put("eps", "application/postscript");
mimeTable.put("etx", "text/x-setext");
mimeTable.put("exe", "application/octet-stream");
mimeTable.put("ez", "application/andrew-inset");
mimeTable.put("gif", "image/gif");
mimeTable.put("gram", "application/srgs");
mimeTable.put("grxml", "application/srgs+xml");
mimeTable.put("gtar", "application/x-gtar");
mimeTable.put("hdf", "application/x-hdf");
mimeTable.put("hqx", "application/mac-binhex40");
mimeTable.put("htm", "text/html");
mimeTable.put("html", "text/html");
mimeTable.put("ice", "x-conference/x-cooltalk");
mimeTable.put("ico", "image/x-icon");
mimeTable.put("ics", "text/calendar");
mimeTable.put("ief", "image/ief");
mimeTable.put("ifb", "text/calendar");
mimeTable.put("iges", "model/iges");
mimeTable.put("igs", "model/iges");
mimeTable.put("jnlp", "application/x-java-jnlp-file");
mimeTable.put("jp2", "image/jp2");
mimeTable.put("jpe", IMAGE_JPEG);
mimeTable.put("jpeg", IMAGE_JPEG);
mimeTable.put("jpg", IMAGE_JPEG);
mimeTable.put("js", TEXT_JAVASCRIPT);
mimeTable.put("kar", "audio/midi");
mimeTable.put("latex", "application/x-latex");
mimeTable.put("lha", "application/octet-stream");
mimeTable.put("log", "text/plain");
mimeTable.put("lzh", "application/octet-stream");
mimeTable.put("m3u", "audio/x-mpegurl");
mimeTable.put("m4a", "audio/mp4a-latm");
mimeTable.put("m4b", "audio/mp4a-latm");
mimeTable.put("m4p", "audio/mp4a-latm");
mimeTable.put("m4u", "video/vnd.mpegurl");
mimeTable.put("m4v", "video/x-m4v");
mimeTable.put("mac", "image/x-macpaint");
mimeTable.put("man", "application/x-troff-man");
mimeTable.put("mathml", "application/mathml+xml");
mimeTable.put("me", "application/x-troff-me");
mimeTable.put("mesh", "model/mesh");
mimeTable.put("mid", "audio/midi");
mimeTable.put("midi", "audio/midi");
mimeTable.put("mif", "application/vnd.mif");
mimeTable.put("mov", "video/quicktime");
mimeTable.put("movie", "video/x-sgi-movie");
mimeTable.put("mp2", "audio/mpeg");
mimeTable.put("mp3", "audio/mpeg");
mimeTable.put("mp4", "video/mp4");
mimeTable.put("mpe", "video/mpeg");
mimeTable.put("mpeg", "video/mpeg");
mimeTable.put("mpg", "video/mpeg");
mimeTable.put("mpga", "audio/mpeg");
mimeTable.put("ms", "application/x-troff-ms");
mimeTable.put("msh", "model/mesh");
mimeTable.put("mxu", "video/vnd.mpegurl");
mimeTable.put("nc", "application/x-netcdf");
mimeTable.put("oda", "application/oda");
mimeTable.put("ogg", "video/ogg");
mimeTable.put("ogv", "video/ogg");
mimeTable.put("pbm", "image/x-portable-bitmap");
mimeTable.put("pct", "image/pict");
mimeTable.put("pdb", "chemical/x-pdb");
mimeTable.put("pdf", "application/pdf");
mimeTable.put("pgm", "image/x-portable-graymap");
mimeTable.put("pgn", "application/x-chess-pgn");
mimeTable.put("pic", "image/pict");
mimeTable.put("pict", "image/pict");
mimeTable.put("png", IMAGE_PNG);
mimeTable.put("pnm", "image/x-portable-anymap");
mimeTable.put("pnt", "image/x-macpaint");
mimeTable.put("pntg", "image/x-macpaint");
mimeTable.put("ppm", "image/x-portable-pixmap");
mimeTable.put("ppt", "application/vnd.ms-powerpoint");
mimeTable.put("ps", "application/postscript");
mimeTable.put("qt", "video/quicktime");
mimeTable.put("qti", "image/x-quicktime");
mimeTable.put("qtif", "image/x-quicktime");
mimeTable.put("ra", "audio/x-pn-realaudio");
mimeTable.put("ram", "audio/x-pn-realaudio");
mimeTable.put("ras", "image/x-cmu-raster");
mimeTable.put("rdf", "application/rdf+xml");
mimeTable.put("rgb", "image/x-rgb");
mimeTable.put("rm", "application/vnd.rn-realmedia");
mimeTable.put("roff", "application/x-troff");
mimeTable.put("rtf", "text/rtf");
mimeTable.put("rtx", "text/richtext");
mimeTable.put("sgm", "text/sgml");
mimeTable.put("sgml", "text/sgml");
mimeTable.put("sh", "application/x-sh");
mimeTable.put("shar", "application/x-shar");
mimeTable.put("silo", "model/mesh");
mimeTable.put("sit", "application/x-stuffit");
mimeTable.put("skd", "application/x-koan");
mimeTable.put("skm", "application/x-koan");
mimeTable.put("skp", "application/x-koan");
mimeTable.put("skt", "application/x-koan");
mimeTable.put("smi", "application/smil");
mimeTable.put("smil", "application/smil");
mimeTable.put("snd", "audio/basic");
mimeTable.put("so", "application/octet-stream");
mimeTable.put("spl", "application/x-futuresplash");
mimeTable.put("src", "application/x-wais-source");
mimeTable.put("sv4cpio", "application/x-sv4cpio");
mimeTable.put("sv4crc", "application/x-sv4crc");
mimeTable.put("svg", "image/svg+xml");
mimeTable.put("swf", APPLICATION_X_SHOCKWAVE_FLASH);
mimeTable.put("t", "application/x-troff");
mimeTable.put("tar", "application/x-tar");
mimeTable.put("tcl", "application/x-tcl");
mimeTable.put("tex", "application/x-tex");
mimeTable.put("texi", "application/x-texinfo");
mimeTable.put("texinfo", "application/x-texinfo");
mimeTable.put("tif", "image/tiff");
mimeTable.put("tiff", "image/tiff");
mimeTable.put("tr", "application/x-troff");
mimeTable.put("tsv", "text/tab-separated-values");
mimeTable.put("txt", "text/plain");
mimeTable.put("ustar", "application/x-ustar");
mimeTable.put("vcd", "application/x-cdlink");
mimeTable.put("vrml", "model/vrml");
mimeTable.put("vxml", "application/voicexml+xml");
mimeTable.put("wav", "audio/x-wav");
mimeTable.put("wbmp", "image/vnd.wap.wbmp");
mimeTable.put("wbmxl", "application/vnd.wap.wbxml");
mimeTable.put("wml", "text/vnd.wap.wml");
mimeTable.put("wmlc", "application/vnd.wap.wmlc");
mimeTable.put("wmls", "text/vnd.wap.wmlscript");
mimeTable.put("wmlsc", "application/vnd.wap.wmlscriptc");
mimeTable.put("wrl", "model/vrml");
mimeTable.put("xbm", "image/x-xbitmap");
mimeTable.put("xht", "application/xhtml+xml");
mimeTable.put("xhtml", "application/xhtml+xml");
mimeTable.put("xls", "application/msexcel");
mimeTable.put("xlsx", "application/msexcel");
mimeTable.put("xml", "text/xml");
mimeTable.put("xpm", "image/x-xpixmap");
mimeTable.put("xsl", "application/xml");
mimeTable.put("xslt", "application/xslt+xml");
mimeTable.put("xul", "application/vnd.mozilla.xul+xml");
mimeTable.put("xwd", "image/x-xwindowdump");
mimeTable.put("xyz", "chemical/x-xyz");
mimeTable.put("zip", "application/zip");
}
/**
* Tries to guess the mime type for the given file, path or url based on its file ending.
*
* @param name the filename, path or URL to use to detect the mime type
* @return the mime type or <tt>null</tt> if the input was <tt>null</tt>
*/
public static String guessMimeType(String name) {
if (Strings.isEmpty(name)) {
return null;
}
// Fast lookup for common types....
- if (name.charAt(name.length() - 4) == '.') {
+ if (name.length() >= 4 && name.charAt(name.length() - 4) == '.') {
String ending = name.substring(name.length() - 3).toLowerCase().intern();
if ("jpg" == ending) {
return IMAGE_JPEG;
}
if ("swf" == ending) {
return APPLICATION_X_SHOCKWAVE_FLASH;
}
if ("pdf" == ending) {
return APPLICATION_PDF;
}
if ("png" == ending) {
return IMAGE_PNG;
}
if ("css" == ending) {
return TEXT_CSS;
}
if ("xml" == ending) {
return TEXT_JAVASCRIPT;
}
if ("txt" == ending) {
return TEXT_JAVASCRIPT;
}
}
name = Files.getFileExtension(name).toLowerCase();
String result = mimeTable.get(name);
if (result == null) {
return "application/octet-stream";
} else {
return result;
}
}
}
| true | true | public static String guessMimeType(String name) {
if (Strings.isEmpty(name)) {
return null;
}
// Fast lookup for common types....
if (name.charAt(name.length() - 4) == '.') {
String ending = name.substring(name.length() - 3).toLowerCase().intern();
if ("jpg" == ending) {
return IMAGE_JPEG;
}
if ("swf" == ending) {
return APPLICATION_X_SHOCKWAVE_FLASH;
}
if ("pdf" == ending) {
return APPLICATION_PDF;
}
if ("png" == ending) {
return IMAGE_PNG;
}
if ("css" == ending) {
return TEXT_CSS;
}
if ("xml" == ending) {
return TEXT_JAVASCRIPT;
}
if ("txt" == ending) {
return TEXT_JAVASCRIPT;
}
}
name = Files.getFileExtension(name).toLowerCase();
String result = mimeTable.get(name);
if (result == null) {
return "application/octet-stream";
} else {
return result;
}
}
| public static String guessMimeType(String name) {
if (Strings.isEmpty(name)) {
return null;
}
// Fast lookup for common types....
if (name.length() >= 4 && name.charAt(name.length() - 4) == '.') {
String ending = name.substring(name.length() - 3).toLowerCase().intern();
if ("jpg" == ending) {
return IMAGE_JPEG;
}
if ("swf" == ending) {
return APPLICATION_X_SHOCKWAVE_FLASH;
}
if ("pdf" == ending) {
return APPLICATION_PDF;
}
if ("png" == ending) {
return IMAGE_PNG;
}
if ("css" == ending) {
return TEXT_CSS;
}
if ("xml" == ending) {
return TEXT_JAVASCRIPT;
}
if ("txt" == ending) {
return TEXT_JAVASCRIPT;
}
}
name = Files.getFileExtension(name).toLowerCase();
String result = mimeTable.get(name);
if (result == null) {
return "application/octet-stream";
} else {
return result;
}
}
|
diff --git a/src/main/java/com/sk89q/worldguard/bukkit/FlagStateManager.java b/src/main/java/com/sk89q/worldguard/bukkit/FlagStateManager.java
index 1c47cc3e..f59793f4 100644
--- a/src/main/java/com/sk89q/worldguard/bukkit/FlagStateManager.java
+++ b/src/main/java/com/sk89q/worldguard/bukkit/FlagStateManager.java
@@ -1,241 +1,241 @@
// $Id$
/*
* WorldGuard
* Copyright (C) 2010 sk89q <http://www.sk89q.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 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package com.sk89q.worldguard.bukkit;
import com.sk89q.worldedit.Vector;
import com.sk89q.worldguard.protection.ApplicableRegionSet;
import com.sk89q.worldguard.protection.flags.DefaultFlag;
import com.sk89q.worldguard.protection.managers.RegionManager;
import org.bukkit.GameMode;
import org.bukkit.World;
import org.bukkit.entity.Player;
import java.util.HashMap;
import java.util.Map;
import static com.sk89q.worldguard.bukkit.BukkitUtil.toVector;
/**
* This processes per-player state information and is also meant to be used
* as a scheduled task.
*
* @author sk89q
*/
public class FlagStateManager implements Runnable {
public static final int RUN_DELAY = 20;
private WorldGuardPlugin plugin;
private Map<String, PlayerFlagState> states;
/**
* Construct the object.
*
* @param plugin The plugin instance
*/
public FlagStateManager(WorldGuardPlugin plugin) {
this.plugin = plugin;
states = new HashMap<String, PlayerFlagState>();
}
/**
* Run the task.
*/
public void run() {
Player[] players = plugin.getServer().getOnlinePlayers();
ConfigurationManager config = plugin.getGlobalStateManager();
for (Player player : players) {
WorldConfiguration worldConfig = config.get(player.getWorld());
if (!worldConfig.useRegions) {
continue;
}
PlayerFlagState state;
synchronized (this) {
state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
}
}
Vector playerLocation = toVector(player.getLocation());
RegionManager regionManager = plugin.getGlobalRegionManager().get(player.getWorld());
ApplicableRegionSet applicable = regionManager.getApplicableRegions(playerLocation);
if (!RegionQueryUtil.isInvincible(plugin, player, applicable)
&& !plugin.getGlobalStateManager().hasGodMode(player)
&& !(player.getGameMode() == GameMode.CREATIVE)) {
processHeal(applicable, player, state);
processFeed(applicable, player, state);
}
}
}
/**
* Process healing for a player.
*
* @param applicable The set of applicable regions
* @param player The player to process healing flags on
* @param state The player's state
*/
private void processHeal(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
if (player.getHealth() <= 0) {
return;
}
long now = System.currentTimeMillis();
Integer healAmount = applicable.getFlag(DefaultFlag.HEAL_AMOUNT);
Integer healDelay = applicable.getFlag(DefaultFlag.HEAL_DELAY);
Integer minHealth = applicable.getFlag(DefaultFlag.MIN_HEAL);
Integer maxHealth = applicable.getFlag(DefaultFlag.MAX_HEAL);
if (healAmount == null || healDelay == null || healAmount == 0 || healDelay < 0) {
return;
}
if (minHealth == null) minHealth = 0;
- if (maxHealth == null) maxHealth = 20;
+ if (maxHealth == null) maxHealth = player.getMaxHealth();
// Apply a cap to prevent possible exceptions
minHealth = Math.min(player.getMaxHealth(), minHealth);
maxHealth = Math.min(player.getMaxHealth(), maxHealth);
if (player.getHealth() >= maxHealth && healAmount > 0) {
return;
}
if (healDelay <= 0) {
player.setHealth(healAmount > 0 ? maxHealth : minHealth); // this will insta-kill if the flag is unset
state.lastHeal = now;
} else if (now - state.lastHeal > healDelay * 1000) {
// clamp health between minimum and maximum
player.setHealth(Math.min(maxHealth, Math.max(minHealth, player.getHealth() + healAmount)));
state.lastHeal = now;
}
}
/**
* Process restoring hunger for a player.
*
* @param applicable The set of applicable regions
* @param player The player to process hunger flags on
* @param state The player's state
*/
private void processFeed(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
long now = System.currentTimeMillis();
Integer feedAmount = applicable.getFlag(DefaultFlag.FEED_AMOUNT);
Integer feedDelay = applicable.getFlag(DefaultFlag.FEED_DELAY);
Integer minHunger = applicable.getFlag(DefaultFlag.MIN_FOOD);
Integer maxHunger = applicable.getFlag(DefaultFlag.MAX_FOOD);
if (feedAmount == null || feedDelay == null || feedAmount == 0 || feedDelay < 0) {
return;
}
if (minHunger == null) minHunger = 0;
if (maxHunger == null) maxHunger = 20;
// Apply a cap to prevent possible exceptions
minHunger = Math.min(20, minHunger);
maxHunger = Math.min(20, maxHunger);
if (player.getFoodLevel() >= maxHunger && feedAmount > 0) {
return;
}
if (feedDelay <= 0) {
player.setFoodLevel(feedAmount > 0 ? maxHunger : minHunger);
state.lastFeed = now;
} else if (now - state.lastFeed > feedDelay * 1000) {
// clamp health between minimum and maximum
player.setFoodLevel(Math.min(maxHunger, Math.max(minHunger, player.getFoodLevel() + feedAmount)));
state.lastFeed = now;
}
}
/**
* Forget a player.
*
* @param player The player to forget
*/
public synchronized void forget(Player player) {
states.remove(player.getName());
}
/**
* Forget all managed players. Use with caution.
*/
public synchronized void forgetAll() {
states.clear();
}
/**
* Get a player's flag state. A new state will be created if there is no existing
* state for the player.
*
* @param player The player to get a state for
* @return The {@code player}'s state
*/
public synchronized PlayerFlagState getState(Player player) {
PlayerFlagState state = states.get(player.getName());
if (state == null) {
state = new PlayerFlagState();
states.put(player.getName(), state);
}
return state;
}
/**
* Keeps state per player.
*/
public static class PlayerFlagState {
public long lastHeal;
public long lastFeed;
public String lastGreeting;
public String lastFarewell;
public Boolean lastExitAllowed = null;
public Boolean notifiedForLeave = false;
public Boolean notifiedForEnter = false;
public GameMode lastGameMode;
public World lastWorld;
public int lastBlockX;
public int lastBlockY;
public int lastBlockZ;
/* Used to cache invincibility status */
public World lastInvincibleWorld;
public int lastInvincibleX;
public int lastInvincibleY;
public int lastInvincibleZ;
public boolean wasInvincible;
}
}
| true | true | private void processHeal(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
if (player.getHealth() <= 0) {
return;
}
long now = System.currentTimeMillis();
Integer healAmount = applicable.getFlag(DefaultFlag.HEAL_AMOUNT);
Integer healDelay = applicable.getFlag(DefaultFlag.HEAL_DELAY);
Integer minHealth = applicable.getFlag(DefaultFlag.MIN_HEAL);
Integer maxHealth = applicable.getFlag(DefaultFlag.MAX_HEAL);
if (healAmount == null || healDelay == null || healAmount == 0 || healDelay < 0) {
return;
}
if (minHealth == null) minHealth = 0;
if (maxHealth == null) maxHealth = 20;
// Apply a cap to prevent possible exceptions
minHealth = Math.min(player.getMaxHealth(), minHealth);
maxHealth = Math.min(player.getMaxHealth(), maxHealth);
if (player.getHealth() >= maxHealth && healAmount > 0) {
return;
}
if (healDelay <= 0) {
player.setHealth(healAmount > 0 ? maxHealth : minHealth); // this will insta-kill if the flag is unset
state.lastHeal = now;
} else if (now - state.lastHeal > healDelay * 1000) {
// clamp health between minimum and maximum
player.setHealth(Math.min(maxHealth, Math.max(minHealth, player.getHealth() + healAmount)));
state.lastHeal = now;
}
}
| private void processHeal(ApplicableRegionSet applicable, Player player,
PlayerFlagState state) {
if (player.getHealth() <= 0) {
return;
}
long now = System.currentTimeMillis();
Integer healAmount = applicable.getFlag(DefaultFlag.HEAL_AMOUNT);
Integer healDelay = applicable.getFlag(DefaultFlag.HEAL_DELAY);
Integer minHealth = applicable.getFlag(DefaultFlag.MIN_HEAL);
Integer maxHealth = applicable.getFlag(DefaultFlag.MAX_HEAL);
if (healAmount == null || healDelay == null || healAmount == 0 || healDelay < 0) {
return;
}
if (minHealth == null) minHealth = 0;
if (maxHealth == null) maxHealth = player.getMaxHealth();
// Apply a cap to prevent possible exceptions
minHealth = Math.min(player.getMaxHealth(), minHealth);
maxHealth = Math.min(player.getMaxHealth(), maxHealth);
if (player.getHealth() >= maxHealth && healAmount > 0) {
return;
}
if (healDelay <= 0) {
player.setHealth(healAmount > 0 ? maxHealth : minHealth); // this will insta-kill if the flag is unset
state.lastHeal = now;
} else if (now - state.lastHeal > healDelay * 1000) {
// clamp health between minimum and maximum
player.setHealth(Math.min(maxHealth, Math.max(minHealth, player.getHealth() + healAmount)));
state.lastHeal = now;
}
}
|
diff --git a/src/main/java/com/adrguides/LoadActivity.java b/src/main/java/com/adrguides/LoadActivity.java
index 9981f24..ed83cd4 100644
--- a/src/main/java/com/adrguides/LoadActivity.java
+++ b/src/main/java/com/adrguides/LoadActivity.java
@@ -1,61 +1,61 @@
// Guidebook is an Android application that reads audioguides using Text-to-Speech services.
// Copyright (C) 2013 Adrián Romero Corchado
//
// This program is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// This program is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this program. If not, see <http://www.gnu.org/licenses/>.
package com.adrguides;
import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.content.Intent;
import android.graphics.Point;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import android.widget.ViewSwitcher;
/**
* Created by adrian on 2/09/13.
*/
public class LoadActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
LoadGuideFragment loadguide = (LoadGuideFragment) fm.findFragmentByTag(LoadGuideFragment.TAG);
if (loadguide == null) {
// Calculate rezize dimensions
Point size = new Point();
this.getWindowManager().getDefaultDisplay().getSize(size);
int imagesize = Math.max(size.x, size.y);
// loading guide
loadguide = new LoadGuideFragment();
fm.beginTransaction().add(loadguide, LoadGuideFragment.TAG).commit();
Log.d("com.adrguides.LoadActivity", "Loading Data --> " + getIntent().getDataString());
loadguide.loadGuide(getApplicationContext(), getIntent().getDataString(), imagesize);
}
Fragment loadfragment = fm.findFragmentByTag(LoadFragment.TAG);
if (loadfragment == null) {
loadfragment = new LoadFragment();
fm.beginTransaction()
- .add(android.R.id.content, loadfragment, ReadGuideFragment.TAG)
+ .add(android.R.id.content, loadfragment, LoadFragment.TAG)
.commit();
}
}
}
| true | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
LoadGuideFragment loadguide = (LoadGuideFragment) fm.findFragmentByTag(LoadGuideFragment.TAG);
if (loadguide == null) {
// Calculate rezize dimensions
Point size = new Point();
this.getWindowManager().getDefaultDisplay().getSize(size);
int imagesize = Math.max(size.x, size.y);
// loading guide
loadguide = new LoadGuideFragment();
fm.beginTransaction().add(loadguide, LoadGuideFragment.TAG).commit();
Log.d("com.adrguides.LoadActivity", "Loading Data --> " + getIntent().getDataString());
loadguide.loadGuide(getApplicationContext(), getIntent().getDataString(), imagesize);
}
Fragment loadfragment = fm.findFragmentByTag(LoadFragment.TAG);
if (loadfragment == null) {
loadfragment = new LoadFragment();
fm.beginTransaction()
.add(android.R.id.content, loadfragment, ReadGuideFragment.TAG)
.commit();
}
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
FragmentManager fm = getFragmentManager();
LoadGuideFragment loadguide = (LoadGuideFragment) fm.findFragmentByTag(LoadGuideFragment.TAG);
if (loadguide == null) {
// Calculate rezize dimensions
Point size = new Point();
this.getWindowManager().getDefaultDisplay().getSize(size);
int imagesize = Math.max(size.x, size.y);
// loading guide
loadguide = new LoadGuideFragment();
fm.beginTransaction().add(loadguide, LoadGuideFragment.TAG).commit();
Log.d("com.adrguides.LoadActivity", "Loading Data --> " + getIntent().getDataString());
loadguide.loadGuide(getApplicationContext(), getIntent().getDataString(), imagesize);
}
Fragment loadfragment = fm.findFragmentByTag(LoadFragment.TAG);
if (loadfragment == null) {
loadfragment = new LoadFragment();
fm.beginTransaction()
.add(android.R.id.content, loadfragment, LoadFragment.TAG)
.commit();
}
}
|
diff --git a/processor-core/src/main/java/de/plushnikov/intellij/lombok/processor/SynchronizedProcessor.java b/processor-core/src/main/java/de/plushnikov/intellij/lombok/processor/SynchronizedProcessor.java
index e720fb7..eb97f73 100644
--- a/processor-core/src/main/java/de/plushnikov/intellij/lombok/processor/SynchronizedProcessor.java
+++ b/processor-core/src/main/java/de/plushnikov/intellij/lombok/processor/SynchronizedProcessor.java
@@ -1,70 +1,70 @@
package de.plushnikov.intellij.lombok.processor;
import com.intellij.codeInsight.intention.QuickFixFactory;
import com.intellij.openapi.util.text.StringUtil;
import com.intellij.psi.PsiAnnotation;
import com.intellij.psi.PsiClass;
import com.intellij.psi.PsiElement;
import com.intellij.psi.PsiField;
import com.intellij.psi.PsiMethod;
import com.intellij.psi.PsiModifier;
import com.intellij.psi.util.PsiTreeUtil;
import de.plushnikov.intellij.lombok.problem.LombokProblem;
import de.plushnikov.intellij.lombok.problem.ProblemNewBuilder;
import de.plushnikov.intellij.lombok.util.PsiAnnotationUtil;
import lombok.Synchronized;
import org.jetbrains.annotations.NotNull;
import java.util.ArrayList;
import java.util.Collection;
/**
* Inspect and validate @Synchronized lombok annotation
*
* @author Plushnikov Michail
*/
public class SynchronizedProcessor extends AbstractLombokProcessor {
public static final String CLASS_NAME = Synchronized.class.getName();
public SynchronizedProcessor() {
super(CLASS_NAME, PsiElement.class);
}
@Override
public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) {
Collection<LombokProblem> result = new ArrayList<LombokProblem>(2);
final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(result);
PsiMethod psiMethod = PsiTreeUtil.getParentOfType(psiAnnotation, PsiMethod.class);
if (null != psiMethod) {
if (psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
problemNewBuilder.addError("'@Synchronized' is legal only on concrete methods.",
QuickFixFactory.getInstance().createModifierListFix(psiMethod, PsiModifier.ABSTRACT, false, false)
);
}
final String lockFieldName = PsiAnnotationUtil.getAnnotationValue(psiAnnotation, "value", String.class);
if (StringUtil.isNotEmpty(lockFieldName)) {
final PsiClass containingClass = psiMethod.getContainingClass();
if (null != containingClass) {
final PsiField lockField = containingClass.findFieldByName(lockFieldName, true);
if (null != lockField) {
- if (lockField.hasModifierProperty(PsiModifier.FINAL)) {
+ if (!lockField.hasModifierProperty(PsiModifier.FINAL)) {
problemNewBuilder.addWarning(String.format("Synchronization on a non-final field %s.", lockFieldName),
QuickFixFactory.getInstance().createModifierListFix(lockField, PsiModifier.FINAL, true, false));
}
} else {
problemNewBuilder.addError(String.format("The field %s does not exist.", lockFieldName)); //TODO add QuickFix for creating this field
}
}
}
} else {
problemNewBuilder.addError("'@Synchronized' is legal only on methods.");
}
return result;
}
}
| true | true | public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) {
Collection<LombokProblem> result = new ArrayList<LombokProblem>(2);
final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(result);
PsiMethod psiMethod = PsiTreeUtil.getParentOfType(psiAnnotation, PsiMethod.class);
if (null != psiMethod) {
if (psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
problemNewBuilder.addError("'@Synchronized' is legal only on concrete methods.",
QuickFixFactory.getInstance().createModifierListFix(psiMethod, PsiModifier.ABSTRACT, false, false)
);
}
final String lockFieldName = PsiAnnotationUtil.getAnnotationValue(psiAnnotation, "value", String.class);
if (StringUtil.isNotEmpty(lockFieldName)) {
final PsiClass containingClass = psiMethod.getContainingClass();
if (null != containingClass) {
final PsiField lockField = containingClass.findFieldByName(lockFieldName, true);
if (null != lockField) {
if (lockField.hasModifierProperty(PsiModifier.FINAL)) {
problemNewBuilder.addWarning(String.format("Synchronization on a non-final field %s.", lockFieldName),
QuickFixFactory.getInstance().createModifierListFix(lockField, PsiModifier.FINAL, true, false));
}
} else {
problemNewBuilder.addError(String.format("The field %s does not exist.", lockFieldName)); //TODO add QuickFix for creating this field
}
}
}
} else {
problemNewBuilder.addError("'@Synchronized' is legal only on methods.");
}
return result;
}
| public Collection<LombokProblem> verifyAnnotation(@NotNull PsiAnnotation psiAnnotation) {
Collection<LombokProblem> result = new ArrayList<LombokProblem>(2);
final ProblemNewBuilder problemNewBuilder = new ProblemNewBuilder(result);
PsiMethod psiMethod = PsiTreeUtil.getParentOfType(psiAnnotation, PsiMethod.class);
if (null != psiMethod) {
if (psiMethod.hasModifierProperty(PsiModifier.ABSTRACT)) {
problemNewBuilder.addError("'@Synchronized' is legal only on concrete methods.",
QuickFixFactory.getInstance().createModifierListFix(psiMethod, PsiModifier.ABSTRACT, false, false)
);
}
final String lockFieldName = PsiAnnotationUtil.getAnnotationValue(psiAnnotation, "value", String.class);
if (StringUtil.isNotEmpty(lockFieldName)) {
final PsiClass containingClass = psiMethod.getContainingClass();
if (null != containingClass) {
final PsiField lockField = containingClass.findFieldByName(lockFieldName, true);
if (null != lockField) {
if (!lockField.hasModifierProperty(PsiModifier.FINAL)) {
problemNewBuilder.addWarning(String.format("Synchronization on a non-final field %s.", lockFieldName),
QuickFixFactory.getInstance().createModifierListFix(lockField, PsiModifier.FINAL, true, false));
}
} else {
problemNewBuilder.addError(String.format("The field %s does not exist.", lockFieldName)); //TODO add QuickFix for creating this field
}
}
}
} else {
problemNewBuilder.addError("'@Synchronized' is legal only on methods.");
}
return result;
}
|
diff --git a/freeplane/src/org/freeplane/core/resources/components/ComboProperty.java b/freeplane/src/org/freeplane/core/resources/components/ComboProperty.java
index 46cd87ae8..8a27d4080 100644
--- a/freeplane/src/org/freeplane/core/resources/components/ComboProperty.java
+++ b/freeplane/src/org/freeplane/core/resources/components/ComboProperty.java
@@ -1,139 +1,139 @@
/*
* Freeplane - mind map editor
* Copyright (C) 2008 Joerg Mueller, Daniel Polansky, Christian Foltin, Dimitry Polivaev
*
* This file is modified by Dimitry Polivaev in 2008.
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 2 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
*/
package org.freeplane.core.resources.components;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.util.Arrays;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import javax.swing.DefaultComboBoxModel;
import javax.swing.JComboBox;
import org.freeplane.core.util.LogUtils;
import org.freeplane.core.util.TextUtils;
import com.jgoodies.forms.builder.DefaultFormBuilder;
public class ComboProperty extends PropertyBean implements IPropertyControl, ActionListener {
static public Vector<String> translate(final String[] possibles) {
final Vector<String> possibleTranslations = new Vector<String>(possibles.length);
for (int i = 0; i < possibles.length; i++) {
possibleTranslations.add(TextUtils.getText("OptionPanel." + possibles[i]));
}
return possibleTranslations;
}
final JComboBox mComboBox;
private Vector<String> possibleValues;
public ComboProperty(final String name, final Collection<String> possibles,
final Collection<String> possibleTranslations) {
super(name);
fillPossibleValues(possibles);
mComboBox = new JComboBox();
mComboBox.setModel(new DefaultComboBoxModel(new Vector<String>(possibleTranslations)));
mComboBox.addActionListener(this);
//mComboBox.setRenderer(ComboBoxSmallFontRenderer.INSTANCE);
}
public ComboProperty(final String name, final String[] strings) {
this(name, Arrays.asList(strings), ComboProperty.translate(strings));
}
/**
*/
private void fillPossibleValues(final Collection<String> possibles) {
possibleValues = new Vector<String>();
possibleValues.addAll(possibles);
}
@Override
public String getValue() {
if(mComboBox.getSelectedIndex() == -1)
return mComboBox.getSelectedItem().toString();
return possibleValues.get(mComboBox.getSelectedIndex());
}
public void layout(final DefaultFormBuilder builder) {
layout(builder, mComboBox);
}
public Vector<String> getPossibleValues() {
return possibleValues;
}
public void setEnabled(final boolean pEnabled) {
mComboBox.setEnabled(pEnabled);
}
@Override
public void setValue(final String value) {
if (possibleValues.contains(value)) {
mComboBox.setSelectedIndex(possibleValues.indexOf(value));
}
else if(mComboBox.isEditable()){
mComboBox.setSelectedItem(value);
}
else{
- LogUtils.severe("Can't set the value:" + value + " into the combo box " + getName() + "/" + getLabel());
+ LogUtils.info("Can't set the value:" + value + " into the combo box " + getName() + "/" + getLabel());
if (mComboBox.getModel().getSize() > 0) {
mComboBox.setSelectedIndex(0);
}
}
}
/**
* If your combo base changes, call this method to update the values. The
* old selected value is not selected, but the first in the list. Thus, you
* should call this method only shortly before setting the value with
* setValue.
*/
public void updateComboBoxEntries(final List<String> possibles, final List<String> possibleTranslations) {
mComboBox.setModel(new DefaultComboBoxModel(new Vector<String>(possibleTranslations)));
fillPossibleValues(possibles);
if (possibles.size() > 0) {
mComboBox.setSelectedIndex(0);
}
}
public void actionPerformed(final ActionEvent e) {
firePropertyChangeEvent();
}
@Override
protected Component[] getComponents() {
return mComboBox.getComponents();
}
public void setEditable(boolean aFlag) {
mComboBox.setEditable(aFlag);
}
public boolean isEditable() {
return mComboBox.isEditable();
}
}
| true | true | public void setValue(final String value) {
if (possibleValues.contains(value)) {
mComboBox.setSelectedIndex(possibleValues.indexOf(value));
}
else if(mComboBox.isEditable()){
mComboBox.setSelectedItem(value);
}
else{
LogUtils.severe("Can't set the value:" + value + " into the combo box " + getName() + "/" + getLabel());
if (mComboBox.getModel().getSize() > 0) {
mComboBox.setSelectedIndex(0);
}
}
}
| public void setValue(final String value) {
if (possibleValues.contains(value)) {
mComboBox.setSelectedIndex(possibleValues.indexOf(value));
}
else if(mComboBox.isEditable()){
mComboBox.setSelectedItem(value);
}
else{
LogUtils.info("Can't set the value:" + value + " into the combo box " + getName() + "/" + getLabel());
if (mComboBox.getModel().getSize() > 0) {
mComboBox.setSelectedIndex(0);
}
}
}
|
diff --git a/src/test/java/com/greatmancode/tools/DatabaseTest.java b/src/test/java/com/greatmancode/tools/DatabaseTest.java
index 220fe54..a7e4f6f 100644
--- a/src/test/java/com/greatmancode/tools/DatabaseTest.java
+++ b/src/test/java/com/greatmancode/tools/DatabaseTest.java
@@ -1,51 +1,51 @@
/*
* This file is part of GreatmancodeTools.
*
* Copyright (c) 2013-2013, Greatman <http://github.com/greatman/>
*
* GreatmancodeTools 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.
*
* GreatmancodeTools 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 GreatmancodeTools. If not, see <http://www.gnu.org/licenses/>.
*/
package com.greatmancode.tools;
import java.io.File;
import java.net.URISyntaxException;
import com.alta189.simplesave.exceptions.ConnectionException;
import com.alta189.simplesave.exceptions.TableRegistrationException;
import com.greatmancode.tools.database.DatabaseManager;
import com.greatmancode.tools.database.interfaces.DatabaseType;
import com.greatmancode.tools.database.throwable.InvalidDatabaseConstructor;
import com.greatmancode.tools.tables.TestTable;
import org.junit.Test;
import static junit.framework.Assert.assertEquals;
import static junit.framework.Assert.assertNotNull;
public class DatabaseTest {
@Test
public void test() throws URISyntaxException, InvalidDatabaseConstructor, TableRegistrationException, ConnectionException {
- DatabaseManager dbManager = new DatabaseManager(DatabaseType.SQLite, "test_", new File(new File(ConfigurationTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()), "testConfig.db"));
+ DatabaseManager dbManager = new DatabaseManager(DatabaseType.SQLITE, "test_", new File(new File(ConfigurationTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()), "testConfig.db"));
dbManager.registerTable(TestTable.class);
dbManager.connect();
TestTable table = new TestTable();
table.test = "wow";
dbManager.getDatabase().save(table);
table = dbManager.getDatabase().select(TestTable.class).where().equal("test", "wow").execute().findOne();
assertNotNull(table);
assertEquals("wow", table.test);
}
}
| true | true | public void test() throws URISyntaxException, InvalidDatabaseConstructor, TableRegistrationException, ConnectionException {
DatabaseManager dbManager = new DatabaseManager(DatabaseType.SQLite, "test_", new File(new File(ConfigurationTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()), "testConfig.db"));
dbManager.registerTable(TestTable.class);
dbManager.connect();
TestTable table = new TestTable();
table.test = "wow";
dbManager.getDatabase().save(table);
table = dbManager.getDatabase().select(TestTable.class).where().equal("test", "wow").execute().findOne();
assertNotNull(table);
assertEquals("wow", table.test);
}
| public void test() throws URISyntaxException, InvalidDatabaseConstructor, TableRegistrationException, ConnectionException {
DatabaseManager dbManager = new DatabaseManager(DatabaseType.SQLITE, "test_", new File(new File(ConfigurationTest.class.getProtectionDomain().getCodeSource().getLocation().toURI()), "testConfig.db"));
dbManager.registerTable(TestTable.class);
dbManager.connect();
TestTable table = new TestTable();
table.test = "wow";
dbManager.getDatabase().save(table);
table = dbManager.getDatabase().select(TestTable.class).where().equal("test", "wow").execute().findOne();
assertNotNull(table);
assertEquals("wow", table.test);
}
|
diff --git a/src/org/dita/dost/util/Job.java b/src/org/dita/dost/util/Job.java
index 42d376e5f..ecda9e4c0 100644
--- a/src/org/dita/dost/util/Job.java
+++ b/src/org/dita/dost/util/Job.java
@@ -1,198 +1,198 @@
/*
* This file is part of the DITA Open Toolkit project hosted on
* Sourceforge.net. See the accompanying license.txt file for
* applicable licenses.
*/
/**
* (c) Copyright IBM Corp. 2011 All Rights Reserved.
*/
package org.dita.dost.util;
import static org.dita.dost.util.Constants.*;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import java.util.StringTokenizer;
/**
* Definition of current job.
*
* <p>Instances are thread-safe.</p>
*
* @since 1.5.4
*/
public final class Job {
private final Properties prop;
private final File tempDir;
/**
* Create new job configuration instance. Initialise by reading temporary configuration files.
*
* @param tempDir temporary directory
* @throws IOException if reading configuration files failed
* @throws IllegalStateException if configuration files are missing
*/
public Job(final File tempDir) throws IOException {
this.tempDir = tempDir;
prop = new Properties();
read();
}
/**
* Read temporary configuration files.
*
* @throws IOException if reading configuration files failed
* @throws IllegalStateException if configuration files are missing
*/
private void read() throws IOException {
final File ditalist = new File(tempDir, FILE_NAME_DITA_LIST);
final File xmlDitalist=new File(tempDir, FILE_NAME_DITA_LIST_XML);
InputStream in = null;
try{
if(xmlDitalist.exists()) {
in = new FileInputStream(xmlDitalist);
prop.loadFromXML(in);
} else if(ditalist.exists()) {
in = new FileInputStream(ditalist);
prop.load(in);
} else {
throw new IllegalStateException("Job configuration files not found");
}
} catch(final IOException e) {
throw new IOException("Failed to read file: " + e.getMessage());
} finally {
if (in != null) {
try {
in.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
}
/**
* Store job into temporary configuration files.
*
* @throws IOException if writing configuration files failed
*/
public void write() throws IOException {
FileOutputStream propertiesOutputStream = null;
try {
propertiesOutputStream = new FileOutputStream(new File(tempDir, FILE_NAME_DITA_LIST));
prop.store(propertiesOutputStream, null);
propertiesOutputStream.flush();
} catch (final IOException e) {
throw new IOException("Failed to write file: " + e.getMessage());
} finally {
if (propertiesOutputStream != null) {
try {
propertiesOutputStream.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
FileOutputStream xmlOutputStream = null;
try {
xmlOutputStream = new FileOutputStream(new File(tempDir, FILE_NAME_DITA_LIST_XML));
prop.storeToXML(xmlOutputStream, null);
xmlOutputStream.flush();
} catch (final IOException e) {
- throw new IOException("Failed to write file: " + e.getMessage(), e);
+ throw new IOException("Failed to write file: " + e.getMessage());
} finally {
if (xmlOutputStream != null) {
try {
xmlOutputStream.close();
} catch (final IOException e) {
- throw new IOException("Failed to close file: " + e.getMessage(), e);
+ throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
}
/**
* Searches for the property with the specified key in this property list.
*
* @param key property key
* @return the value in this property list with the specified key value, {@code null} if not found
*/
public String getProperty(final String key) {
return prop.getProperty(key);
}
/**
* Set property value.
*
* @param key property key
* @param value property value
* @return the previous value of the specified key in this property list, or {@code null} if it did not have one
*/
public String setProperty(final String key, final String value) {
return (String) prop.setProperty(key, value);
}
/**
* Return the copy-to map.
* @return copy-to map
*/
public Map<String, String> getCopytoMap() {
return StringUtils.restoreMap(prop.getProperty(COPYTO_TARGET_TO_SOURCE_MAP_LIST, ""));
}
/**
* @return the schemeSet
*/
public Set<String> getSchemeSet() {
return StringUtils.restoreSet(prop.getProperty(SUBJEC_SCHEME_LIST, ""));
}
/**
* @return the inputMap
*/
public String getInputMap() {
return prop.getProperty(INPUT_DITAMAP);
}
/**
* Get reference list.
*
* <p>TODO: rename to getReferenceList</p>
*
* @return reference list
*/
public LinkedList<String> getCollection() {
final LinkedList<String> refList = new LinkedList<String>();
final String liststr = prop.getProperty(FULL_DITAMAP_TOPIC_LIST, "")
+ COMMA
+ prop.getProperty(CONREF_TARGET_LIST, "")
+ COMMA
+ prop.getProperty(COPYTO_SOURCE_LIST, "");
final StringTokenizer tokenizer = new StringTokenizer(liststr, COMMA);
while (tokenizer.hasMoreTokens()) {
refList.addFirst(tokenizer.nextToken());
}
return refList;
}
/**
* Get input directory.
*
* <p>TODO: rename to getInputDir</p>
*
* @return input directory
*/
public String getValue() {
return prop.getProperty("user.input.dir");
}
}
| false | true | public void write() throws IOException {
FileOutputStream propertiesOutputStream = null;
try {
propertiesOutputStream = new FileOutputStream(new File(tempDir, FILE_NAME_DITA_LIST));
prop.store(propertiesOutputStream, null);
propertiesOutputStream.flush();
} catch (final IOException e) {
throw new IOException("Failed to write file: " + e.getMessage());
} finally {
if (propertiesOutputStream != null) {
try {
propertiesOutputStream.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
FileOutputStream xmlOutputStream = null;
try {
xmlOutputStream = new FileOutputStream(new File(tempDir, FILE_NAME_DITA_LIST_XML));
prop.storeToXML(xmlOutputStream, null);
xmlOutputStream.flush();
} catch (final IOException e) {
throw new IOException("Failed to write file: " + e.getMessage(), e);
} finally {
if (xmlOutputStream != null) {
try {
xmlOutputStream.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage(), e);
}
}
}
}
| public void write() throws IOException {
FileOutputStream propertiesOutputStream = null;
try {
propertiesOutputStream = new FileOutputStream(new File(tempDir, FILE_NAME_DITA_LIST));
prop.store(propertiesOutputStream, null);
propertiesOutputStream.flush();
} catch (final IOException e) {
throw new IOException("Failed to write file: " + e.getMessage());
} finally {
if (propertiesOutputStream != null) {
try {
propertiesOutputStream.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
FileOutputStream xmlOutputStream = null;
try {
xmlOutputStream = new FileOutputStream(new File(tempDir, FILE_NAME_DITA_LIST_XML));
prop.storeToXML(xmlOutputStream, null);
xmlOutputStream.flush();
} catch (final IOException e) {
throw new IOException("Failed to write file: " + e.getMessage());
} finally {
if (xmlOutputStream != null) {
try {
xmlOutputStream.close();
} catch (final IOException e) {
throw new IOException("Failed to close file: " + e.getMessage());
}
}
}
}
|
diff --git a/src/simpleserver/command/GameModeCommand.java b/src/simpleserver/command/GameModeCommand.java
index fe1e765..f785baf 100644
--- a/src/simpleserver/command/GameModeCommand.java
+++ b/src/simpleserver/command/GameModeCommand.java
@@ -1,59 +1,64 @@
/*
* Copyright (c) 2010 SimpleServer authors (see CONTRIBUTORS)
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
* THE SOFTWARE.
*/
package simpleserver.command;
import simpleserver.Color;
import simpleserver.Player;
public class GameModeCommand extends AbstractCommand implements PlayerCommand {
public GameModeCommand() {
super("gamemode [PLAYER] MODE", "set gameMode for a specific player.");
}
public void execute(Player player, String message) {
String[] args = extractArguments(message);
Player target;
Integer gameMode;
- if (args.length == 1) {
- target = player;
- gameMode = Integer.parseInt(args[0]);
- } else if (args.length == 2) {
- target = player.getServer().findPlayer(args[0]);
- if (target == null) {
- player.addTMessage(Color.RED, "Player not online (%s)", args[1]);
+ try {
+ if (args.length == 1) {
+ target = player;
+ gameMode = Integer.parseInt(args[0]);
+ } else if (args.length == 2) {
+ target = player.getServer().findPlayer(args[0]);
+ if (target == null) {
+ player.addTMessage(Color.RED, "Player not online (%s)", args[1]);
+ return;
+ }
+ gameMode = Integer.parseInt(args[1]);
+ } else {
+ player.addTMessage(Color.RED, "Invalid number of arguments!");
return;
}
- gameMode = Integer.parseInt(args[1]);
- } else {
- player.addTMessage(Color.RED, "Invalid number of arguments!");
+ } catch (NumberFormatException e) {
+ player.addTMessage(Color.RED, "Invalid gameMode %s!", args[0]);
return;
}
if (gameMode != 0 && gameMode != 1) {
- player.addTMessage(Color.RED, "Invalid gameMode!");
+ player.addTMessage(Color.RED, "Invalid gameMode %d!", gameMode);
return;
}
player.getServer().runCommand("gamemode", target.getName() + " " + gameMode);
}
}
| false | true | public void execute(Player player, String message) {
String[] args = extractArguments(message);
Player target;
Integer gameMode;
if (args.length == 1) {
target = player;
gameMode = Integer.parseInt(args[0]);
} else if (args.length == 2) {
target = player.getServer().findPlayer(args[0]);
if (target == null) {
player.addTMessage(Color.RED, "Player not online (%s)", args[1]);
return;
}
gameMode = Integer.parseInt(args[1]);
} else {
player.addTMessage(Color.RED, "Invalid number of arguments!");
return;
}
if (gameMode != 0 && gameMode != 1) {
player.addTMessage(Color.RED, "Invalid gameMode!");
return;
}
player.getServer().runCommand("gamemode", target.getName() + " " + gameMode);
}
| public void execute(Player player, String message) {
String[] args = extractArguments(message);
Player target;
Integer gameMode;
try {
if (args.length == 1) {
target = player;
gameMode = Integer.parseInt(args[0]);
} else if (args.length == 2) {
target = player.getServer().findPlayer(args[0]);
if (target == null) {
player.addTMessage(Color.RED, "Player not online (%s)", args[1]);
return;
}
gameMode = Integer.parseInt(args[1]);
} else {
player.addTMessage(Color.RED, "Invalid number of arguments!");
return;
}
} catch (NumberFormatException e) {
player.addTMessage(Color.RED, "Invalid gameMode %s!", args[0]);
return;
}
if (gameMode != 0 && gameMode != 1) {
player.addTMessage(Color.RED, "Invalid gameMode %d!", gameMode);
return;
}
player.getServer().runCommand("gamemode", target.getName() + " " + gameMode);
}
|
diff --git a/src/java/se/idega/idegaweb/commune/accounting/presentation/AccountingBlock.java b/src/java/se/idega/idegaweb/commune/accounting/presentation/AccountingBlock.java
index 0f315441..90166787 100644
--- a/src/java/se/idega/idegaweb/commune/accounting/presentation/AccountingBlock.java
+++ b/src/java/se/idega/idegaweb/commune/accounting/presentation/AccountingBlock.java
@@ -1,461 +1,462 @@
/*
* Created on Aug 18, 2003
*
*/
package se.idega.idegaweb.commune.accounting.presentation;
import java.rmi.RemoteException;
import java.sql.Date;
import java.sql.Timestamp;
import java.text.DateFormat;
import java.text.NumberFormat;
import java.text.ParsePosition;
import java.text.SimpleDateFormat;
import java.util.Collection;
import java.util.Locale;
import se.idega.idegaweb.commune.accounting.business.AccountingBusiness;
import se.idega.idegaweb.commune.accounting.business.AccountingSession;
import se.idega.idegaweb.commune.presentation.CommuneBlock;
import com.idega.business.IBOLookup;
import com.idega.business.IBORuntimeException;
import com.idega.idegaweb.IWApplicationContext;
import com.idega.idegaweb.IWUserContext;
import com.idega.presentation.IWContext;
import com.idega.presentation.text.Link;
import com.idega.presentation.text.Text;
import com.idega.presentation.ui.CheckBox;
import com.idega.presentation.ui.DropdownMenu;
import com.idega.presentation.ui.SubmitButton;
import com.idega.presentation.ui.TextInput;
import com.idega.presentation.ui.util.SelectorUtility;
/**
* AccountingBlock a super class of all blocks in the accounting framework
* @author aron
* @version 1.0
*/
public abstract class AccountingBlock extends CommuneBlock {
public final static String IW_ACCOUNTING_BUNDLE_IDENTIFER = "se.idega.idegaweb.commune.accounting";
private AccountingBusiness business;
private AccountingSession session;
public void _main(IWContext iwc) throws Exception{
setResourceBundle(getResourceBundle(iwc));
business = getAccountingBusiness(iwc);
session = getAccountingSession(iwc);
super._main(iwc);
}
public void main(IWContext iwc) throws Exception{
init(iwc);
}
/**
* This method can be overridden instead of the main method from Block.
* @param iwc
* @throws Exception
*/
public abstract void init(IWContext iwc) throws Exception;
/* (non-Javadoc)
* @see com.idega.presentation.PresentationObject#getBundleIdentifier()
*/
public String getBundleIdentifier() {
return IW_ACCOUNTING_BUNDLE_IDENTIFER;
}
/**
* @return AccountingBusiness
*/
public AccountingBusiness getBusiness() {
return business;
}
/**
* @return AccountingSession
*/
public AccountingSession getSession() {
return session;
}
/**
* Gets the common number format for the current locale
*/
public NumberFormat getNumberFormat(Locale locale){
return NumberFormat.getInstance(locale);
}
/**
* Gets the common short date format for the given locale
*/
public DateFormat getShortDateFormat(Locale locale){
return DateFormat.getDateInstance(DateFormat.SHORT,locale);
}
/**
* Gets the common long date format for the given locale
*/
public DateFormat getLongDateFormat(Locale locale){
return DateFormat.getDateInstance(DateFormat.LONG,locale);
}
/**
* Gets the common date-time-format for the given locale
*/
public DateFormat getDateTimeFormat(Locale locale){
return DateFormat.getDateTimeInstance(DateFormat.SHORT,DateFormat.SHORT,locale);
}
/**
* Returns a formatted and localized form label.
* @param textKey the text key to localize
* @param defaultText the default localized text
* @author anders
*/
protected Text getLocalizedLabel(String textKey, String defaultText) {
return getSmallHeader(localize(textKey, defaultText) + ":");
}
/**
* Returns a formatted and localized form text.
* @param textKey the text key to localize
* @param defaultText the default localized text
* @author anders
*/
public Text getLocalizedText(String textKey, String defaultText) {
return getSmallText(localize(textKey, defaultText));
}
/**
* Returns a formatted and form text.
* @param text the text string for the Text object
* @author anders
*/
public Text getText(String text) {
return getSmallText(text);
}
/**
* Returns a formatted text input.
* @param parameter the form parameter
* @param text the text to set
* @author anders
*/
protected TextInput getTextInput(String parameter, String text) {
return (TextInput) getStyledInterface(new TextInput(parameter, text));
}
/**
* Returns a formatted text input with the specified width.
* @param parameter the form parameter
* @param text the text to set
* @param width the width of the text input
* @author anders
*/
protected TextInput getTextInput(String parameter, String text, int width) {
TextInput ti = getTextInput(parameter, ""+text);
ti.setWidth("" + width);
return ti;
}
/**
* Returns a formatted text input with the specified width and size.
* @param parameter the form parameter
* @param text the text to set
* @param width the width of the text input
* @param size the number of character in the text input
* @author anders
*/
protected TextInput getTextInput(String parameter, String text, int width, int size) {
TextInput ti = getTextInput(parameter, text, width);
ti.setSize(width);
ti.setMaxlength(size);
return ti;
}
/**
* Returns a formatted link.
* @param text the link text
* @param parameter the form parameter
* @param value the parameter value
* @author anders
*/
protected Link getLink(String text, String parameter, String value) {
Link l = getSmallLink(text);
l.addParameter(parameter, value);
return l;
}
/**
* Returns a formatted and localized button.
* @param parameter the form parameter
* @param textKey the text key to localize
* @param defaultText the default localized text
* @author anders
*/
protected SubmitButton getLocalizedButton(String parameter, String textKey, String defaultText) {
return getSubmitButton(new SubmitButton(parameter, localize(textKey, defaultText)));
}
/**
* Sets the style for the specified button.
* @param button the submit button to stylize
* @author anders
*/
protected SubmitButton getSubmitButton(SubmitButton button) {
button.setHeight("20");
return (SubmitButton) setStyle(button,STYLENAME_INTERFACE_BUTTON);
}
/**
* Parses the specified string to a java.sql.Date object.
* The date formats yyMM, yyMMdd, yyyyMMdd, yy-MM-dd, yyyy-MM-dd are accepted.
* @param dateString the date string to parse
* @author anders
*/
protected Date parseDate(String dateString) {
if (dateString == null) {
return null;
}
SimpleDateFormat formatter = null;
ParsePosition pos = null;
java.util.Date d = null;
String s = dateString.trim();
Date date = null;
if ((d == null) && (s.length() == 4)) {
- pos = new ParsePosition(0);
- formatter = new SimpleDateFormat ("yyMM");
- d = formatter.parse(s, pos);
+ s = "20" + s;
+// pos = new ParsePosition(0);
+// formatter = new SimpleDateFormat ("yyMM");
+// d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 6)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyMMdd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 8) && (s.indexOf('-') == -1)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyyyMMdd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 8)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yy-MM-dd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 10)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyyy-MM-dd");
d = formatter.parse(s, pos);
}
if (d != null) {
date = validateDate(d, s);
}
return date;
}
/**
* Formats the specified java.sql.Date object into a string.
* The length can be 4, 6, 8 or 10 characters resulting in the
* formats yyMM, yyMMdd, yyyyMMdd, yyyy-MM-dd.
* @param date the date object to format
* @param length the length of the formatted date
* @return the formatted string
* @author anders
*/
protected String formatDate(Date date, int length) {
if (date == null) {
return "";
}
SimpleDateFormat formatter = null;
if (length == 4) {
formatter = new SimpleDateFormat ("yyMM");
} else if (length == 6) {
formatter = new SimpleDateFormat ("yyMMdd");
} else if (length == 8) {
formatter = new SimpleDateFormat ("yyyyMMdd");
} else if (length == 10) {
formatter = new SimpleDateFormat ("yyyy-MM-dd");
}
String dateString = "";
if (formatter != null) {
java.util.Date d = new java.util.Date(date.getTime());
dateString = formatter.format(d);
}
return dateString;
}
/*
* Returns a java.sqlDate object if s has valid date format.
*/
private Date validateDate(java.util.Date d, String s) {
Date date = null;
if (d != null) {
date = new Date(d.getTime());
String validate = null;
if ((s.length() == 8) && (s.indexOf('-') != -1)) {
SimpleDateFormat formatter = new SimpleDateFormat ("yy-MM-dd");
validate = formatter.format(d);
} else {
validate = formatDate(date, s.length());
}
if (!validate.equals(s)) {
date = null;
}
}
return date;
}
/**
* Formats the specified java.sql.Timestamp object into a string.
* The length can be 4, 6, 8 or 10 characters resulting in the
* formats yyMM, yyMMdd, yyyyMMdd, yyyy-MM-dd.
* @param timestamp the timestamp object to format
* @param length the length of the formatted date
* @return the formatted string
* @author anders
*/
protected String formatDate(Timestamp timestamp, int length) {
return formatDate(new Date(timestamp.getTime()), length);
}
/**
* Returns the form parameter with the specified parameter name
* from the specified IWContext object. Returns an empty string
* if the parameter is not set instead of null.
* @param iwc the idegaWeb context object
* @param parameterName the name of the form parameter
* @author anders
*/
protected String getParameter(IWContext iwc, String parameterName) {
String p = iwc.getParameter(parameterName);
if (p == null) {
p = "";
}
return p;
}
/**
* Returns the form parameter with the specified parameter name
* from the specified IWContext object as an integer. Returns -1 if
* the parameter is not set.
* @param iwc the idegaWeb context object
* @param parameterName the name of the form parameter
* @author anders
*/
protected int getIntParameter(IWContext iwc, String parameterName) {
int intValue = 0;
String s = getParameter(iwc, parameterName);
try {
intValue = Integer.parseInt(s);
} catch (NumberFormatException e) {
intValue = -1;
}
return intValue;
}
/**
* Returns a <code>DropdownMenu</code> that uses the given <code>Collection</code> of entities as options.
* @param name The form name for the returned <code>DropdownMenu</code>
* @param entities The entity beans to use as values.
* @param methodName The name of the method from which the values are retrieved.
* @param defaultValue The default value to set if method returns null
* @return
*/
protected DropdownMenu getDropdownMenu(String name, Collection entities, String methodName) {
SelectorUtility util = new SelectorUtility();
DropdownMenu menu = (DropdownMenu) util.getSelectorFromIDOEntities(new DropdownMenu(name), entities, methodName);
return menu;
}
/**
* Returns a <code>DropdownMenu</code> that uses the given <code>Collection</code> of entities as options where the
* value is a localization key.
* @param name The form name for the returned <code>DropdownMenu</code>
* @param entities The entity beans to use as values.
* @param methodName The name of the method from which the values are retrieved.
* @return
*/
protected DropdownMenu getDropdownMenuLocalized(String name, Collection entities, String methodName) {
return getDropdownMenuLocalized(name, entities, methodName, null);
}
/**
* Returns a <code>DropdownMenu</code> that uses the given <code>Collection</code> of entities as options where the
* value is a localization key.
* @param name The form name for the returned <code>DropdownMenu</code>
* @param entities The entity beans to use as values.
* @param methodName The name of the method from which the values are retrieved.
* @param defaultValue The default value to set if method returns null
* @return
*/
protected DropdownMenu getDropdownMenuLocalized(String name, Collection entities, String methodName, String defaultValue) {
SelectorUtility util = new SelectorUtility();
DropdownMenu menu = (DropdownMenu) util.getSelectorFromIDOEntities(new DropdownMenu(name), entities, methodName, getResourceBundle(), defaultValue);
return menu;
}
/**
* Returns a formatted check box.
* @param parameter the form parameter
* @param value the value to set
* @author aron
*/
protected CheckBox getCheckBox(String parameter, String value) {
return (CheckBox) getStyledInterface(new CheckBox(parameter, value));
}
protected boolean isOperationalFieldChildcareSelected(IWContext iwc){
iwc.toString(); // Added to remove compiler warning
//TODO: Implement
return true;
}
protected boolean isOperationalFieldElementarySchoolSelected(IWContext iwc){
iwc.toString(); // Added to remove compiler warning
//TODO: Implement
return false;
}
protected boolean isOperationalFieldHighSchoolSelected(IWContext iwc){
iwc.toString(); // Added to remove compiler warning
//TODO: Implement
return false;
}
protected AccountingBusiness getAccountingBusiness(IWApplicationContext iwac) {
try {
return (AccountingBusiness) IBOLookup.getServiceInstance(iwac, AccountingBusiness.class);
}
catch (RemoteException e) {
throw new IBORuntimeException(e.getMessage());
}
}
protected AccountingSession getAccountingSession(IWUserContext iwuc) {
try {
return (AccountingSession) IBOLookup.getSessionInstance(iwuc, AccountingSession.class);
}
catch (RemoteException e) {
throw new IBORuntimeException(e.getMessage());
}
}
}
| true | true | protected Date parseDate(String dateString) {
if (dateString == null) {
return null;
}
SimpleDateFormat formatter = null;
ParsePosition pos = null;
java.util.Date d = null;
String s = dateString.trim();
Date date = null;
if ((d == null) && (s.length() == 4)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyMM");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 6)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyMMdd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 8) && (s.indexOf('-') == -1)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyyyMMdd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 8)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yy-MM-dd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 10)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyyy-MM-dd");
d = formatter.parse(s, pos);
}
if (d != null) {
date = validateDate(d, s);
}
return date;
}
| protected Date parseDate(String dateString) {
if (dateString == null) {
return null;
}
SimpleDateFormat formatter = null;
ParsePosition pos = null;
java.util.Date d = null;
String s = dateString.trim();
Date date = null;
if ((d == null) && (s.length() == 4)) {
s = "20" + s;
// pos = new ParsePosition(0);
// formatter = new SimpleDateFormat ("yyMM");
// d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 6)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyMMdd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 8) && (s.indexOf('-') == -1)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyyyMMdd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 8)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yy-MM-dd");
d = formatter.parse(s, pos);
}
if ((d == null) && (s.length() == 10)) {
pos = new ParsePosition(0);
formatter = new SimpleDateFormat ("yyyy-MM-dd");
d = formatter.parse(s, pos);
}
if (d != null) {
date = validateDate(d, s);
}
return date;
}
|
diff --git a/WordWrap/src/com/WordWrap/WordWrapTests.java b/WordWrap/src/com/WordWrap/WordWrapTests.java
index f145301..fb072ee 100644
--- a/WordWrap/src/com/WordWrap/WordWrapTests.java
+++ b/WordWrap/src/com/WordWrap/WordWrapTests.java
@@ -1,14 +1,14 @@
package com.WordWrap;
import static org.junit.Assert.*;
import org.junit.Test;
public class WordWrapTests {
@Test
public void Test(){
- assertTrue(false);
+ assertTrue(true);
}
}
| true | true | public void Test(){
assertTrue(false);
}
| public void Test(){
assertTrue(true);
}
|
diff --git a/src/com/android/mms/transaction/SmsSingleRecipientSender.java b/src/com/android/mms/transaction/SmsSingleRecipientSender.java
index 42d8ad6b..40866d8a 100644
--- a/src/com/android/mms/transaction/SmsSingleRecipientSender.java
+++ b/src/com/android/mms/transaction/SmsSingleRecipientSender.java
@@ -1,128 +1,130 @@
package com.android.mms.transaction;
import java.util.ArrayList;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.net.Uri;
import android.provider.Telephony.Mms;
import android.telephony.SmsManager;
import android.util.Log;
import com.android.mms.LogTag;
import com.android.mms.MmsConfig;
import com.google.android.mms.MmsException;
import android.provider.Telephony.Sms;
import com.android.mms.data.Conversation;
import com.android.mms.ui.MessageUtils;
public class SmsSingleRecipientSender extends SmsMessageSender {
private final boolean mRequestDeliveryReport;
private String mDest;
private Uri mUri;
private static final String TAG = "SmsSingleRecipientSender";
public SmsSingleRecipientSender(Context context, String dest, String msgText, long threadId,
boolean requestDeliveryReport, Uri uri) {
super(context, null, msgText, threadId);
mRequestDeliveryReport = requestDeliveryReport;
mDest = dest;
mUri = uri;
}
public boolean sendMessage(long token) throws MmsException {
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage token: " + token);
}
if (mMessageText == null) {
// Don't try to send an empty message, and destination should be just
// one.
throw new MmsException("Null message body or have multiple destinations.");
}
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> messages = null;
if ((MmsConfig.getEmailGateway() != null) &&
(Mms.isEmailAddress(mDest) || MessageUtils.isAlias(mDest))) {
String msgText;
msgText = mDest + " " + mMessageText;
mDest = MmsConfig.getEmailGateway();
messages = smsManager.divideMessage(msgText);
} else {
messages = smsManager.divideMessage(mMessageText);
// remove spaces from destination number (e.g. "801 555 1212" -> "8015551212")
mDest = mDest.replaceAll(" ", "");
mDest = Conversation.verifySingleRecipient(mContext, mThreadId, mDest);
}
int messageCount = messages.size();
if (messageCount == 0) {
// Don't try to send an empty message.
throw new MmsException("SmsMessageSender.sendMessage: divideMessage returned " +
"empty messages. Original message is \"" + mMessageText + "\"");
}
boolean moved = Sms.moveMessageToFolder(mContext, mUri, Sms.MESSAGE_TYPE_OUTBOX, 0);
if (!moved) {
throw new MmsException("SmsMessageSender.sendMessage: couldn't move message " +
"to outbox: " + mUri);
}
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage mDest: " + mDest + " mRequestDeliveryReport: " +
mRequestDeliveryReport);
}
ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(messageCount);
ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount);
for (int i = 0; i < messageCount; i++) {
- if (mRequestDeliveryReport) {
+ if (mRequestDeliveryReport && (i == (messageCount - 1))) {
// TODO: Fix: It should not be necessary to
// specify the class in this intent. Doing that
// unnecessarily limits customizability.
deliveryIntents.add(PendingIntent.getBroadcast(
mContext, 0,
new Intent(
MessageStatusReceiver.MESSAGE_STATUS_RECEIVED_ACTION,
mUri,
mContext,
MessageStatusReceiver.class),
- 0));
+ 0));
+ } else {
+ deliveryIntents.add(null);
}
Intent intent = new Intent(SmsReceiverService.MESSAGE_SENT_ACTION,
mUri,
mContext,
SmsReceiver.class);
int requestCode = 0;
if (i == messageCount -1) {
// Changing the requestCode so that a different pending intent
// is created for the last fragment with
// EXTRA_MESSAGE_SENT_SEND_NEXT set to true.
requestCode = 1;
intent.putExtra(SmsReceiverService.EXTRA_MESSAGE_SENT_SEND_NEXT, true);
}
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage sendIntent: " + intent);
}
sentIntents.add(PendingIntent.getBroadcast(mContext, requestCode, intent, 0));
}
try {
smsManager.sendMultipartTextMessage(mDest, mServiceCenter, messages, sentIntents, deliveryIntents);
} catch (Exception ex) {
Log.e(TAG, "SmsMessageSender.sendMessage: caught", ex);
throw new MmsException("SmsMessageSender.sendMessage: caught " + ex +
" from SmsManager.sendTextMessage()");
}
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
log("sendMessage: address=" + mDest + ", threadId=" + mThreadId +
", uri=" + mUri + ", msgs.count=" + messageCount);
}
return false;
}
private void log(String msg) {
Log.d(LogTag.TAG, "[SmsSingleRecipientSender] " + msg);
}
}
| false | true | public boolean sendMessage(long token) throws MmsException {
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage token: " + token);
}
if (mMessageText == null) {
// Don't try to send an empty message, and destination should be just
// one.
throw new MmsException("Null message body or have multiple destinations.");
}
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> messages = null;
if ((MmsConfig.getEmailGateway() != null) &&
(Mms.isEmailAddress(mDest) || MessageUtils.isAlias(mDest))) {
String msgText;
msgText = mDest + " " + mMessageText;
mDest = MmsConfig.getEmailGateway();
messages = smsManager.divideMessage(msgText);
} else {
messages = smsManager.divideMessage(mMessageText);
// remove spaces from destination number (e.g. "801 555 1212" -> "8015551212")
mDest = mDest.replaceAll(" ", "");
mDest = Conversation.verifySingleRecipient(mContext, mThreadId, mDest);
}
int messageCount = messages.size();
if (messageCount == 0) {
// Don't try to send an empty message.
throw new MmsException("SmsMessageSender.sendMessage: divideMessage returned " +
"empty messages. Original message is \"" + mMessageText + "\"");
}
boolean moved = Sms.moveMessageToFolder(mContext, mUri, Sms.MESSAGE_TYPE_OUTBOX, 0);
if (!moved) {
throw new MmsException("SmsMessageSender.sendMessage: couldn't move message " +
"to outbox: " + mUri);
}
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage mDest: " + mDest + " mRequestDeliveryReport: " +
mRequestDeliveryReport);
}
ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(messageCount);
ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount);
for (int i = 0; i < messageCount; i++) {
if (mRequestDeliveryReport) {
// TODO: Fix: It should not be necessary to
// specify the class in this intent. Doing that
// unnecessarily limits customizability.
deliveryIntents.add(PendingIntent.getBroadcast(
mContext, 0,
new Intent(
MessageStatusReceiver.MESSAGE_STATUS_RECEIVED_ACTION,
mUri,
mContext,
MessageStatusReceiver.class),
0));
}
Intent intent = new Intent(SmsReceiverService.MESSAGE_SENT_ACTION,
mUri,
mContext,
SmsReceiver.class);
int requestCode = 0;
if (i == messageCount -1) {
// Changing the requestCode so that a different pending intent
// is created for the last fragment with
// EXTRA_MESSAGE_SENT_SEND_NEXT set to true.
requestCode = 1;
intent.putExtra(SmsReceiverService.EXTRA_MESSAGE_SENT_SEND_NEXT, true);
}
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage sendIntent: " + intent);
}
sentIntents.add(PendingIntent.getBroadcast(mContext, requestCode, intent, 0));
}
try {
smsManager.sendMultipartTextMessage(mDest, mServiceCenter, messages, sentIntents, deliveryIntents);
} catch (Exception ex) {
Log.e(TAG, "SmsMessageSender.sendMessage: caught", ex);
throw new MmsException("SmsMessageSender.sendMessage: caught " + ex +
" from SmsManager.sendTextMessage()");
}
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
log("sendMessage: address=" + mDest + ", threadId=" + mThreadId +
", uri=" + mUri + ", msgs.count=" + messageCount);
}
return false;
}
| public boolean sendMessage(long token) throws MmsException {
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage token: " + token);
}
if (mMessageText == null) {
// Don't try to send an empty message, and destination should be just
// one.
throw new MmsException("Null message body or have multiple destinations.");
}
SmsManager smsManager = SmsManager.getDefault();
ArrayList<String> messages = null;
if ((MmsConfig.getEmailGateway() != null) &&
(Mms.isEmailAddress(mDest) || MessageUtils.isAlias(mDest))) {
String msgText;
msgText = mDest + " " + mMessageText;
mDest = MmsConfig.getEmailGateway();
messages = smsManager.divideMessage(msgText);
} else {
messages = smsManager.divideMessage(mMessageText);
// remove spaces from destination number (e.g. "801 555 1212" -> "8015551212")
mDest = mDest.replaceAll(" ", "");
mDest = Conversation.verifySingleRecipient(mContext, mThreadId, mDest);
}
int messageCount = messages.size();
if (messageCount == 0) {
// Don't try to send an empty message.
throw new MmsException("SmsMessageSender.sendMessage: divideMessage returned " +
"empty messages. Original message is \"" + mMessageText + "\"");
}
boolean moved = Sms.moveMessageToFolder(mContext, mUri, Sms.MESSAGE_TYPE_OUTBOX, 0);
if (!moved) {
throw new MmsException("SmsMessageSender.sendMessage: couldn't move message " +
"to outbox: " + mUri);
}
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage mDest: " + mDest + " mRequestDeliveryReport: " +
mRequestDeliveryReport);
}
ArrayList<PendingIntent> deliveryIntents = new ArrayList<PendingIntent>(messageCount);
ArrayList<PendingIntent> sentIntents = new ArrayList<PendingIntent>(messageCount);
for (int i = 0; i < messageCount; i++) {
if (mRequestDeliveryReport && (i == (messageCount - 1))) {
// TODO: Fix: It should not be necessary to
// specify the class in this intent. Doing that
// unnecessarily limits customizability.
deliveryIntents.add(PendingIntent.getBroadcast(
mContext, 0,
new Intent(
MessageStatusReceiver.MESSAGE_STATUS_RECEIVED_ACTION,
mUri,
mContext,
MessageStatusReceiver.class),
0));
} else {
deliveryIntents.add(null);
}
Intent intent = new Intent(SmsReceiverService.MESSAGE_SENT_ACTION,
mUri,
mContext,
SmsReceiver.class);
int requestCode = 0;
if (i == messageCount -1) {
// Changing the requestCode so that a different pending intent
// is created for the last fragment with
// EXTRA_MESSAGE_SENT_SEND_NEXT set to true.
requestCode = 1;
intent.putExtra(SmsReceiverService.EXTRA_MESSAGE_SENT_SEND_NEXT, true);
}
if (LogTag.DEBUG_SEND) {
Log.v(TAG, "sendMessage sendIntent: " + intent);
}
sentIntents.add(PendingIntent.getBroadcast(mContext, requestCode, intent, 0));
}
try {
smsManager.sendMultipartTextMessage(mDest, mServiceCenter, messages, sentIntents, deliveryIntents);
} catch (Exception ex) {
Log.e(TAG, "SmsMessageSender.sendMessage: caught", ex);
throw new MmsException("SmsMessageSender.sendMessage: caught " + ex +
" from SmsManager.sendTextMessage()");
}
if (Log.isLoggable(LogTag.TRANSACTION, Log.VERBOSE) || LogTag.DEBUG_SEND) {
log("sendMessage: address=" + mDest + ", threadId=" + mThreadId +
", uri=" + mUri + ", msgs.count=" + messageCount);
}
return false;
}
|
diff --git a/kai2/src/edu/hawaii/ihale/housesimulator/aquaponics/AquaponicsData.java b/kai2/src/edu/hawaii/ihale/housesimulator/aquaponics/AquaponicsData.java
index e3454db..16b1157 100644
--- a/kai2/src/edu/hawaii/ihale/housesimulator/aquaponics/AquaponicsData.java
+++ b/kai2/src/edu/hawaii/ihale/housesimulator/aquaponics/AquaponicsData.java
@@ -1,432 +1,432 @@
package edu.hawaii.ihale.housesimulator.aquaponics;
import java.text.DecimalFormat;
import java.util.Date;
import java.util.Random;
import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import org.restlet.ext.xml.DomRepresentation;
import org.w3c.dom.Document;
import org.w3c.dom.Element;
/**
* Provides data on the Aquaponics system, as well as an XML representation.
*
* @author Anthony Kinsey, Michael Cera
* @author Christopher Ramelb, David Lin, Leonardo Nguyen, Nathan Dorman
*/
public class AquaponicsData {
// /** Test number generation here. */
// public static void main(String[] args) {
// for (int i = 0; i < 10; i++) {
// System.out.println((randomGen.nextInt(2) * randomGen.nextInt(2)
// * randomGen.nextInt(2))
// - (randomGen.nextInt(2) * randomGen.nextInt(2) *
// randomGen.nextInt(2)));
// }
// }
/** Random generator. */
private static final Random randomGen = new Random();
// Necessary conditions for fish to live.
/** Number of fish alive in tank. */
private static int alive_fish = 100;
/** Minimum electrical conductivity for fish. */
private static double minEC = 1.0;
/** Maximum electrical conductivity for fish. */
private static double maxEC = 2.0;
/** Minimum temperature for fish. */
private static int minTemp = 20;
/** Maximum temperature for fish. */
private static int maxTemp = 45;
/** Minimum water level for fish. */
private static int minWaterLevel = alive_fish;
/** Minimum water PH for fish. */
private static double minPH = 6.8;
/** Maximum water PH for fish. */
private static double maxPH = 8.0;
/** Minimum oxygen level for fish. */
private static double minOxygen = alive_fish;
/** Minimum tank water circulation for fish. */
private static double minCirc = minOxygen;
/** The current water circulation. */
private static double circulation = (randomGen.nextDouble() * 10) + alive_fish;
/** The current number of dead fish. */
private static int dead_fish = 0;
/** The current electrical conductivity. */
private static double ec = (randomGen.nextDouble()) + 1;
/** The current temperature. */
private static int temperature = randomGen.nextInt(3) + 28;
/** The current turbidity. */
private static double turbidity = ec + dead_fish + circulation;
/** The current water level. */
private static int water_level = (randomGen.nextInt(51)) + 200;
/** The current pH. */
private static double ph = (randomGen.nextDouble() * 1.2) + 6.8;
/** The current dissolved oxygen. */
private static double oxygen = circulation;
/** The desired electrical conductivity. */
private static double desiredEC = (randomGen.nextDouble()) + 1;
/** The desired temperature. */
private static int desiredTemperature = randomGen.nextInt(3) + 28;
/** The desired water level. */
private static int desiredWaterLevel = (randomGen.nextInt(51)) + 200;
/** The desired pH. */
private static double desiredPh = (randomGen.nextDouble() * 1.2) + 6.8;
/**
* Modifies the state of the system.
*/
public static void modifySystemState() {
// Print system state values.
final String desired = " (Desired: "; // PMD pickiness
final String required = " (Required: "; // PMD pickiness
System.out.println("----------------------");
System.out.println("System: Aquaponics");
System.out.println("Alive fish: " + alive_fish);
System.out.println("Dead fish: " + dead_fish);
System.out.println("Circulation: " + roundSingleDecimal(circulation) + required + minCirc
+ ")");
System.out.println("Electrical conductivity: " + roundSingleDecimal(ec)
+ desired + roundSingleDecimal(desiredEC) + ")" + required + minEC + "-"
+ maxEC + ")");
System.out.println("Temperature: " + temperature + desired + desiredTemperature + ")"
+ required + minTemp + "-" + maxTemp + ")");
System.out.println("Turbidity: " + roundSingleDecimal(turbidity));
System.out.println("Water level: " + water_level + desired + desiredWaterLevel + ")" + required
+ minWaterLevel + ")");
System.out.println("pH: " + roundSingleDecimal(ph) + desired + roundSingleDecimal(desiredPh)
+ ")" + required + minPH + "-" + maxPH + ")");
System.out.println("Oxygen level: " + roundSingleDecimal(oxygen) + required + minOxygen + ")");
// Changes water circulation by a random amount.
if (circulation < (alive_fish * 0.8)) {
// Fish need more circulation and oxygen!!! Increment circulation by 0.0 to 1.0 units.
circulation += randomGen.nextDouble();
}
else {
// Increment or decrement circulation by 0.0 to 1.0 units.
circulation += randomGen.nextDouble() - randomGen.nextDouble();
}
// Checks if fish are going to die or not.
if ((ec < minEC) || (ec > maxEC) || (temperature < minTemp) || (temperature > maxTemp)
|| (water_level < minWaterLevel) || (ph < minPH) || (ph > maxPH) || (oxygen < minOxygen)) {
// 50% chance of 1 fish dying.
int fishDeath = randomGen.nextInt(2);
dead_fish += fishDeath;
alive_fish -= fishDeath;
if (fishDeath == 1) {
// 1 dead fish increases EC by 0.05
ec += 0.05;
}
}
// Increments electrical conductivity within range of desired value.
if (ec < desiredEC) {
// 25% chance of incrementing by 0.05
ec += (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.05;
}
else if (ec > desiredEC) {
// 50% chance of decrementing by 0.05. EC declines as nutrients and food gets used up.
ec -= (randomGen.nextInt(2)) * 0.05;
}
- else if (ec == desiredEC) {
+ else {
// 12.5% chance of incrementing or decrementing 0.05 from desired ec.
ec += ((randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))) * 0.05;
}
// Increments temperature within range of the desired temperature.
if (temperature < desiredTemperature) {
// 25% chance of incrementing by 1 degree.
temperature += randomGen.nextInt(2) * randomGen.nextInt(2);
}
else if (temperature > desiredTemperature) {
// 25% chance of decrementing by 1 degree.
temperature -= randomGen.nextInt(2) * randomGen.nextInt(2);
}
else if (temperature == desiredTemperature) {
// 12.5% chance of incrementing or decrementing 1 degree from desired temperature.
temperature += (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2));
}
// Changes water level by a random amount.
if (water_level < (minWaterLevel)) {
// Fish need more water!!! 50% chance to increment water_level by 1 unit.
water_level += randomGen.nextInt(2);
}
else {
// Increment or decrement water_level by 1 unit.
water_level += randomGen.nextInt(2) - randomGen.nextInt(2);
}
// Update required water level in case fish have died.
minWaterLevel = alive_fish;
// Increments PH within range of the desired PH.
if (ph < desiredPh) {
// 25% chance of incrementing by 0.1
ph += (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.1;
}
else if (ph > desiredPh) {
// 25% chance of decrementing by 0.1
ph -= (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.1;
}
- else if (ph == desiredPh) {
+ else {
// 12.5% chance of incrementing or decrementing 0.1 from desired PH.
ph += ((randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))) * 0.1;
}
// Update oxygen.
oxygen = circulation;
// Update required circulation in case fish have died.
minCirc = alive_fish;
// Update required oxygen in case fish have died.
minOxygen = alive_fish;
// Updates turbidity. More dead fish = more turbidity. More circulation = less turbidity.
- turbidity = (alive_fish / 2) + ec + (dead_fish * 2) - (circulation - minCirc);
+ turbidity = ((alive_fish * 1.0) / 2) + ec + (dead_fish * 2) - (circulation - minCirc);
}
/**
* Modifies the desired system state values to within acceptable range.
*/
public static void modifyDesiredState() {
desiredEC = (randomGen.nextDouble()) + 1;
desiredTemperature = randomGen.nextInt(3) + 28;
desiredWaterLevel = (randomGen.nextInt(51)) + 200;
desiredPh = (randomGen.nextDouble() * 1.2) + 6.8;
}
/**
* Sets the desired temperature.
*
* @param newDesiredTemperature the desired temperature
*/
public static void setDesiredTemperature(int newDesiredTemperature) {
desiredTemperature = newDesiredTemperature;
}
/**
* Adds fish feed to the tank.
*
* @param feedAmount the amount of fish feed to add.
*/
public static void addFishFeed(double feedAmount) {
ec += feedAmount * 0.01;
}
/**
* Harvests fish from tank.
*
* @param numFish the amount of fish to harvest.
*/
public static void harvestFish(int numFish) {
alive_fish -= numFish;
}
/**
* Sets the desired nutrient amount which corresponds to EC.
*
* @param newDesiredNutrients the nutrient level.
*/
public static void setNutrients(double newDesiredNutrients) {
desiredEC = newDesiredNutrients;
}
/**
* Sets the desired pH.
*
* @param newDesiredPh the ph.
*/
public static void setDesiredPh(double newDesiredPh) {
desiredPh = newDesiredPh;
}
/**
* Sets the desired water level.
*
* @param newDesiredWaterLevel the water level.
*/
public static void setDesiredWaterLevel(int newDesiredWaterLevel) {
desiredWaterLevel = newDesiredWaterLevel;
}
/**
* Rounds double value to a single decimal place.
*
* @param doubleValue A double value
* @return Rounded value
*/
static double roundSingleDecimal(double doubleValue) {
DecimalFormat singleDecimal = new DecimalFormat("#.#");
return Double.valueOf(singleDecimal.format(doubleValue));
}
/**
* Returns the data as an XML Document instance.
*
* @return The data as XML.
* @throws Exception If problems occur creating the XML.
*/
public static DomRepresentation toXml() throws Exception {
final String state = "state"; // PMD pickiness
final String key = "key"; // PMD pickiness
final String value = "value"; // PMD pickiness
DocumentBuilderFactory factory = DocumentBuilderFactory.newInstance();
DocumentBuilder docBuilder = null;
docBuilder = factory.newDocumentBuilder();
Document doc = docBuilder.newDocument();
// Create root tag
Element rootElement = doc.createElement("state-data");
rootElement.setAttribute("system", "AQUAPONICS");
rootElement.setAttribute("device", "arduino-1");
rootElement.setAttribute("timestamp", String.valueOf(new Date().getTime()));
doc.appendChild(rootElement);
// Create circulation state tag.
Element circulationElement = doc.createElement(state);
circulationElement.setAttribute(key, "CIRCULATION");
circulationElement.setAttribute(value, String.valueOf(circulation));
rootElement.appendChild(circulationElement);
// Create dead fish state tag.
Element deadFishElement = doc.createElement(state);
deadFishElement.setAttribute(key, "DEAD_FISH");
deadFishElement.setAttribute(value, String.valueOf(dead_fish));
rootElement.appendChild(deadFishElement);
// Create electrical conductivity state tag.
Element electricalConductivityElement = doc.createElement(state);
electricalConductivityElement.setAttribute(key, "ELECTRICAL_CONDUCTIVITY");
electricalConductivityElement.setAttribute(value, String.valueOf(ec));
rootElement.appendChild(electricalConductivityElement);
// Create temperature state tag.
Element temperatureElement = doc.createElement(state);
temperatureElement.setAttribute(key, "TEMPERATURE");
temperatureElement.setAttribute(value, String.valueOf(temperature));
rootElement.appendChild(temperatureElement);
// Create turbidity state tag.
Element turbidityElement = doc.createElement(state);
turbidityElement.setAttribute(key, "TURBIDITY");
turbidityElement.setAttribute(value, String.valueOf(turbidity));
rootElement.appendChild(turbidityElement);
// Create water state tag.
Element waterLevelElement = doc.createElement(state);
waterLevelElement.setAttribute(key, "WATER_LEVEL");
waterLevelElement.setAttribute(value, String.valueOf(water_level));
rootElement.appendChild(waterLevelElement);
// Create PH state tag.
Element phElement = doc.createElement(state);
phElement.setAttribute(key, "PH");
phElement.setAttribute(value, String.valueOf(roundSingleDecimal(ph)));
rootElement.appendChild(phElement);
// Create oxygen state tag.
Element oxygenElement = doc.createElement(state);
oxygenElement.setAttribute(key, "OXYGEN");
oxygenElement.setAttribute(value, String.valueOf(oxygen));
rootElement.appendChild(oxygenElement);
// Convert Document to DomRepresentation.
DomRepresentation result = new DomRepresentation();
result.setDocument(doc);
// Return the XML in DomRepresentation form.
return result;
}
/**
* Appends Aquaponics state data at a specific timestamp snap-shot to the Document object
* passed to this method.
*
* @param doc Document object to append Aquaponics state data as child nodes.
* @param timestamp The specific time snap-shot the state data interested to be appended.
* @return Document object with appended Aquaponics state data.
*/
public static Document toXmlByTimestamp(Document doc, Long timestamp) {
final String state = "state"; // PMD pickiness
final String key = "key"; // PMD pickiness
final String value = "value"; // PMD pickiness
// Change the values.
modifyDesiredState();
modifySystemState();
// Get the root element, in this case would be <state-history> element.
Element rootElement = doc.getDocumentElement();
// Create state-data tag
Element stateElement = doc.createElement("state-data");
stateElement.setAttribute("system", "AQUAPONICS");
stateElement.setAttribute("device", "arduino-1");
stateElement.setAttribute("timestamp", timestamp.toString());
rootElement.appendChild(stateElement);
// Create circulation state tag.
Element circulationElement = doc.createElement(state);
circulationElement.setAttribute(key, "CIRCULATION");
circulationElement.setAttribute(value, String.valueOf(circulation));
stateElement.appendChild(circulationElement);
// Create dead fish state tag.
Element deadFishElement = doc.createElement(state);
deadFishElement.setAttribute(key, "DEAD_FISH");
deadFishElement.setAttribute(value, String.valueOf(dead_fish));
stateElement.appendChild(deadFishElement);
// Create electrical conductivity state tag.
Element electricalConductivityElement = doc.createElement(state);
electricalConductivityElement.setAttribute(key, "ELECTRICAL_CONDUCTIVITY");
electricalConductivityElement.setAttribute(value, String.valueOf(ec));
stateElement.appendChild(electricalConductivityElement);
// Create temperature state tag.
Element temperatureElement = doc.createElement(state);
temperatureElement.setAttribute(key, "TEMPERATURE");
temperatureElement.setAttribute(value, String.valueOf(temperature));
stateElement.appendChild(temperatureElement);
// Create turbidity state tag.
Element turbidityElement = doc.createElement(state);
turbidityElement.setAttribute(key, "TURBIDITY");
turbidityElement.setAttribute(value, String.valueOf(turbidity));
stateElement.appendChild(turbidityElement);
// Create water state tag.
Element waterLevelElement = doc.createElement(state);
waterLevelElement.setAttribute(key, "WATER_LEVEL");
waterLevelElement.setAttribute(value, String.valueOf(water_level));
stateElement.appendChild(waterLevelElement);
// Create PH state tag.
Element phElement = doc.createElement(state);
phElement.setAttribute(key, "PH");
phElement.setAttribute(value, String.valueOf(roundSingleDecimal(ph)));
stateElement.appendChild(phElement);
// Create oxygen state tag.
Element oxygenElement = doc.createElement(state);
oxygenElement.setAttribute(key, "OXYGEN");
oxygenElement.setAttribute(value, String.valueOf(oxygen));
stateElement.appendChild(oxygenElement);
// Return the XML in DomRepresentation form.
return doc;
}
}
| false | true | public static void modifySystemState() {
// Print system state values.
final String desired = " (Desired: "; // PMD pickiness
final String required = " (Required: "; // PMD pickiness
System.out.println("----------------------");
System.out.println("System: Aquaponics");
System.out.println("Alive fish: " + alive_fish);
System.out.println("Dead fish: " + dead_fish);
System.out.println("Circulation: " + roundSingleDecimal(circulation) + required + minCirc
+ ")");
System.out.println("Electrical conductivity: " + roundSingleDecimal(ec)
+ desired + roundSingleDecimal(desiredEC) + ")" + required + minEC + "-"
+ maxEC + ")");
System.out.println("Temperature: " + temperature + desired + desiredTemperature + ")"
+ required + minTemp + "-" + maxTemp + ")");
System.out.println("Turbidity: " + roundSingleDecimal(turbidity));
System.out.println("Water level: " + water_level + desired + desiredWaterLevel + ")" + required
+ minWaterLevel + ")");
System.out.println("pH: " + roundSingleDecimal(ph) + desired + roundSingleDecimal(desiredPh)
+ ")" + required + minPH + "-" + maxPH + ")");
System.out.println("Oxygen level: " + roundSingleDecimal(oxygen) + required + minOxygen + ")");
// Changes water circulation by a random amount.
if (circulation < (alive_fish * 0.8)) {
// Fish need more circulation and oxygen!!! Increment circulation by 0.0 to 1.0 units.
circulation += randomGen.nextDouble();
}
else {
// Increment or decrement circulation by 0.0 to 1.0 units.
circulation += randomGen.nextDouble() - randomGen.nextDouble();
}
// Checks if fish are going to die or not.
if ((ec < minEC) || (ec > maxEC) || (temperature < minTemp) || (temperature > maxTemp)
|| (water_level < minWaterLevel) || (ph < minPH) || (ph > maxPH) || (oxygen < minOxygen)) {
// 50% chance of 1 fish dying.
int fishDeath = randomGen.nextInt(2);
dead_fish += fishDeath;
alive_fish -= fishDeath;
if (fishDeath == 1) {
// 1 dead fish increases EC by 0.05
ec += 0.05;
}
}
// Increments electrical conductivity within range of desired value.
if (ec < desiredEC) {
// 25% chance of incrementing by 0.05
ec += (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.05;
}
else if (ec > desiredEC) {
// 50% chance of decrementing by 0.05. EC declines as nutrients and food gets used up.
ec -= (randomGen.nextInt(2)) * 0.05;
}
else if (ec == desiredEC) {
// 12.5% chance of incrementing or decrementing 0.05 from desired ec.
ec += ((randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))) * 0.05;
}
// Increments temperature within range of the desired temperature.
if (temperature < desiredTemperature) {
// 25% chance of incrementing by 1 degree.
temperature += randomGen.nextInt(2) * randomGen.nextInt(2);
}
else if (temperature > desiredTemperature) {
// 25% chance of decrementing by 1 degree.
temperature -= randomGen.nextInt(2) * randomGen.nextInt(2);
}
else if (temperature == desiredTemperature) {
// 12.5% chance of incrementing or decrementing 1 degree from desired temperature.
temperature += (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2));
}
// Changes water level by a random amount.
if (water_level < (minWaterLevel)) {
// Fish need more water!!! 50% chance to increment water_level by 1 unit.
water_level += randomGen.nextInt(2);
}
else {
// Increment or decrement water_level by 1 unit.
water_level += randomGen.nextInt(2) - randomGen.nextInt(2);
}
// Update required water level in case fish have died.
minWaterLevel = alive_fish;
// Increments PH within range of the desired PH.
if (ph < desiredPh) {
// 25% chance of incrementing by 0.1
ph += (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.1;
}
else if (ph > desiredPh) {
// 25% chance of decrementing by 0.1
ph -= (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.1;
}
else if (ph == desiredPh) {
// 12.5% chance of incrementing or decrementing 0.1 from desired PH.
ph += ((randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))) * 0.1;
}
// Update oxygen.
oxygen = circulation;
// Update required circulation in case fish have died.
minCirc = alive_fish;
// Update required oxygen in case fish have died.
minOxygen = alive_fish;
// Updates turbidity. More dead fish = more turbidity. More circulation = less turbidity.
turbidity = (alive_fish / 2) + ec + (dead_fish * 2) - (circulation - minCirc);
}
| public static void modifySystemState() {
// Print system state values.
final String desired = " (Desired: "; // PMD pickiness
final String required = " (Required: "; // PMD pickiness
System.out.println("----------------------");
System.out.println("System: Aquaponics");
System.out.println("Alive fish: " + alive_fish);
System.out.println("Dead fish: " + dead_fish);
System.out.println("Circulation: " + roundSingleDecimal(circulation) + required + minCirc
+ ")");
System.out.println("Electrical conductivity: " + roundSingleDecimal(ec)
+ desired + roundSingleDecimal(desiredEC) + ")" + required + minEC + "-"
+ maxEC + ")");
System.out.println("Temperature: " + temperature + desired + desiredTemperature + ")"
+ required + minTemp + "-" + maxTemp + ")");
System.out.println("Turbidity: " + roundSingleDecimal(turbidity));
System.out.println("Water level: " + water_level + desired + desiredWaterLevel + ")" + required
+ minWaterLevel + ")");
System.out.println("pH: " + roundSingleDecimal(ph) + desired + roundSingleDecimal(desiredPh)
+ ")" + required + minPH + "-" + maxPH + ")");
System.out.println("Oxygen level: " + roundSingleDecimal(oxygen) + required + minOxygen + ")");
// Changes water circulation by a random amount.
if (circulation < (alive_fish * 0.8)) {
// Fish need more circulation and oxygen!!! Increment circulation by 0.0 to 1.0 units.
circulation += randomGen.nextDouble();
}
else {
// Increment or decrement circulation by 0.0 to 1.0 units.
circulation += randomGen.nextDouble() - randomGen.nextDouble();
}
// Checks if fish are going to die or not.
if ((ec < minEC) || (ec > maxEC) || (temperature < minTemp) || (temperature > maxTemp)
|| (water_level < minWaterLevel) || (ph < minPH) || (ph > maxPH) || (oxygen < minOxygen)) {
// 50% chance of 1 fish dying.
int fishDeath = randomGen.nextInt(2);
dead_fish += fishDeath;
alive_fish -= fishDeath;
if (fishDeath == 1) {
// 1 dead fish increases EC by 0.05
ec += 0.05;
}
}
// Increments electrical conductivity within range of desired value.
if (ec < desiredEC) {
// 25% chance of incrementing by 0.05
ec += (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.05;
}
else if (ec > desiredEC) {
// 50% chance of decrementing by 0.05. EC declines as nutrients and food gets used up.
ec -= (randomGen.nextInt(2)) * 0.05;
}
else {
// 12.5% chance of incrementing or decrementing 0.05 from desired ec.
ec += ((randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))) * 0.05;
}
// Increments temperature within range of the desired temperature.
if (temperature < desiredTemperature) {
// 25% chance of incrementing by 1 degree.
temperature += randomGen.nextInt(2) * randomGen.nextInt(2);
}
else if (temperature > desiredTemperature) {
// 25% chance of decrementing by 1 degree.
temperature -= randomGen.nextInt(2) * randomGen.nextInt(2);
}
else if (temperature == desiredTemperature) {
// 12.5% chance of incrementing or decrementing 1 degree from desired temperature.
temperature += (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2));
}
// Changes water level by a random amount.
if (water_level < (minWaterLevel)) {
// Fish need more water!!! 50% chance to increment water_level by 1 unit.
water_level += randomGen.nextInt(2);
}
else {
// Increment or decrement water_level by 1 unit.
water_level += randomGen.nextInt(2) - randomGen.nextInt(2);
}
// Update required water level in case fish have died.
minWaterLevel = alive_fish;
// Increments PH within range of the desired PH.
if (ph < desiredPh) {
// 25% chance of incrementing by 0.1
ph += (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.1;
}
else if (ph > desiredPh) {
// 25% chance of decrementing by 0.1
ph -= (randomGen.nextInt(2) * randomGen.nextInt(2)) * 0.1;
}
else {
// 12.5% chance of incrementing or decrementing 0.1 from desired PH.
ph += ((randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))
- (randomGen.nextInt(2) * randomGen.nextInt(2) * randomGen.nextInt(2))) * 0.1;
}
// Update oxygen.
oxygen = circulation;
// Update required circulation in case fish have died.
minCirc = alive_fish;
// Update required oxygen in case fish have died.
minOxygen = alive_fish;
// Updates turbidity. More dead fish = more turbidity. More circulation = less turbidity.
turbidity = ((alive_fish * 1.0) / 2) + ec + (dead_fish * 2) - (circulation - minCirc);
}
|
diff --git a/stratosphere-addons/hadoop-compatibility/src/main/java/eu/stratosphere/hadoopcompat/datatypes/WritableWrapper.java b/stratosphere-addons/hadoop-compatibility/src/main/java/eu/stratosphere/hadoopcompat/datatypes/WritableWrapper.java
index 61011d097..1de44ceda 100644
--- a/stratosphere-addons/hadoop-compatibility/src/main/java/eu/stratosphere/hadoopcompat/datatypes/WritableWrapper.java
+++ b/stratosphere-addons/hadoop-compatibility/src/main/java/eu/stratosphere/hadoopcompat/datatypes/WritableWrapper.java
@@ -1,49 +1,49 @@
package eu.stratosphere.hadoopcompat.datatypes;
import java.io.DataInput;
import java.io.DataOutput;
import java.io.IOException;
import org.apache.hadoop.io.Writable;
import eu.stratosphere.types.Value;
import eu.stratosphere.util.InstantiationUtil;
public class WritableWrapper implements Value {
private static final long serialVersionUID = 1L;
private Writable wrapped;
private String wrappedType;
public WritableWrapper() {
}
public WritableWrapper(Writable toWrap) {
wrapped = toWrap;
wrappedType = toWrap.getClass().getCanonicalName();
}
public Writable value() {
return wrapped;
}
@Override
public void write(DataOutput out) throws IOException {
out.writeUTF(wrappedType);
wrapped.write(out);
}
@Override
public void read(DataInput in) throws IOException {
wrappedType = in.readUTF();
try {
Class wrClass = Class.forName(wrappedType);
- wrapped = InstantiationUtil.instantiate(wrClass, Writable.class);
+ wrapped = (Writable) InstantiationUtil.instantiate(wrClass, Writable.class);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Error cerating the WritableWrapper");
}
wrapped.readFields(in);
}
}
| true | true | public void read(DataInput in) throws IOException {
wrappedType = in.readUTF();
try {
Class wrClass = Class.forName(wrappedType);
wrapped = InstantiationUtil.instantiate(wrClass, Writable.class);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Error cerating the WritableWrapper");
}
wrapped.readFields(in);
}
| public void read(DataInput in) throws IOException {
wrappedType = in.readUTF();
try {
Class wrClass = Class.forName(wrappedType);
wrapped = (Writable) InstantiationUtil.instantiate(wrClass, Writable.class);
} catch (ClassNotFoundException e) {
throw new RuntimeException("Error cerating the WritableWrapper");
}
wrapped.readFields(in);
}
|
diff --git a/BLCMiner/src/net/mohatu/bloocoin/miner/MinerClass.java b/BLCMiner/src/net/mohatu/bloocoin/miner/MinerClass.java
index 1cf9a59..133c8d3 100644
--- a/BLCMiner/src/net/mohatu/bloocoin/miner/MinerClass.java
+++ b/BLCMiner/src/net/mohatu/bloocoin/miner/MinerClass.java
@@ -1,97 +1,97 @@
/*
* Copyright (C) 2013 Mohatu.net
*
* 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 net.mohatu.bloocoin.miner;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.util.Random;
public class MinerClass implements Runnable {
private String difficulty = "0000000";
public MinerClass(int diff) {
if (diff == 7) {
this.difficulty = "0000000";
}
if (diff == 8) {
this.difficulty = "00000000";
}
if (diff == 9) {
this.difficulty = "000000000";
}
if (diff == 10) {
this.difficulty = "0000000000";
}
}
@Override
public void run() {
try {
mine();
} catch (NoSuchAlgorithmException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void mine() throws NoSuchAlgorithmException {
String startString = randomString();
String currentString;
MessageDigest md = MessageDigest.getInstance("SHA-512");
StringBuffer sb;
+ while (MainView.getStatus()) {
for (int counter = 0; counter < 999999999; counter++) {
- while (MainView.getStatus()) {
MainView.updateCounter();
sb = new StringBuffer();
currentString = startString + counter;
md.update(currentString.getBytes());
byte byteData[] = md.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer
.toString((byteData[i] & 0xff) + 0x100, 16)
.substring(1));
}
if (sb.toString().startsWith(difficulty)) {
MainView.updateSolved(currentString);
System.out.println("Success: " + currentString);
}
}
}
}
public String randomString() {
String chars = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789";
Random r = new Random();
int limit = 5;
StringBuffer buf = new StringBuffer();
buf.append(chars.charAt(r.nextInt(26)));
for (int i = 0; i < limit; i++) {
buf.append(chars.charAt(r.nextInt(chars.length())));
}
System.out.println(buf);
return buf.toString();
}
public void submit() {
}
}
| false | true | public void mine() throws NoSuchAlgorithmException {
String startString = randomString();
String currentString;
MessageDigest md = MessageDigest.getInstance("SHA-512");
StringBuffer sb;
for (int counter = 0; counter < 999999999; counter++) {
while (MainView.getStatus()) {
MainView.updateCounter();
sb = new StringBuffer();
currentString = startString + counter;
md.update(currentString.getBytes());
byte byteData[] = md.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer
.toString((byteData[i] & 0xff) + 0x100, 16)
.substring(1));
}
if (sb.toString().startsWith(difficulty)) {
MainView.updateSolved(currentString);
System.out.println("Success: " + currentString);
}
}
}
}
| public void mine() throws NoSuchAlgorithmException {
String startString = randomString();
String currentString;
MessageDigest md = MessageDigest.getInstance("SHA-512");
StringBuffer sb;
while (MainView.getStatus()) {
for (int counter = 0; counter < 999999999; counter++) {
MainView.updateCounter();
sb = new StringBuffer();
currentString = startString + counter;
md.update(currentString.getBytes());
byte byteData[] = md.digest();
for (int i = 0; i < byteData.length; i++) {
sb.append(Integer
.toString((byteData[i] & 0xff) + 0x100, 16)
.substring(1));
}
if (sb.toString().startsWith(difficulty)) {
MainView.updateSolved(currentString);
System.out.println("Success: " + currentString);
}
}
}
}
|
diff --git a/src/com/orangeleap/tangerine/web/common/TangerineCustomDateEditor.java b/src/com/orangeleap/tangerine/web/common/TangerineCustomDateEditor.java
index f7b5f106..9dead8ef 100644
--- a/src/com/orangeleap/tangerine/web/common/TangerineCustomDateEditor.java
+++ b/src/com/orangeleap/tangerine/web/common/TangerineCustomDateEditor.java
@@ -1,65 +1,65 @@
package com.orangeleap.tangerine.web.common;
import org.springframework.beans.propertyeditors.CustomDateEditor;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.text.ParseException;
import java.util.Date;
import java.util.Calendar;
/**
* Extend the normal CustomDateEditor to know how to deal with
* seasonal dates, which are just specified as Month-Day, without
* a year. Will correctly parse a standard date format (MM/dd/yyyy)
* along with dates that are just MMMMM-d format. Will add the current
* year as the year component, unless that date would fall earlier
* than current date, which means Date is for next year.
* @version 1.0
*/
public class TangerineCustomDateEditor extends CustomDateEditor {
private DateFormat alternateDateFormat = new SimpleDateFormat("MMMMM-d");
public TangerineCustomDateEditor(DateFormat dateFormat, boolean allowEmpty) {
super(dateFormat, allowEmpty);
}
public TangerineCustomDateEditor(DateFormat dateFormat, boolean allowEmpty, int exactDateLength) {
super(dateFormat, allowEmpty, exactDateLength);
}
@Override
public void setAsText(String text) throws IllegalArgumentException {
try {
super.setAsText(text);
} catch(IllegalArgumentException ex) {
try {
// need to add a year component if
Date d = this.alternateDateFormat.parse(text);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.YEAR, year);
// if the date is before current date, assume it is next year
- if(c.get(Calendar.DAY_OF_YEAR) < now.get(Calendar.DAY_OF_YEAR)) {
- c.set(Calendar.YEAR, year+1);
- }
+ //if(c.get(Calendar.DAY_OF_YEAR) < now.get(Calendar.DAY_OF_YEAR)) {
+ // c.set(Calendar.YEAR, year+1);
+ //}
setValue(c.getTime());
}
catch (ParseException parseEx) {
IllegalArgumentException iae =
new IllegalArgumentException("Could not parse date: " + parseEx.getMessage());
iae.initCause(parseEx);
throw iae;
}
}
}
}
| true | true | public void setAsText(String text) throws IllegalArgumentException {
try {
super.setAsText(text);
} catch(IllegalArgumentException ex) {
try {
// need to add a year component if
Date d = this.alternateDateFormat.parse(text);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.YEAR, year);
// if the date is before current date, assume it is next year
if(c.get(Calendar.DAY_OF_YEAR) < now.get(Calendar.DAY_OF_YEAR)) {
c.set(Calendar.YEAR, year+1);
}
setValue(c.getTime());
}
catch (ParseException parseEx) {
IllegalArgumentException iae =
new IllegalArgumentException("Could not parse date: " + parseEx.getMessage());
iae.initCause(parseEx);
throw iae;
}
}
}
| public void setAsText(String text) throws IllegalArgumentException {
try {
super.setAsText(text);
} catch(IllegalArgumentException ex) {
try {
// need to add a year component if
Date d = this.alternateDateFormat.parse(text);
Calendar now = Calendar.getInstance();
int year = now.get(Calendar.YEAR);
Calendar c = Calendar.getInstance();
c.setTime(d);
c.set(Calendar.YEAR, year);
// if the date is before current date, assume it is next year
//if(c.get(Calendar.DAY_OF_YEAR) < now.get(Calendar.DAY_OF_YEAR)) {
// c.set(Calendar.YEAR, year+1);
//}
setValue(c.getTime());
}
catch (ParseException parseEx) {
IllegalArgumentException iae =
new IllegalArgumentException("Could not parse date: " + parseEx.getMessage());
iae.initCause(parseEx);
throw iae;
}
}
}
|
diff --git a/src/android2iphone/android/view/LayoutInflater.java b/src/android2iphone/android/view/LayoutInflater.java
index eff556ec..7c0d9cc2 100644
--- a/src/android2iphone/android/view/LayoutInflater.java
+++ b/src/android2iphone/android/view/LayoutInflater.java
@@ -1,62 +1,64 @@
/*
* Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language
*
* 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., 675 Mass
* Ave, Cambridge, MA 02139, USA.
*
* For more information, visit the XMLVM Home Page at http://www.xmlvm.org
*/
package android.view;
import android.content.Context;
import android.internal.LayoutManager;
/**
* @author arno
*
*/
public class LayoutInflater {
private Context context;
public LayoutInflater(Context context) {
this.context = context;
}
/**
* @param legionGameOver
* @param legionGameOverLayout
* @param b
*/
public View inflate(int resource, ViewGroup root, boolean attachToRoot)
throws InflateException {
View v = LayoutManager.getLayout(context, resource);
if (v == null) {
throw new InflateException("Unable to inflate layout: " + resource);
}
if (root != null) {
- v.setLayoutParams(root.getLayoutParams());
if (attachToRoot) {
root.addView(v);
}
+ else {
+ v.setLayoutParams(root.getLayoutParams());
+ }
}
return root != null && attachToRoot ? root : v;
}
}
| false | true | public View inflate(int resource, ViewGroup root, boolean attachToRoot)
throws InflateException {
View v = LayoutManager.getLayout(context, resource);
if (v == null) {
throw new InflateException("Unable to inflate layout: " + resource);
}
if (root != null) {
v.setLayoutParams(root.getLayoutParams());
if (attachToRoot) {
root.addView(v);
}
}
return root != null && attachToRoot ? root : v;
}
| public View inflate(int resource, ViewGroup root, boolean attachToRoot)
throws InflateException {
View v = LayoutManager.getLayout(context, resource);
if (v == null) {
throw new InflateException("Unable to inflate layout: " + resource);
}
if (root != null) {
if (attachToRoot) {
root.addView(v);
}
else {
v.setLayoutParams(root.getLayoutParams());
}
}
return root != null && attachToRoot ? root : v;
}
|
diff --git a/src/KingPiece.java b/src/KingPiece.java
index f01ea40..171959f 100644
--- a/src/KingPiece.java
+++ b/src/KingPiece.java
@@ -1,66 +1,66 @@
public class KingPiece extends Piece{
public KingPiece(Board board,boolean white, int xCord, int yCord, Piece[][] pieceBoard, boolean[][]whiteMoves, boolean[][]blackMoves)
{
super(board,white, xCord, yCord, pieceBoard,whiteMoves,blackMoves);
this.pieceType = "TKing";
isKing = true;
}
public void setMoves()
{
int cVal = getColorValueKing();
for(int y=-1; y<2; y++)
{
for(int x=-1; x<2; x++)
{
if(isValid(xCord+x,yCord+y)&&(!sameColor(xCord+x, yCord+y)||isEmpty(xCord+x,yCord+y)))
{
if((white && !blackMoves[xCord+x][yCord+y]) || (!white && !whiteMoves[xCord+x][yCord+y]))
canMove[xCord+x][yCord+y]=true;
}
}
}
- if(pBoard.getTurnCount()>0 && !moved) //King couldn't have moved
+ if(pBoard.getTurnCount()>0 && !moved && ((white&&!blackMoves[xCord][yCord])||(!white&&!whiteMoves[xCord][yCord]))) //King couldn't have moved
{
if(!isEmpty(xCord-4,cVal) && !pieceBoard[xCord-4][cVal].moved)//rook involved couldn't have moved
{
for(int x=-1; x>-3; x--)
{
if(!isEmpty(xCord+x,cVal) || ((white && blackMoves[xCord+x][cVal]) || (!white && whiteMoves[xCord+x][cVal])))
break;
if(x==-2)
canMove[xCord+x][cVal] = true;
}
}
if(!isEmpty(xCord+3,cVal) && !pieceBoard[xCord+3][cVal].moved)//rook involved couldn't have moved
{
for(int x=1; x<3; x++)
{
if(!isEmpty(xCord+x,cVal) || ((white && blackMoves[xCord+x][cVal]) || (!white && whiteMoves[xCord+x][cVal])))
break;
if(x == 2)
canMove[xCord+x][cVal] = true;
}
}
}
addBlackAndWhiteMoves();
}
public void setImage()
{
super.setImage();
pieceImage = pieceImage.getSubimage(0, ySpacing, 70, 70);
}
}
| true | true | public void setMoves()
{
int cVal = getColorValueKing();
for(int y=-1; y<2; y++)
{
for(int x=-1; x<2; x++)
{
if(isValid(xCord+x,yCord+y)&&(!sameColor(xCord+x, yCord+y)||isEmpty(xCord+x,yCord+y)))
{
if((white && !blackMoves[xCord+x][yCord+y]) || (!white && !whiteMoves[xCord+x][yCord+y]))
canMove[xCord+x][yCord+y]=true;
}
}
}
if(pBoard.getTurnCount()>0 && !moved) //King couldn't have moved
{
if(!isEmpty(xCord-4,cVal) && !pieceBoard[xCord-4][cVal].moved)//rook involved couldn't have moved
{
for(int x=-1; x>-3; x--)
{
if(!isEmpty(xCord+x,cVal) || ((white && blackMoves[xCord+x][cVal]) || (!white && whiteMoves[xCord+x][cVal])))
break;
if(x==-2)
canMove[xCord+x][cVal] = true;
}
}
if(!isEmpty(xCord+3,cVal) && !pieceBoard[xCord+3][cVal].moved)//rook involved couldn't have moved
{
for(int x=1; x<3; x++)
{
if(!isEmpty(xCord+x,cVal) || ((white && blackMoves[xCord+x][cVal]) || (!white && whiteMoves[xCord+x][cVal])))
break;
if(x == 2)
canMove[xCord+x][cVal] = true;
}
}
}
addBlackAndWhiteMoves();
}
| public void setMoves()
{
int cVal = getColorValueKing();
for(int y=-1; y<2; y++)
{
for(int x=-1; x<2; x++)
{
if(isValid(xCord+x,yCord+y)&&(!sameColor(xCord+x, yCord+y)||isEmpty(xCord+x,yCord+y)))
{
if((white && !blackMoves[xCord+x][yCord+y]) || (!white && !whiteMoves[xCord+x][yCord+y]))
canMove[xCord+x][yCord+y]=true;
}
}
}
if(pBoard.getTurnCount()>0 && !moved && ((white&&!blackMoves[xCord][yCord])||(!white&&!whiteMoves[xCord][yCord]))) //King couldn't have moved
{
if(!isEmpty(xCord-4,cVal) && !pieceBoard[xCord-4][cVal].moved)//rook involved couldn't have moved
{
for(int x=-1; x>-3; x--)
{
if(!isEmpty(xCord+x,cVal) || ((white && blackMoves[xCord+x][cVal]) || (!white && whiteMoves[xCord+x][cVal])))
break;
if(x==-2)
canMove[xCord+x][cVal] = true;
}
}
if(!isEmpty(xCord+3,cVal) && !pieceBoard[xCord+3][cVal].moved)//rook involved couldn't have moved
{
for(int x=1; x<3; x++)
{
if(!isEmpty(xCord+x,cVal) || ((white && blackMoves[xCord+x][cVal]) || (!white && whiteMoves[xCord+x][cVal])))
break;
if(x == 2)
canMove[xCord+x][cVal] = true;
}
}
}
addBlackAndWhiteMoves();
}
|
diff --git a/query/src/test/java/org/infinispan/query/blackbox/LocalCacheTest.java b/query/src/test/java/org/infinispan/query/blackbox/LocalCacheTest.java
index 9a346a4403..95541ecb7b 100644
--- a/query/src/test/java/org/infinispan/query/blackbox/LocalCacheTest.java
+++ b/query/src/test/java/org/infinispan/query/blackbox/LocalCacheTest.java
@@ -1,83 +1,83 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2009, Red Hat Middleware LLC, and individual contributors
* by the @authors tag. See the copyright.txt 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.infinispan.query.blackbox;
import org.infinispan.config.Configuration;
import org.infinispan.manager.CacheManager;
import org.infinispan.query.helper.TestQueryHelperFactory;
import org.infinispan.query.test.Person;
import org.infinispan.test.fwk.TestCacheManagerFactory;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import static org.infinispan.config.Configuration.CacheMode.LOCAL;
/**
* @author Navin Surtani
*/
@Test(groups = "functional")
public class LocalCacheTest extends AbstractLocalQueryTest {
protected void enhanceConfig(Configuration c) {
// no op, meant to be overridden
}
protected CacheManager createCacheManager() throws Exception {
Configuration c = getDefaultClusteredConfig(LOCAL, true);
c.setIndexingEnabled(true);
c.setIndexLocalOnly(false);
enhanceConfig(c);
return TestCacheManagerFactory.createCacheManager(c, true);
}
@BeforeMethod
public void setUp() throws Exception {
- cache = createCacheManager().getCache();
+ cache = cacheManager.getCache();
qh = TestQueryHelperFactory.createTestQueryHelperInstance(cache, Person.class);
person1 = new Person();
person1.setName("Navin Surtani");
person1.setBlurb("Likes playing WoW");
person2 = new Person();
person2.setName("Big Goat");
person2.setBlurb("Eats grass");
person3 = new Person();
person3.setName("Mini Goat");
person3.setBlurb("Eats cheese");
person5 = new Person();
person5.setName("Smelly Cat");
person5.setBlurb("Eats fish");
//Put the 3 created objects in the cache.
cache.put(key1, person1);
cache.put(key2, person2);
cache.put(key3, person3);
}
}
| true | true | public void setUp() throws Exception {
cache = createCacheManager().getCache();
qh = TestQueryHelperFactory.createTestQueryHelperInstance(cache, Person.class);
person1 = new Person();
person1.setName("Navin Surtani");
person1.setBlurb("Likes playing WoW");
person2 = new Person();
person2.setName("Big Goat");
person2.setBlurb("Eats grass");
person3 = new Person();
person3.setName("Mini Goat");
person3.setBlurb("Eats cheese");
person5 = new Person();
person5.setName("Smelly Cat");
person5.setBlurb("Eats fish");
//Put the 3 created objects in the cache.
cache.put(key1, person1);
cache.put(key2, person2);
cache.put(key3, person3);
}
| public void setUp() throws Exception {
cache = cacheManager.getCache();
qh = TestQueryHelperFactory.createTestQueryHelperInstance(cache, Person.class);
person1 = new Person();
person1.setName("Navin Surtani");
person1.setBlurb("Likes playing WoW");
person2 = new Person();
person2.setName("Big Goat");
person2.setBlurb("Eats grass");
person3 = new Person();
person3.setName("Mini Goat");
person3.setBlurb("Eats cheese");
person5 = new Person();
person5.setName("Smelly Cat");
person5.setBlurb("Eats fish");
//Put the 3 created objects in the cache.
cache.put(key1, person1);
cache.put(key2, person2);
cache.put(key3, person3);
}
|
diff --git a/Poker/src/poker/arturka/Game.java b/Poker/src/poker/arturka/Game.java
index 1b989f4..10a0bfd 100644
--- a/Poker/src/poker/arturka/Game.java
+++ b/Poker/src/poker/arturka/Game.java
@@ -1,300 +1,300 @@
package poker.arturka;
import commands.*;
import message.data.*;
import poker.server.Room;
import poker.server.Tuple2;
import java.util.ArrayList;
import java.util.List;
public class Game implements Runnable {
private Deck deck;
private Players players;
private int blind;
private List<Card> table;
private int maxBet;
private int state;
private Room room;
private boolean endGame;
private HandEvaluator evaluator;
private List<SendWinnerListCommand.Tuple> winners;
public Game(Room room){
deck=new Deck();
players=new Players();
blind=30;
maxBet=0;
table=new ArrayList<Card>();
state=0;
this.room=room;
for(Tuple2 tuple: room.getUsers()){
players.addPlayer(tuple.id,tuple.nick);
}
endGame=false;
winners=new ArrayList<SendWinnerListCommand.Tuple>();
}
private void moneyDispenser(PlayerHand... hands){
int betsForWinner;
betsForWinner=players.fetchBets(hands[0].getPlayer().getBet())/hands.length;
for(PlayerHand hand:hands){
hand.getPlayer().giveCash(betsForWinner);
winners.add(new SendWinnerListCommand.Tuple(hand.getPlayer().getId(), betsForWinner, hand.getHand()));
System.out.println("COMBO DUMP//PLAYER ID:"+hand.getPlayer().getId()+" NICK:"+hand.getPlayer().getNick()+" WON ("+betsForWinner+"$) WITH "+hand.getHand());
}
}
private void triariaSolver(PlayerHand smallest,PlayerHand hand,PlayerHand hand2){
moneyDispenser(smallest);
if (hand.getPlayer().getBet()<hand2.getPlayer().getBet()){
moneyDispenser(hand);
moneyDispenser(hand2);
}else if(hand.getPlayer().getBet()==hand2.getPlayer().getBet()){
moneyDispenser(hand, hand2);
}else{
moneyDispenser(hand2);
moneyDispenser(hand);
}
}
private void duariaSolver(PlayerHand equal1, PlayerHand equal2, PlayerHand biggest){
moneyDispenser(equal1, equal2);
moneyDispenser(biggest);
}
private void endGame(){
System.out.println("ENTER ENDGAME");
if (!endGame) {
System.out.println("ENTER IF ENDGAME");
List<SendWinnerListCommand.Tuple> winners =new ArrayList<SendWinnerListCommand.Tuple>();
evaluator=new HandEvaluator(players.playersLeft(), table);
if (players.playersLeft().size()>1){
List<PlayerHand> bestPlayers=evaluator.getPlayerHandEvaluation();
int i=0;
PlayerHand currentWinnerHand;
PlayerHand anotherWinnerHand;
PlayerHand thirdWinnerHand;
while(players.getPot()>0&&i<10){
currentWinnerHand=bestPlayers.get(i);
if(bestPlayers.size()>=i+3){
anotherWinnerHand=bestPlayers.get(i + 1);
thirdWinnerHand=bestPlayers.get(i + 2);
if(currentWinnerHand.getPosition()==anotherWinnerHand.getPosition()
&¤tWinnerHand.getPosition()==thirdWinnerHand.getPosition()){
int curVAno=currentWinnerHand.getPlayer().getBet()-anotherWinnerHand.getPlayer().getBet();
int curVThi=currentWinnerHand.getPlayer().getBet()-thirdWinnerHand.getPlayer().getBet();
int anoVThi=anotherWinnerHand.getPlayer().getBet()-thirdWinnerHand.getPlayer().getBet();
if(curVAno==0&&curVThi==0){
System.out.println("Case when all player have same bets");
moneyDispenser(currentWinnerHand, anotherWinnerHand, thirdWinnerHand);
}else if(curVAno<0&&curVThi<0){
System.out.println("Case when current has smallest bet");
triariaSolver(currentWinnerHand,anotherWinnerHand,thirdWinnerHand);
}else if(curVAno>0&&anoVThi<0){
System.out.println("Case when another has smallest bet");
triariaSolver(anotherWinnerHand,currentWinnerHand,thirdWinnerHand);
}else if(curVThi>0&&anoVThi>0){
System.out.println("Case when third has smallest bet");
triariaSolver(thirdWinnerHand,anotherWinnerHand,currentWinnerHand);
}else if(curVAno==0){
System.out.println("Case when current and another have same bets");
duariaSolver(currentWinnerHand,anotherWinnerHand,thirdWinnerHand);
}else if(curVThi==0){
System.out.println("Case when current and third have same bets");
duariaSolver(currentWinnerHand,thirdWinnerHand,anotherWinnerHand);
}else if(anoVThi==0){
System.out.println("Case when another and third have same bets");
duariaSolver(thirdWinnerHand,anotherWinnerHand,currentWinnerHand);
}
i+=3;
continue;
}
}
if(bestPlayers.size()>=i+2){
anotherWinnerHand=bestPlayers.get(i+1);
if(currentWinnerHand.getPosition()==anotherWinnerHand.getPosition()){
int curVAno=currentWinnerHand.getPlayer().getBet()-anotherWinnerHand.getPlayer().getBet();
if (curVAno<0){
moneyDispenser(currentWinnerHand);
}else if(curVAno==0){
moneyDispenser(currentWinnerHand, anotherWinnerHand);
}else{
moneyDispenser(anotherWinnerHand);
}
i+=2;
continue;
}
}
moneyDispenser(currentWinnerHand);
}
}else if(players.playersLeft().size()>0){
players.playersLeft().get(0).giveCash(players.getPot());
winners.add(new SendWinnerListCommand.Tuple(players.playersLeft().get(0).getId(), players.getPot(),Hand.LAST_ONE));
}else{
Thread.currentThread().interrupt();
return;
}
room.Broadcast(new SendWinnerListCommand(winners));
System.out.println("BROADCAST WINNER");
winners.clear();
for(Player currentPlayer: players.getPlayersList()){
if(currentPlayer.isInGame()&¤tPlayer.getCash()==0){
currentPlayer.toggleInGame();
}
room.Broadcast(new ChangeCashCommand(currentPlayer.getId(),currentPlayer.getCash()));
System.out.println("BROADCAST CASH UPDATE");
}
players.fetchBets(99999);
endGame=true;
}
}
private boolean raiseBet(int playerPot){
if (playerPot>maxBet){
maxBet=playerPot;
return true;
}else{
return false;
}
}
public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Game thread started");
// for(int id: Room.getUsers()){
// players.addPlayer(id);
// }
players.getDealer();
while(true){
state=0;
maxBet=0;
endGame=false;
table.clear();
room.Broadcast(new FlopCommand(null,null,null));
room.Broadcast(new TurnRiverCommand(null, TurnRiverCommand.RorT.TURN));
room.Broadcast(new TurnRiverCommand(null, TurnRiverCommand.RorT.RIVER));
for(Player player:players.getPlayersList()){
room.sendToUser(player.getId(), new SendPlayerListCommand(players.getSafeList()));
System.out.println("COMMAND TO ID:"+player.getId()+" NICK:"+player.getNick()+" SEND PLAYER LIST");
}
deck.shuffleDeck();
for(Player currentPlayer: players.getPlayersList()){
if (currentPlayer.isInGame()){
currentPlayer.unFold();
currentPlayer.giveCards(deck.getTopCard(),deck.getTopCard());
room.sendToUser(currentPlayer.getId(),new SendCardsCommand(currentPlayer.getId(),currentPlayer.getHand()[0],currentPlayer.getHand()[1]));
System.out.println("COMMAND TO ID:"+currentPlayer.getId()+" NICK:"+currentPlayer.getNick()+" HAND "+currentPlayer.handToSymbol());
}
}
Player oldDealer=players.nextDealer();
room.Broadcast(new ChangeDealersCommand(oldDealer.getId(),players.getDealer().getId()));
System.out.println("BROADCAST ID:"+players.getDealer().getId()+" NICK:"+players.getDealer().getNick()+" NEW DEALER");
Player nextPlayer=players.getNextPlayer(players.getDealer());
if (!nextPlayer.bet(blind/2)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(nextPlayer.getId(),ClientTurn.BLIND,nextPlayer.getBet(),nextPlayer.getCash())));
System.out.println("BROADCAST ID:"+nextPlayer.getId()+" NICK:"+nextPlayer.getNick()+" SMALL BLIND ("+blind/2+"$)");
nextPlayer=players.getNextPlayer(nextPlayer);
if (!nextPlayer.bet(blind)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(nextPlayer.getId(),ClientTurn.BLIND,nextPlayer.getBet(),nextPlayer.getCash())));
System.out.println("BROADCAST ID:"+nextPlayer.getId()+" NICK:"+nextPlayer.getNick()+" BIG BLIND ("+blind+"$)");
Player firstBetter=players.getNextPlayer(nextPlayer);
Player better=firstBetter;
ClientResponse move;
while(state<4&&!endGame){
do{
if(!better.hasFolded()&&better.getCash()>0){
if(better.getBet()==maxBet){
move = room.sendToUser(better.getId(),new FRCheckCommand());
System.out.println("COMMAND TO ID: "+better.getId()+" NICK:"+better.getNick()+" DO CHECK");
}else{
move = room.sendToUser(better.getId(),new FRCallCommand());
System.out.println("COMMAND TO ID: "+better.getId()+" NICK:"+better.getNick()+" DO CALL");
}
if (move==null){
move=new ClientResponse(ClientTurn.EXIT,1);
}
System.out.println("RESPONSE FROM ID:"+better.getId()+" NICK:"+better.getNick()+" TURN MADE:"+move.turn+(move.turn==ClientTurn.RAISE?"("+better.getBet()+"$)":""));
switch(move.turn){
case FOLD:
better.Fold();
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.FOLD,better.getBet(),better.getCash())));
// System.out.println("BROADCAST FOLD");
break;
case CHECK:
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.CHECK,better.getBet(),better.getCash())));
// System.out.println("BROADCAST CHECK");
break;
case CALL:
better.bet(maxBet-better.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.CALL,better.getBet(),better.getCash())));
// System.out.println("BROADCAST CALL");
break;
case RAISE:
better.bet(move.getBet());
raiseBet(better.getBet());
firstBetter=better;
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.RAISE,better.getBet(),better.getCash())));
// System.out.println("BROADCAST RAISE ("+better.getBet()+"$)");
break;
case EXIT:
better.Fold();
better.toggleInGame();
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.EXIT,better.getBet(),better.getCash())));
// System.out.println("BROADCAST FOLD");
room.removeUser(better.getId());
players.removePlayer(better.getId());
}
- if(players.playersLeft().size()<2||players.playersHaveToMove().size()<2){
+ if(players.playersLeft().size()<2&&players.playersHaveToMove().size()<2){
endGame();
break;
}
}
better=players.getNextPlayer(better);
}while (better!=firstBetter&&!endGame);
if(!endGame){
switch (state){
case 0:
table.add(deck.getTopCard());
table.add(deck.getTopCard());
table.add(deck.getTopCard());
room.Broadcast(new FlopCommand(table.get(0), table.get(1), table.get(2)));
System.out.println("BROADCAST FLOP " + table.get(0).toSymbol() + " " + table.get(1).toSymbol() + " " + table.get(2).toSymbol());
state++;
break;
case 1:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(3), TurnRiverCommand.RorT.TURN));
System.out.println("BROADCAST TURN "+table.get(3).toSymbol());
state++;
break;
case 2:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(4), TurnRiverCommand.RorT.RIVER));
System.out.println("BROADCAST RIVER "+table.get(4).toSymbol());
state++;
break;
default:
state++;
}
}
}
endGame();
}
}
}
| true | true | public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Game thread started");
// for(int id: Room.getUsers()){
// players.addPlayer(id);
// }
players.getDealer();
while(true){
state=0;
maxBet=0;
endGame=false;
table.clear();
room.Broadcast(new FlopCommand(null,null,null));
room.Broadcast(new TurnRiverCommand(null, TurnRiverCommand.RorT.TURN));
room.Broadcast(new TurnRiverCommand(null, TurnRiverCommand.RorT.RIVER));
for(Player player:players.getPlayersList()){
room.sendToUser(player.getId(), new SendPlayerListCommand(players.getSafeList()));
System.out.println("COMMAND TO ID:"+player.getId()+" NICK:"+player.getNick()+" SEND PLAYER LIST");
}
deck.shuffleDeck();
for(Player currentPlayer: players.getPlayersList()){
if (currentPlayer.isInGame()){
currentPlayer.unFold();
currentPlayer.giveCards(deck.getTopCard(),deck.getTopCard());
room.sendToUser(currentPlayer.getId(),new SendCardsCommand(currentPlayer.getId(),currentPlayer.getHand()[0],currentPlayer.getHand()[1]));
System.out.println("COMMAND TO ID:"+currentPlayer.getId()+" NICK:"+currentPlayer.getNick()+" HAND "+currentPlayer.handToSymbol());
}
}
Player oldDealer=players.nextDealer();
room.Broadcast(new ChangeDealersCommand(oldDealer.getId(),players.getDealer().getId()));
System.out.println("BROADCAST ID:"+players.getDealer().getId()+" NICK:"+players.getDealer().getNick()+" NEW DEALER");
Player nextPlayer=players.getNextPlayer(players.getDealer());
if (!nextPlayer.bet(blind/2)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(nextPlayer.getId(),ClientTurn.BLIND,nextPlayer.getBet(),nextPlayer.getCash())));
System.out.println("BROADCAST ID:"+nextPlayer.getId()+" NICK:"+nextPlayer.getNick()+" SMALL BLIND ("+blind/2+"$)");
nextPlayer=players.getNextPlayer(nextPlayer);
if (!nextPlayer.bet(blind)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(nextPlayer.getId(),ClientTurn.BLIND,nextPlayer.getBet(),nextPlayer.getCash())));
System.out.println("BROADCAST ID:"+nextPlayer.getId()+" NICK:"+nextPlayer.getNick()+" BIG BLIND ("+blind+"$)");
Player firstBetter=players.getNextPlayer(nextPlayer);
Player better=firstBetter;
ClientResponse move;
while(state<4&&!endGame){
do{
if(!better.hasFolded()&&better.getCash()>0){
if(better.getBet()==maxBet){
move = room.sendToUser(better.getId(),new FRCheckCommand());
System.out.println("COMMAND TO ID: "+better.getId()+" NICK:"+better.getNick()+" DO CHECK");
}else{
move = room.sendToUser(better.getId(),new FRCallCommand());
System.out.println("COMMAND TO ID: "+better.getId()+" NICK:"+better.getNick()+" DO CALL");
}
if (move==null){
move=new ClientResponse(ClientTurn.EXIT,1);
}
System.out.println("RESPONSE FROM ID:"+better.getId()+" NICK:"+better.getNick()+" TURN MADE:"+move.turn+(move.turn==ClientTurn.RAISE?"("+better.getBet()+"$)":""));
switch(move.turn){
case FOLD:
better.Fold();
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.FOLD,better.getBet(),better.getCash())));
// System.out.println("BROADCAST FOLD");
break;
case CHECK:
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.CHECK,better.getBet(),better.getCash())));
// System.out.println("BROADCAST CHECK");
break;
case CALL:
better.bet(maxBet-better.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.CALL,better.getBet(),better.getCash())));
// System.out.println("BROADCAST CALL");
break;
case RAISE:
better.bet(move.getBet());
raiseBet(better.getBet());
firstBetter=better;
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.RAISE,better.getBet(),better.getCash())));
// System.out.println("BROADCAST RAISE ("+better.getBet()+"$)");
break;
case EXIT:
better.Fold();
better.toggleInGame();
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.EXIT,better.getBet(),better.getCash())));
// System.out.println("BROADCAST FOLD");
room.removeUser(better.getId());
players.removePlayer(better.getId());
}
if(players.playersLeft().size()<2||players.playersHaveToMove().size()<2){
endGame();
break;
}
}
better=players.getNextPlayer(better);
}while (better!=firstBetter&&!endGame);
if(!endGame){
switch (state){
case 0:
table.add(deck.getTopCard());
table.add(deck.getTopCard());
table.add(deck.getTopCard());
room.Broadcast(new FlopCommand(table.get(0), table.get(1), table.get(2)));
System.out.println("BROADCAST FLOP " + table.get(0).toSymbol() + " " + table.get(1).toSymbol() + " " + table.get(2).toSymbol());
state++;
break;
case 1:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(3), TurnRiverCommand.RorT.TURN));
System.out.println("BROADCAST TURN "+table.get(3).toSymbol());
state++;
break;
case 2:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(4), TurnRiverCommand.RorT.RIVER));
System.out.println("BROADCAST RIVER "+table.get(4).toSymbol());
state++;
break;
default:
state++;
}
}
}
endGame();
}
}
| public void run() {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Game thread started");
// for(int id: Room.getUsers()){
// players.addPlayer(id);
// }
players.getDealer();
while(true){
state=0;
maxBet=0;
endGame=false;
table.clear();
room.Broadcast(new FlopCommand(null,null,null));
room.Broadcast(new TurnRiverCommand(null, TurnRiverCommand.RorT.TURN));
room.Broadcast(new TurnRiverCommand(null, TurnRiverCommand.RorT.RIVER));
for(Player player:players.getPlayersList()){
room.sendToUser(player.getId(), new SendPlayerListCommand(players.getSafeList()));
System.out.println("COMMAND TO ID:"+player.getId()+" NICK:"+player.getNick()+" SEND PLAYER LIST");
}
deck.shuffleDeck();
for(Player currentPlayer: players.getPlayersList()){
if (currentPlayer.isInGame()){
currentPlayer.unFold();
currentPlayer.giveCards(deck.getTopCard(),deck.getTopCard());
room.sendToUser(currentPlayer.getId(),new SendCardsCommand(currentPlayer.getId(),currentPlayer.getHand()[0],currentPlayer.getHand()[1]));
System.out.println("COMMAND TO ID:"+currentPlayer.getId()+" NICK:"+currentPlayer.getNick()+" HAND "+currentPlayer.handToSymbol());
}
}
Player oldDealer=players.nextDealer();
room.Broadcast(new ChangeDealersCommand(oldDealer.getId(),players.getDealer().getId()));
System.out.println("BROADCAST ID:"+players.getDealer().getId()+" NICK:"+players.getDealer().getNick()+" NEW DEALER");
Player nextPlayer=players.getNextPlayer(players.getDealer());
if (!nextPlayer.bet(blind/2)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(nextPlayer.getId(),ClientTurn.BLIND,nextPlayer.getBet(),nextPlayer.getCash())));
System.out.println("BROADCAST ID:"+nextPlayer.getId()+" NICK:"+nextPlayer.getNick()+" SMALL BLIND ("+blind/2+"$)");
nextPlayer=players.getNextPlayer(nextPlayer);
if (!nextPlayer.bet(blind)){
nextPlayer.bet(nextPlayer.getCash());
}
raiseBet(nextPlayer.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(nextPlayer.getId(),ClientTurn.BLIND,nextPlayer.getBet(),nextPlayer.getCash())));
System.out.println("BROADCAST ID:"+nextPlayer.getId()+" NICK:"+nextPlayer.getNick()+" BIG BLIND ("+blind+"$)");
Player firstBetter=players.getNextPlayer(nextPlayer);
Player better=firstBetter;
ClientResponse move;
while(state<4&&!endGame){
do{
if(!better.hasFolded()&&better.getCash()>0){
if(better.getBet()==maxBet){
move = room.sendToUser(better.getId(),new FRCheckCommand());
System.out.println("COMMAND TO ID: "+better.getId()+" NICK:"+better.getNick()+" DO CHECK");
}else{
move = room.sendToUser(better.getId(),new FRCallCommand());
System.out.println("COMMAND TO ID: "+better.getId()+" NICK:"+better.getNick()+" DO CALL");
}
if (move==null){
move=new ClientResponse(ClientTurn.EXIT,1);
}
System.out.println("RESPONSE FROM ID:"+better.getId()+" NICK:"+better.getNick()+" TURN MADE:"+move.turn+(move.turn==ClientTurn.RAISE?"("+better.getBet()+"$)":""));
switch(move.turn){
case FOLD:
better.Fold();
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.FOLD,better.getBet(),better.getCash())));
// System.out.println("BROADCAST FOLD");
break;
case CHECK:
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.CHECK,better.getBet(),better.getCash())));
// System.out.println("BROADCAST CHECK");
break;
case CALL:
better.bet(maxBet-better.getBet());
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.CALL,better.getBet(),better.getCash())));
// System.out.println("BROADCAST CALL");
break;
case RAISE:
better.bet(move.getBet());
raiseBet(better.getBet());
firstBetter=better;
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.RAISE,better.getBet(),better.getCash())));
// System.out.println("BROADCAST RAISE ("+better.getBet()+"$)");
break;
case EXIT:
better.Fold();
better.toggleInGame();
room.Broadcast(new PlayerMoveCommand(new PlayerMove(better.getId(),ClientTurn.EXIT,better.getBet(),better.getCash())));
// System.out.println("BROADCAST FOLD");
room.removeUser(better.getId());
players.removePlayer(better.getId());
}
if(players.playersLeft().size()<2&&players.playersHaveToMove().size()<2){
endGame();
break;
}
}
better=players.getNextPlayer(better);
}while (better!=firstBetter&&!endGame);
if(!endGame){
switch (state){
case 0:
table.add(deck.getTopCard());
table.add(deck.getTopCard());
table.add(deck.getTopCard());
room.Broadcast(new FlopCommand(table.get(0), table.get(1), table.get(2)));
System.out.println("BROADCAST FLOP " + table.get(0).toSymbol() + " " + table.get(1).toSymbol() + " " + table.get(2).toSymbol());
state++;
break;
case 1:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(3), TurnRiverCommand.RorT.TURN));
System.out.println("BROADCAST TURN "+table.get(3).toSymbol());
state++;
break;
case 2:
deck.getTopCard();
table.add(deck.getTopCard());
room.Broadcast(new TurnRiverCommand(table.get(4), TurnRiverCommand.RorT.RIVER));
System.out.println("BROADCAST RIVER "+table.get(4).toSymbol());
state++;
break;
default:
state++;
}
}
}
endGame();
}
}
|
diff --git a/gxt3-miglayout/src/main/java/net/miginfocom/layout/gxt3/GxtContainerWrapper.java b/gxt3-miglayout/src/main/java/net/miginfocom/layout/gxt3/GxtContainerWrapper.java
index d2c7db5..9596600 100644
--- a/gxt3-miglayout/src/main/java/net/miginfocom/layout/gxt3/GxtContainerWrapper.java
+++ b/gxt3-miglayout/src/main/java/net/miginfocom/layout/gxt3/GxtContainerWrapper.java
@@ -1,111 +1,111 @@
/*
* Copyright (c) 2013, Harald Westphal
* All rights reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions are met:
* * Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
* * Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in the
* documentation and/or other materials provided with the distribution.
* * Neither the name of the author nor the
* names of its contributors may be used to endorse or promote products
* derived from this software without specific prior written permission.
*
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
* AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
* IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
* ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR ANY
* DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
* (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
* SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER
* CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT
* LIABILITY, OR TORT(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY
* OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH
* DAMAGE.
*/
package net.miginfocom.layout.gxt3;
import java.util.ArrayList;
import java.util.List;
import net.miginfocom.layout.ComponentWrapper;
import net.miginfocom.layout.ContainerWrapper;
import com.google.gwt.dom.client.Style;
import com.google.gwt.dom.client.Style.BorderStyle;
import com.google.gwt.dom.client.Style.Position;
import com.google.gwt.dom.client.Style.Unit;
import com.google.gwt.user.client.Element;
import com.google.gwt.user.client.ui.Widget;
import com.sencha.gxt.core.client.dom.XElement;
class GxtContainerWrapper extends GxtComponentWrapper implements ContainerWrapper {
private final MigLayoutContainer container;
private final List<XElement> debugOverlays = new ArrayList<XElement>();
GxtContainerWrapper(MigLayoutContainer container) {
super(container);
this.container = container;
}
@Override
public ComponentWrapper[] getComponents() {
return container.getComponents();
}
@Override
public int getComponentCount() {
return container.getWidgetCount();
}
@Override
public Object getLayout() {
return container;
}
@Override
public boolean isLeftToRight() {
// TODO support RTL containers
return true;
}
@Override
public void paintDebugOutline() {
removeDebugOverlays();
paintDebug(0, 0, container.getOffsetWidth(true), container.getOffsetHeight(true), "blue");
}
private void removeDebugOverlays() {
Element root = container.getElement();
for (Element overlay : debugOverlays) {
root.removeChild(overlay);
}
debugOverlays.clear();
}
@Override
public void paintDebugCell(int x, int y, int width, int height) {
paintDebug(x, y, width, height, "red");
}
void applyLayout(Widget widget, int x, int y, int width, int height) {
container.applyLayout(widget, x, y, width, height);
}
void paintDebug(int x, int y, int width, int height, String color) {
XElement overlay = XElement.createElement("div");
Style style = overlay.getStyle();
style.setPosition(Position.ABSOLUTE);
style.setBorderColor(color);
style.setBorderStyle(BorderStyle.DASHED);
style.setBorderWidth(1, Unit.PX);
style.setProperty("pointerEvents", "none");
- overlay.setBounds(x + 1, y + 1, width - 2, height - 2);
+ overlay.setBounds(x, y, width - 2, height - 2);
container.getElement().appendChild(overlay);
debugOverlays.add(overlay);
}
}
| true | true | void paintDebug(int x, int y, int width, int height, String color) {
XElement overlay = XElement.createElement("div");
Style style = overlay.getStyle();
style.setPosition(Position.ABSOLUTE);
style.setBorderColor(color);
style.setBorderStyle(BorderStyle.DASHED);
style.setBorderWidth(1, Unit.PX);
style.setProperty("pointerEvents", "none");
overlay.setBounds(x + 1, y + 1, width - 2, height - 2);
container.getElement().appendChild(overlay);
debugOverlays.add(overlay);
}
| void paintDebug(int x, int y, int width, int height, String color) {
XElement overlay = XElement.createElement("div");
Style style = overlay.getStyle();
style.setPosition(Position.ABSOLUTE);
style.setBorderColor(color);
style.setBorderStyle(BorderStyle.DASHED);
style.setBorderWidth(1, Unit.PX);
style.setProperty("pointerEvents", "none");
overlay.setBounds(x, y, width - 2, height - 2);
container.getElement().appendChild(overlay);
debugOverlays.add(overlay);
}
|
diff --git a/src/main/java/com/twobytes/util/DocRunningUtil.java b/src/main/java/com/twobytes/util/DocRunningUtil.java
index 989e421..afffee5 100644
--- a/src/main/java/com/twobytes/util/DocRunningUtil.java
+++ b/src/main/java/com/twobytes/util/DocRunningUtil.java
@@ -1,113 +1,113 @@
package com.twobytes.util;
import java.util.Calendar;
import java.util.Locale;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import com.twobytes.master.service.DocRunningService;
import com.twobytes.model.DocRunning;
@Component("docRunningUtil")
public class DocRunningUtil {
@Autowired
private DocRunningService docRunningService;
public String genDoc(String document){
if(document.equals("SO")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
String docNo = "";
Integer nMonth = now.get(Calendar.MONTH) + 1;
Integer nYear = now.get(Calendar.YEAR);
Integer nDate = now.get(Calendar.DATE);
DocRunning docRunning = docRunningService.getDocByYearMonthDate("SO", nYear, nMonth, nDate);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("SO");
docRunning.setPrefix("so");
docRunning.setMonth(now.get(Calendar.MONTH) + 1);
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setDate(now.get(Calendar.DATE));
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
String month = docRunning.getMonth().toString();
if(month.length() == 1){
month = "0"+month;
}
String year = docRunning.getYear().toString();
year = year.substring(2, 4);
String date = docRunning.getDate().toString();
if(date.length() == 1){
date = "0"+date;
}
// docNo = docRunning.getPrefix()+"-"+year+month+"-"+docRunning.getRunningNumber();
docNo = year+month+date+"-"+docRunning.getRunningNumber();
// increse running no
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else if(document.equals("customer")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
Integer nYear = now.get(Calendar.YEAR);
String docNo = "";
DocRunning docRunning = docRunningService.getDocByYear("customer", nYear);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("customer");
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
Integer year = docRunning.getYear();
// convert to thai
year = year+543;
docNo = year.toString().substring(2,4)+StringUtils.leftPad(docRunning.getRunningNumber().toString(),8,"0");
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else if(document.equals("computer")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
Integer nYear = now.get(Calendar.YEAR);
Integer nMonth = now.get(Calendar.MONTH) + 1;
String docNo = "";
- DocRunning docRunning = docRunningService.getDocByYearMonth("SO", nYear, nMonth);
+ DocRunning docRunning = docRunningService.getDocByYearMonth("computer", nYear, nMonth);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("computer");
docRunning.setPrefix("COM");
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setMonth(now.get(Calendar.MONTH) + 1);
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
String month = docRunning.getMonth().toString();
if(month.length() == 1){
month = "0"+month;
}
Integer year = docRunning.getYear();
// convert to thai
year = year+543;
docNo = docRunning.getPrefix()+"-"+year.toString().substring(2,4)+month+"-"+docRunning.getRunningNumber();
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else{
return "Not support document";
}
}
}
| true | true | public String genDoc(String document){
if(document.equals("SO")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
String docNo = "";
Integer nMonth = now.get(Calendar.MONTH) + 1;
Integer nYear = now.get(Calendar.YEAR);
Integer nDate = now.get(Calendar.DATE);
DocRunning docRunning = docRunningService.getDocByYearMonthDate("SO", nYear, nMonth, nDate);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("SO");
docRunning.setPrefix("so");
docRunning.setMonth(now.get(Calendar.MONTH) + 1);
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setDate(now.get(Calendar.DATE));
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
String month = docRunning.getMonth().toString();
if(month.length() == 1){
month = "0"+month;
}
String year = docRunning.getYear().toString();
year = year.substring(2, 4);
String date = docRunning.getDate().toString();
if(date.length() == 1){
date = "0"+date;
}
// docNo = docRunning.getPrefix()+"-"+year+month+"-"+docRunning.getRunningNumber();
docNo = year+month+date+"-"+docRunning.getRunningNumber();
// increse running no
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else if(document.equals("customer")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
Integer nYear = now.get(Calendar.YEAR);
String docNo = "";
DocRunning docRunning = docRunningService.getDocByYear("customer", nYear);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("customer");
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
Integer year = docRunning.getYear();
// convert to thai
year = year+543;
docNo = year.toString().substring(2,4)+StringUtils.leftPad(docRunning.getRunningNumber().toString(),8,"0");
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else if(document.equals("computer")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
Integer nYear = now.get(Calendar.YEAR);
Integer nMonth = now.get(Calendar.MONTH) + 1;
String docNo = "";
DocRunning docRunning = docRunningService.getDocByYearMonth("SO", nYear, nMonth);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("computer");
docRunning.setPrefix("COM");
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setMonth(now.get(Calendar.MONTH) + 1);
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
String month = docRunning.getMonth().toString();
if(month.length() == 1){
month = "0"+month;
}
Integer year = docRunning.getYear();
// convert to thai
year = year+543;
docNo = docRunning.getPrefix()+"-"+year.toString().substring(2,4)+month+"-"+docRunning.getRunningNumber();
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else{
return "Not support document";
}
}
| public String genDoc(String document){
if(document.equals("SO")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
String docNo = "";
Integer nMonth = now.get(Calendar.MONTH) + 1;
Integer nYear = now.get(Calendar.YEAR);
Integer nDate = now.get(Calendar.DATE);
DocRunning docRunning = docRunningService.getDocByYearMonthDate("SO", nYear, nMonth, nDate);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("SO");
docRunning.setPrefix("so");
docRunning.setMonth(now.get(Calendar.MONTH) + 1);
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setDate(now.get(Calendar.DATE));
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
String month = docRunning.getMonth().toString();
if(month.length() == 1){
month = "0"+month;
}
String year = docRunning.getYear().toString();
year = year.substring(2, 4);
String date = docRunning.getDate().toString();
if(date.length() == 1){
date = "0"+date;
}
// docNo = docRunning.getPrefix()+"-"+year+month+"-"+docRunning.getRunningNumber();
docNo = year+month+date+"-"+docRunning.getRunningNumber();
// increse running no
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else if(document.equals("customer")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
Integer nYear = now.get(Calendar.YEAR);
String docNo = "";
DocRunning docRunning = docRunningService.getDocByYear("customer", nYear);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("customer");
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
Integer year = docRunning.getYear();
// convert to thai
year = year+543;
docNo = year.toString().substring(2,4)+StringUtils.leftPad(docRunning.getRunningNumber().toString(),8,"0");
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else if(document.equals("computer")){
Calendar now = Calendar.getInstance(new Locale ( "US" ));
Integer nYear = now.get(Calendar.YEAR);
Integer nMonth = now.get(Calendar.MONTH) + 1;
String docNo = "";
DocRunning docRunning = docRunningService.getDocByYearMonth("computer", nYear, nMonth);
if(null == docRunning){
// save new docrunning
docRunning = new DocRunning();
docRunning.setDocument("computer");
docRunning.setPrefix("COM");
docRunning.setYear(now.get(Calendar.YEAR));
docRunning.setMonth(now.get(Calendar.MONTH) + 1);
docRunning.setRunningNumber(1);
docRunningService.createNewDocRunning(docRunning);
}
String month = docRunning.getMonth().toString();
if(month.length() == 1){
month = "0"+month;
}
Integer year = docRunning.getYear();
// convert to thai
year = year+543;
docNo = docRunning.getPrefix()+"-"+year.toString().substring(2,4)+month+"-"+docRunning.getRunningNumber();
docRunning.setRunningNumber(docRunning.getRunningNumber()+1);
docRunningService.updateDocRunning(docRunning);
return docNo;
}else{
return "Not support document";
}
}
|
diff --git a/webmacro/src/org/webmacro/resource/DelegatingTemplateProvider.java b/webmacro/src/org/webmacro/resource/DelegatingTemplateProvider.java
index 09b9fefc..a34601af 100755
--- a/webmacro/src/org/webmacro/resource/DelegatingTemplateProvider.java
+++ b/webmacro/src/org/webmacro/resource/DelegatingTemplateProvider.java
@@ -1,148 +1,148 @@
/*
* Copyright (C) 1998-2000 Semiotek Inc. All Rights Reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted under the terms of either of the following
* Open Source licenses:
*
* The GNU General Public License, version 2, or any later version, as
* published by the Free Software Foundation
* (http://www.fsf.org/copyleft/gpl.html);
*
* or
*
* The Semiotek Public License (http://webmacro.org/LICENSE.)
*
* This software is provided "as is", with NO WARRANTY, not even the
* implied warranties of fitness to purpose, or merchantability. You
* assume all risks and liabilities associated with its use.
*
* See www.webmacro.org for more information on the WebMacro project.
*/
package org.webmacro.resource;
import org.webmacro.*;
import org.webmacro.util.Settings;
import java.util.List;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Arrays;
/**
* Alternative implementation of a TemplateProvider that uses TemplateLoaders to do the actual work.
* This template provider controls a list of TemplateLoaders to do the actual work of loading
* a template. It asks the template loaders one by one, until a template is found or the end of
* the list is reached. It is configured by a list of "TemplateLoaderPath.n" settings in
* WebMacro.properties.<br>
* <br>
* Each template loader is described by an url like syntax with a TemplateLoaderPath.n setting,
* where n should be a number starting from one.
* <br>
* Each template loader path is of the form "[protocol:][path]". If the protocol part in square brackets
* is ommited, "default:" is assumed.
* For each protocol, a "TemplateLoader.protocol" setting must give the fully qualified
* classname of the template loader to be used for this protocol.
* Example configuration:<br>
* <pre>
* TemplateLoaderPath.1=.
* TemplateLoaderPath.2=classpath:
* TemplateLoaderPath.3=webapp:/WEB-INF/templates/
* TemplateLoader.default=org.webmacro.resource.FileTemplateLoader
* TemplateLoader.classpath=org.webmacro.resource.ClassPathTemplateLoader
* TemplateLoader.webapp=org.webmacro.resource.ServletContextTemplateLoader
* </pre>
* This configuration will search for templates at three locations in this order:
* <ol>
* <li>The current directory (".")
* <li>The classpath (classpath:)
* <li>The directory WEB-INF/templates/ in the web-app directory ("webapp:/WEB-INF/templates/")
* </ol>
* Note, that this setup only makes sense in a web-app environment, because the webapp template loader
* won't work otherwise.
* @author Sebastian Kanthak ([email protected])
*/
public class DelegatingTemplateProvider extends CachingProvider {
private Broker broker;
private Log log;
private TemplateLoaderFactory factory;
private TemplateLoader[] templateLoaders;
public void init(Broker broker,Settings config) throws InitException {
super.init(broker,config);
this.broker = broker;
log = broker.getLog("resource","DelegatingTemplateProvider");
String factoryClass = config.getSetting("TemplateLoaderFactory","");
log.info("DelegatingTemplateProvider: Using TemplateLoaderFactory "+factoryClass);
factory = createFactory(factoryClass);
List loaders = new ArrayList();
// for compatability reasons, check old TemplatePath setting
if (config.getBooleanSetting("DelegatingTemplateProvider.EmulateTemplatePath",false)) {
- if (config.getSetting("TemplatePath").length() > 0) {
+ if (config.getSetting("TemplatePath","").length() > 0) {
TemplateLoader loader = new TemplatePathTemplateLoader();
loader.init(broker,config);
loader.setConfig("");
loaders.add(loader);
}
}
int i = 0;
String loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1)));
while (loader != null) {
loaders.add(factory.getTemplateLoader(broker,loader));
i++;
loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1)));
}
templateLoaders = new TemplateLoader[loaders.size()];
loaders.toArray(templateLoaders);
}
public String getType() {
return "template";
}
/**
* Ask all template loaders to load a template from query.
* Returns the template from the first provider, that returns a non-null value
* or throws a NotFoundException, if all providers return null.
*/
public Object load(String query,CacheElement ce) throws ResourceException {
for (int i=0; i < templateLoaders.length; i++) {
Template t = templateLoaders[i].load(query,ce);
if (t != null) {
return t;
}
}
throw new NotFoundException("Could not locate template "+query);
}
/**
* Returns an unmodifieable list of this provider's template loaders.
* The list is has the same order used for searching templates. You may
* use this method to access template loaders and change their settings
* at runtime if they have an appropriate method.
* @return unmodifieable list of TemplateLoader objects
*/
public List getTemplateLoaders() {
return Collections.unmodifiableList(Arrays.asList(templateLoaders));
}
protected TemplateLoaderFactory createFactory(String classname) throws InitException {
try {
return (TemplateLoaderFactory)Class.forName(classname).newInstance();
} catch (ClassNotFoundException e) {
throw new InitException("Class "+classname+" for template loader factory not found",e);
} catch (InstantiationException e) {
throw new InitException("Could not instantiate class "+classname+" for template loader factory",e);
} catch (IllegalAccessException e) {
throw new InitException("Could not instantiate class "+classname+" for template loader facory",e);
} catch (ClassCastException e) {
throw new InitException("Class "+classname+" for template loader factory does not implement "+
"interface org.webmacro.resource.TemplateLoaderFactory",e);
}
}
}
| true | true | public void init(Broker broker,Settings config) throws InitException {
super.init(broker,config);
this.broker = broker;
log = broker.getLog("resource","DelegatingTemplateProvider");
String factoryClass = config.getSetting("TemplateLoaderFactory","");
log.info("DelegatingTemplateProvider: Using TemplateLoaderFactory "+factoryClass);
factory = createFactory(factoryClass);
List loaders = new ArrayList();
// for compatability reasons, check old TemplatePath setting
if (config.getBooleanSetting("DelegatingTemplateProvider.EmulateTemplatePath",false)) {
if (config.getSetting("TemplatePath").length() > 0) {
TemplateLoader loader = new TemplatePathTemplateLoader();
loader.init(broker,config);
loader.setConfig("");
loaders.add(loader);
}
}
int i = 0;
String loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1)));
while (loader != null) {
loaders.add(factory.getTemplateLoader(broker,loader));
i++;
loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1)));
}
templateLoaders = new TemplateLoader[loaders.size()];
loaders.toArray(templateLoaders);
}
| public void init(Broker broker,Settings config) throws InitException {
super.init(broker,config);
this.broker = broker;
log = broker.getLog("resource","DelegatingTemplateProvider");
String factoryClass = config.getSetting("TemplateLoaderFactory","");
log.info("DelegatingTemplateProvider: Using TemplateLoaderFactory "+factoryClass);
factory = createFactory(factoryClass);
List loaders = new ArrayList();
// for compatability reasons, check old TemplatePath setting
if (config.getBooleanSetting("DelegatingTemplateProvider.EmulateTemplatePath",false)) {
if (config.getSetting("TemplatePath","").length() > 0) {
TemplateLoader loader = new TemplatePathTemplateLoader();
loader.init(broker,config);
loader.setConfig("");
loaders.add(loader);
}
}
int i = 0;
String loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1)));
while (loader != null) {
loaders.add(factory.getTemplateLoader(broker,loader));
i++;
loader = config.getSetting("TemplateLoaderPath.".concat(String.valueOf(i+1)));
}
templateLoaders = new TemplateLoader[loaders.size()];
loaders.toArray(templateLoaders);
}
|
diff --git a/src/main/java/ru/tehkode/permissions/backends/FileBackend.java b/src/main/java/ru/tehkode/permissions/backends/FileBackend.java
index 261858a..c81d10c 100644
--- a/src/main/java/ru/tehkode/permissions/backends/FileBackend.java
+++ b/src/main/java/ru/tehkode/permissions/backends/FileBackend.java
@@ -1,431 +1,431 @@
/*
* PermissionsEx - Permissions plugin for Bukkit
* Copyright (C) 2011 t3hk0d3 http://www.tehkode.ru
*
* 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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
*/
package ru.tehkode.permissions.backends;
import java.io.File;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import org.bukkit.Bukkit;
import org.bukkit.World;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import org.yaml.snakeyaml.constructor.SafeConstructor;
import org.yaml.snakeyaml.representer.Representer;
import ru.tehkode.permissions.PermissionBackend;
import ru.tehkode.permissions.PermissionGroup;
import ru.tehkode.permissions.PermissionManager;
import ru.tehkode.permissions.PermissionUser;
import ru.tehkode.permissions.config.Configuration;
import ru.tehkode.permissions.config.ConfigurationNode;
import ru.tehkode.permissions.backends.file.FileGroup;
import ru.tehkode.permissions.backends.file.FileUser;
/**
*
* @author code
*/
public class FileBackend extends PermissionBackend {
public Configuration permissions;
protected boolean spamUserRecords = false;
public FileBackend(PermissionManager manager, Configuration config) {
super(manager, config);
}
@Override
public void initialize() {
String permissionFilename = config.getString("permissions.backends.file.file");
// Default settings
if (permissionFilename == null) {
permissionFilename = "permissions.yml";
config.setProperty("permissions.backends.file.file", "permissions.yml");
config.save();
}
String baseDir = config.getString("permissions.basedir");
if (baseDir.contains("\\") && !"\\".equals(File.separator)) {
baseDir = baseDir.replace("\\", File.separator);
}
File baseDirectory = new File(baseDir);
if (!baseDirectory.exists()) {
baseDirectory.mkdirs();
}
File permissionFile = new File(baseDir, permissionFilename);
permissions = new Configuration(permissionFile);
if (!permissionFile.exists()) {
try {
permissionFile.createNewFile();
// Load default permissions
permissions.setProperty("groups.default.default", true);
List<String> defaultPermissions = new LinkedList<String>();
// Specify here default permissions
defaultPermissions.add("modifyworld.*");
permissions.setProperty("groups.default.permissions", defaultPermissions);
permissions.save();
} catch (IOException e) {
throw new RuntimeException(e);
}
}
this.spamUserRecords = config.getBoolean("permissions.backends.file.userSpam", this.spamUserRecords);
permissions.load();
}
public boolean doUserRecordsSpamming(){
return this.spamUserRecords;
}
@Override
public String[] getWorldInheritance(String world) {
if (world != null && !world.isEmpty()) {
return this.permissions.getStringList("worlds.`" + world + "`.inheritance", new LinkedList<String>()).toArray(new String[0]);
}
return new String[0];
}
@Override
public void setWorldInheritance(String world, String[] parentWorlds) {
if (world == null && world.isEmpty()) {
return;
}
this.permissions.setProperty("worlds.`" + world + "`.inheritance", Arrays.asList(parentWorlds));
this.permissions.save();
}
@Override
public PermissionUser getUser(String userName) {
return new FileUser(userName, manager, this);
}
@Override
public PermissionGroup getGroup(String groupName) {
return new FileGroup(groupName, manager, this);
}
@Override
public PermissionGroup getDefaultGroup(String worldName) {
Map<String, ConfigurationNode> groupsMap = this.permissions.getNodesMap("groups");
if (groupsMap == null || groupsMap.isEmpty()) {
throw new RuntimeException("No groups defined. Check your permissions file.");
}
String defaultGroupProperty = "default";
if (worldName != null) {
defaultGroupProperty = "worlds.`" + worldName + "`." + defaultGroupProperty;
}
for (Map.Entry<String, ConfigurationNode> entry : groupsMap.entrySet()) {
Object property = entry.getValue().getProperty(defaultGroupProperty);
if(property instanceof Boolean && ((Boolean)property)){
return this.manager.getGroup(entry.getKey());
}
}
if (worldName == null) {
throw new RuntimeException("Default user group are not defined. Please select one using \"default: true\" property");
}
return null;
}
@Override
public void setDefaultGroup(PermissionGroup group, String worldName) {
Map<String, ConfigurationNode> groupsMap = this.permissions.getNodesMap("groups");
String defaultGroupProperty = "default";
if (worldName != null) {
defaultGroupProperty = "worlds.`" + worldName + "`." + defaultGroupProperty;
}
for (Map.Entry<String, ConfigurationNode> entry : groupsMap.entrySet()) {
if (!entry.getKey().equalsIgnoreCase(group.getName())
&& entry.getValue().getProperty(defaultGroupProperty) != null) {
entry.getValue().removeProperty(defaultGroupProperty);
}
if (entry.getKey().equalsIgnoreCase(group.getName())) {
entry.getValue().setProperty(defaultGroupProperty, true);
}
}
this.permissions.save();
}
@Override
public PermissionGroup[] getGroups() {
List<PermissionGroup> groups = new LinkedList<PermissionGroup>();
Map<String, ConfigurationNode> groupsMap = this.permissions.getNodesMap("groups");
for (String groupName : groupsMap.keySet()) {
groups.add(this.manager.getGroup(groupName));
}
Collections.sort(groups);
return groups.toArray(new PermissionGroup[0]);
}
@Override
public PermissionUser[] getRegisteredUsers() {
List<PermissionUser> users = new LinkedList<PermissionUser>();
Map<String, ConfigurationNode> userMap = this.permissions.getNodesMap("users");
if (userMap != null) {
for (Map.Entry<String, ConfigurationNode> entry : userMap.entrySet()) {
users.add(this.manager.getUser(entry.getKey()));
}
}
return users.toArray(new PermissionUser[]{});
}
@Override
public void reload() {
this.permissions.load();
}
public static Map<String, String> collectOptions(Map<String, Object> root) {
return collectOptions(root, "", new HashMap<String, String>());
}
protected static Map<String, String> collectOptions(Map<String, Object> root, String baseKey, Map<String, String> collector) {
for (Map.Entry<String, Object> entry : root.entrySet()) {
String newKey = entry.getKey();
if (baseKey != null && !baseKey.isEmpty()) {
newKey = baseKey + "." + newKey;
}
if (entry.getValue() instanceof Map) {
Map<String, Object> map = (Map<String, Object>) entry.getValue();
collectOptions(map, newKey, collector);
} else if (entry.getValue() instanceof ConfigurationNode) {
collectOptions(((ConfigurationNode) entry.getValue()).getRoot(), newKey, collector);
} else {
collector.put(newKey, (String) entry.getValue());
}
}
return collector;
}
@Override
public void dumpData(OutputStreamWriter writer) throws IOException {
DumperOptions options = new DumperOptions();
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), options);
ConfigurationNode root = new ConfigurationNode();
// Users setup
for (PermissionUser user : this.manager.getUsers()) {
ConfigurationNode userNode = new ConfigurationNode();
// Inheritance
if (user.getGroupsNames().length > 0) {
userNode.setProperty("group", Arrays.asList(user.getGroupsNames()));
}
// Prefix
if (user.getOwnPrefix() != null && !user.getOwnPrefix().isEmpty()) {
userNode.setProperty("prefix", user.getOwnPrefix());
}
//Suffix
if (user.getOwnSuffix() != null && !user.getOwnSuffix().isEmpty()) {
userNode.setProperty("suffix", user.getOwnSuffix());
}
// Permissions
for (Map.Entry<String, String[]> entry : user.getAllPermissions().entrySet()) {
if (entry.getValue().length == 0) continue;
String nodePath = "permissions";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
userNode.setProperty(nodePath, Arrays.asList(entry.getValue()));
}
// Options
for (Map.Entry<String, Map<String, String>> entry : user.getAllOptions().entrySet()) {
if(entry.getValue().isEmpty()) continue;
String nodePath = "options";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
userNode.setProperty(nodePath, entry.getValue());
}
// world-specific inheritance
for(Map.Entry<String, PermissionGroup[]> entry : user.getAllGroups().entrySet()){
if(entry.getKey() == null) continue;
List<String> groups = new ArrayList<String>();
for(PermissionGroup group : entry.getValue()){
if(group == null){ continue; }
groups.add(group.getName());
}
if(groups.isEmpty()) continue;
userNode.setProperty("worlds.`" + entry.getKey() + "`.group", groups);
}
// world specific stuff
for (String worldName : user.getWorlds()){
if(worldName == null) continue;
String worldPath = "worlds.`" + worldName + "`.";
// world-specific prefix
String prefix = user.getOwnPrefix(worldName);
if(prefix != null && !prefix.isEmpty()){
userNode.setProperty(worldPath + "prefix", prefix);
}
String suffix = user.getOwnSuffix(worldName);
if(suffix != null && !suffix.isEmpty()){
userNode.setProperty(worldPath + "suffix", suffix);
}
}
root.setProperty("users.`" + user.getName() + "`", userNode);
}
// Groups
for (PermissionGroup group : this.manager.getGroups()) {
ConfigurationNode groupNode = new ConfigurationNode();
// Inheritance
if (group.getParentGroupsNames().length > 0) {
- groupNode.setProperty("groups.`" + group.getName() + "`.inheritance", Arrays.asList(group.getParentGroupsNames()));
+ groupNode.setProperty("inheritance", Arrays.asList(group.getParentGroupsNames()));
}
// Prefix
if (group.getOwnPrefix() != null && !group.getOwnPrefix().isEmpty()) {
groupNode.setProperty("prefix", group.getOwnPrefix());
}
//Suffix
if (group.getOwnSuffix() != null && !group.getOwnSuffix().isEmpty()) {
groupNode.setProperty("suffix", group.getOwnSuffix());
}
// Permissions
for (Map.Entry<String, String[]> entry : group.getAllPermissions().entrySet()) {
if (entry.getValue().length == 0) continue;
String nodePath = "permissions";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
groupNode.setProperty(nodePath, Arrays.asList(entry.getValue()));
}
// Options
for (Map.Entry<String, Map<String, String>> entry : group.getAllOptions().entrySet()) {
if(entry.getValue().isEmpty()) continue;
String nodePath = "options";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
groupNode.setProperty(nodePath, entry.getValue());
}
// world-specific inheritance
for(Map.Entry<String, PermissionGroup[]> entry : group.getAllParentGroups().entrySet()){
if(entry.getKey() == null) continue;
List<String> groups = new ArrayList<String>();
for(PermissionGroup parentGroup : entry.getValue()){
if(parentGroup == null){ continue; }
groups.add(parentGroup.getName());
}
if(groups.isEmpty()) continue;
groupNode.setProperty("worlds.`" + entry.getKey() + "`.inheritance", groups);
}
// world specific stuff
for (String worldName : group.getWorlds()){
if(worldName == null) continue;
String worldPath = "worlds.`" + worldName + "`.";
// world-specific prefix
String prefix = group.getOwnPrefix(worldName);
if(prefix != null && !prefix.isEmpty()){
groupNode.setProperty(worldPath + "prefix", prefix);
}
String suffix = group.getOwnSuffix(worldName);
if(suffix != null && !suffix.isEmpty()){
groupNode.setProperty(worldPath + "suffix", suffix);
}
}
root.setProperty("groups.`" + group.getName() + "`", groupNode);
}
// World inheritance
for (World world : Bukkit.getServer().getWorlds()) {
String[] parentWorlds = manager.getWorldInheritance(world.getName());
if (parentWorlds.length == 0) {
continue;
}
root.setProperty("worlds.`" + world.getName() + "`.inheritance", Arrays.asList(parentWorlds));
}
// Write data to writer
yaml.dump(root.getRoot(), writer);
}
}
| true | true | public void dumpData(OutputStreamWriter writer) throws IOException {
DumperOptions options = new DumperOptions();
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), options);
ConfigurationNode root = new ConfigurationNode();
// Users setup
for (PermissionUser user : this.manager.getUsers()) {
ConfigurationNode userNode = new ConfigurationNode();
// Inheritance
if (user.getGroupsNames().length > 0) {
userNode.setProperty("group", Arrays.asList(user.getGroupsNames()));
}
// Prefix
if (user.getOwnPrefix() != null && !user.getOwnPrefix().isEmpty()) {
userNode.setProperty("prefix", user.getOwnPrefix());
}
//Suffix
if (user.getOwnSuffix() != null && !user.getOwnSuffix().isEmpty()) {
userNode.setProperty("suffix", user.getOwnSuffix());
}
// Permissions
for (Map.Entry<String, String[]> entry : user.getAllPermissions().entrySet()) {
if (entry.getValue().length == 0) continue;
String nodePath = "permissions";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
userNode.setProperty(nodePath, Arrays.asList(entry.getValue()));
}
// Options
for (Map.Entry<String, Map<String, String>> entry : user.getAllOptions().entrySet()) {
if(entry.getValue().isEmpty()) continue;
String nodePath = "options";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
userNode.setProperty(nodePath, entry.getValue());
}
// world-specific inheritance
for(Map.Entry<String, PermissionGroup[]> entry : user.getAllGroups().entrySet()){
if(entry.getKey() == null) continue;
List<String> groups = new ArrayList<String>();
for(PermissionGroup group : entry.getValue()){
if(group == null){ continue; }
groups.add(group.getName());
}
if(groups.isEmpty()) continue;
userNode.setProperty("worlds.`" + entry.getKey() + "`.group", groups);
}
// world specific stuff
for (String worldName : user.getWorlds()){
if(worldName == null) continue;
String worldPath = "worlds.`" + worldName + "`.";
// world-specific prefix
String prefix = user.getOwnPrefix(worldName);
if(prefix != null && !prefix.isEmpty()){
userNode.setProperty(worldPath + "prefix", prefix);
}
String suffix = user.getOwnSuffix(worldName);
if(suffix != null && !suffix.isEmpty()){
userNode.setProperty(worldPath + "suffix", suffix);
}
}
root.setProperty("users.`" + user.getName() + "`", userNode);
}
// Groups
for (PermissionGroup group : this.manager.getGroups()) {
ConfigurationNode groupNode = new ConfigurationNode();
// Inheritance
if (group.getParentGroupsNames().length > 0) {
groupNode.setProperty("groups.`" + group.getName() + "`.inheritance", Arrays.asList(group.getParentGroupsNames()));
}
// Prefix
if (group.getOwnPrefix() != null && !group.getOwnPrefix().isEmpty()) {
groupNode.setProperty("prefix", group.getOwnPrefix());
}
//Suffix
if (group.getOwnSuffix() != null && !group.getOwnSuffix().isEmpty()) {
groupNode.setProperty("suffix", group.getOwnSuffix());
}
// Permissions
for (Map.Entry<String, String[]> entry : group.getAllPermissions().entrySet()) {
if (entry.getValue().length == 0) continue;
String nodePath = "permissions";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
groupNode.setProperty(nodePath, Arrays.asList(entry.getValue()));
}
// Options
for (Map.Entry<String, Map<String, String>> entry : group.getAllOptions().entrySet()) {
if(entry.getValue().isEmpty()) continue;
String nodePath = "options";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
groupNode.setProperty(nodePath, entry.getValue());
}
// world-specific inheritance
for(Map.Entry<String, PermissionGroup[]> entry : group.getAllParentGroups().entrySet()){
if(entry.getKey() == null) continue;
List<String> groups = new ArrayList<String>();
for(PermissionGroup parentGroup : entry.getValue()){
if(parentGroup == null){ continue; }
groups.add(parentGroup.getName());
}
if(groups.isEmpty()) continue;
groupNode.setProperty("worlds.`" + entry.getKey() + "`.inheritance", groups);
}
// world specific stuff
for (String worldName : group.getWorlds()){
if(worldName == null) continue;
String worldPath = "worlds.`" + worldName + "`.";
// world-specific prefix
String prefix = group.getOwnPrefix(worldName);
if(prefix != null && !prefix.isEmpty()){
groupNode.setProperty(worldPath + "prefix", prefix);
}
String suffix = group.getOwnSuffix(worldName);
if(suffix != null && !suffix.isEmpty()){
groupNode.setProperty(worldPath + "suffix", suffix);
}
}
root.setProperty("groups.`" + group.getName() + "`", groupNode);
}
// World inheritance
for (World world : Bukkit.getServer().getWorlds()) {
String[] parentWorlds = manager.getWorldInheritance(world.getName());
if (parentWorlds.length == 0) {
continue;
}
root.setProperty("worlds.`" + world.getName() + "`.inheritance", Arrays.asList(parentWorlds));
}
// Write data to writer
yaml.dump(root.getRoot(), writer);
}
| public void dumpData(OutputStreamWriter writer) throws IOException {
DumperOptions options = new DumperOptions();
options.setIndent(4);
options.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(new SafeConstructor(), new Representer(), options);
ConfigurationNode root = new ConfigurationNode();
// Users setup
for (PermissionUser user : this.manager.getUsers()) {
ConfigurationNode userNode = new ConfigurationNode();
// Inheritance
if (user.getGroupsNames().length > 0) {
userNode.setProperty("group", Arrays.asList(user.getGroupsNames()));
}
// Prefix
if (user.getOwnPrefix() != null && !user.getOwnPrefix().isEmpty()) {
userNode.setProperty("prefix", user.getOwnPrefix());
}
//Suffix
if (user.getOwnSuffix() != null && !user.getOwnSuffix().isEmpty()) {
userNode.setProperty("suffix", user.getOwnSuffix());
}
// Permissions
for (Map.Entry<String, String[]> entry : user.getAllPermissions().entrySet()) {
if (entry.getValue().length == 0) continue;
String nodePath = "permissions";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
userNode.setProperty(nodePath, Arrays.asList(entry.getValue()));
}
// Options
for (Map.Entry<String, Map<String, String>> entry : user.getAllOptions().entrySet()) {
if(entry.getValue().isEmpty()) continue;
String nodePath = "options";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
userNode.setProperty(nodePath, entry.getValue());
}
// world-specific inheritance
for(Map.Entry<String, PermissionGroup[]> entry : user.getAllGroups().entrySet()){
if(entry.getKey() == null) continue;
List<String> groups = new ArrayList<String>();
for(PermissionGroup group : entry.getValue()){
if(group == null){ continue; }
groups.add(group.getName());
}
if(groups.isEmpty()) continue;
userNode.setProperty("worlds.`" + entry.getKey() + "`.group", groups);
}
// world specific stuff
for (String worldName : user.getWorlds()){
if(worldName == null) continue;
String worldPath = "worlds.`" + worldName + "`.";
// world-specific prefix
String prefix = user.getOwnPrefix(worldName);
if(prefix != null && !prefix.isEmpty()){
userNode.setProperty(worldPath + "prefix", prefix);
}
String suffix = user.getOwnSuffix(worldName);
if(suffix != null && !suffix.isEmpty()){
userNode.setProperty(worldPath + "suffix", suffix);
}
}
root.setProperty("users.`" + user.getName() + "`", userNode);
}
// Groups
for (PermissionGroup group : this.manager.getGroups()) {
ConfigurationNode groupNode = new ConfigurationNode();
// Inheritance
if (group.getParentGroupsNames().length > 0) {
groupNode.setProperty("inheritance", Arrays.asList(group.getParentGroupsNames()));
}
// Prefix
if (group.getOwnPrefix() != null && !group.getOwnPrefix().isEmpty()) {
groupNode.setProperty("prefix", group.getOwnPrefix());
}
//Suffix
if (group.getOwnSuffix() != null && !group.getOwnSuffix().isEmpty()) {
groupNode.setProperty("suffix", group.getOwnSuffix());
}
// Permissions
for (Map.Entry<String, String[]> entry : group.getAllPermissions().entrySet()) {
if (entry.getValue().length == 0) continue;
String nodePath = "permissions";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
groupNode.setProperty(nodePath, Arrays.asList(entry.getValue()));
}
// Options
for (Map.Entry<String, Map<String, String>> entry : group.getAllOptions().entrySet()) {
if(entry.getValue().isEmpty()) continue;
String nodePath = "options";
if (!entry.getKey().isEmpty()) {
nodePath = "worlds.`" + entry.getKey() + "`." + nodePath;
}
groupNode.setProperty(nodePath, entry.getValue());
}
// world-specific inheritance
for(Map.Entry<String, PermissionGroup[]> entry : group.getAllParentGroups().entrySet()){
if(entry.getKey() == null) continue;
List<String> groups = new ArrayList<String>();
for(PermissionGroup parentGroup : entry.getValue()){
if(parentGroup == null){ continue; }
groups.add(parentGroup.getName());
}
if(groups.isEmpty()) continue;
groupNode.setProperty("worlds.`" + entry.getKey() + "`.inheritance", groups);
}
// world specific stuff
for (String worldName : group.getWorlds()){
if(worldName == null) continue;
String worldPath = "worlds.`" + worldName + "`.";
// world-specific prefix
String prefix = group.getOwnPrefix(worldName);
if(prefix != null && !prefix.isEmpty()){
groupNode.setProperty(worldPath + "prefix", prefix);
}
String suffix = group.getOwnSuffix(worldName);
if(suffix != null && !suffix.isEmpty()){
groupNode.setProperty(worldPath + "suffix", suffix);
}
}
root.setProperty("groups.`" + group.getName() + "`", groupNode);
}
// World inheritance
for (World world : Bukkit.getServer().getWorlds()) {
String[] parentWorlds = manager.getWorldInheritance(world.getName());
if (parentWorlds.length == 0) {
continue;
}
root.setProperty("worlds.`" + world.getName() + "`.inheritance", Arrays.asList(parentWorlds));
}
// Write data to writer
yaml.dump(root.getRoot(), writer);
}
|
diff --git a/bgBanking/src/eu/masconsult/bgbanking/activity/HomeActivity.java b/bgBanking/src/eu/masconsult/bgbanking/activity/HomeActivity.java
index f43bee7..429103c 100644
--- a/bgBanking/src/eu/masconsult/bgbanking/activity/HomeActivity.java
+++ b/bgBanking/src/eu/masconsult/bgbanking/activity/HomeActivity.java
@@ -1,209 +1,209 @@
/*******************************************************************************
* Copyright (c) 2012 MASConsult Ltd
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
******************************************************************************/
package eu.masconsult.bgbanking.activity;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.BroadcastReceiver;
import android.content.ContentResolver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Bundle;
import android.support.v4.app.FragmentManager;
import android.util.Log;
import android.view.Window;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.zubhium.ZubhiumSDK;
import eu.masconsult.bgbanking.BankingApplication;
import eu.masconsult.bgbanking.R;
import eu.masconsult.bgbanking.activity.fragment.AccountsListFragment;
import eu.masconsult.bgbanking.activity.fragment.ChooseAccountTypeFragment;
import eu.masconsult.bgbanking.banks.Bank;
import eu.masconsult.bgbanking.provider.BankingContract;
import eu.masconsult.bgbanking.sync.SyncAdapter;
public class HomeActivity extends SherlockFragmentActivity {
private static final String TAG = BankingApplication.TAG + "HomeActivity";
final BroadcastReceiver syncReceiver = new BroadcastReceiver() {
@Override
public void onReceive(Context context, Intent intent) {
if (SyncAdapter.START_SYNC.equals(intent.getAction())) {
syncStateChanged(true);
} else if (SyncAdapter.STOP_SYNC.equals(intent.getAction())) {
syncStateChanged(false);
}
}
};
private AccountManager accountManager;
@Override
protected void onCreate(Bundle arg0) {
super.onCreate(arg0);
enableZubhiumUpdates(this);
accountManager = AccountManager.get(this);
requestWindowFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
}
@Override
protected void onDestroy() {
disableZubhiumUpdates(this);
super.onDestroy();
}
// TODO: extract to some utility class
private static ZubhiumSDK getZubhiumSDK(Context context) {
BankingApplication globalContext = (BankingApplication) context.getApplicationContext();
return globalContext != null ? globalContext.getZubhiumSDK() : null;
}
// TODO: extract to some utility class
private static void enableZubhiumUpdates(Activity activity) {
ZubhiumSDK sdk = getZubhiumSDK(activity);
if (sdk != null) {
/**
* Lets register kill switch / update receiver Read more :
* https://www.zubhium.com/docs/sendmessage/
*/
sdk.registerUpdateReceiver(activity);
}
}
// TODO: extract to some utility class
private static void disableZubhiumUpdates(Activity activity) {
ZubhiumSDK sdk = getZubhiumSDK(activity);
if (sdk != null) {
sdk.unRegisterUpdateReceiver();
}
}
@Override
protected void onStart() {
super.onStart();
checkForLoggedAccounts();
FragmentManager fm = getSupportFragmentManager();
// Create the list fragment and add it as our sole content.
if (fm.findFragmentById(android.R.id.content) == null) {
AccountsListFragment list = new AccountsListFragment();
fm.beginTransaction().add(android.R.id.content, list).commit();
}
}
@Override
protected void onResume() {
super.onResume();
IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(SyncAdapter.START_SYNC);
intentFilter.addAction(SyncAdapter.STOP_SYNC);
registerReceiver(syncReceiver, intentFilter);
syncStateChanged(isSyncActive());
}
@Override
protected void onPause() {
unregisterReceiver(syncReceiver);
super.onPause();
}
protected void checkForLoggedAccounts() {
Bank[] banks = Bank.values();
String[] accountTypes = new String[banks.length];
boolean hasAccounts = false;
for (int i = 0; i < banks.length; i++) {
accountTypes[i] = banks[i].getAccountType(this);
if (accountManager.getAccountsByType(banks[i].getAccountType(this)).length > 0) {
hasAccounts = true;
}
}
if (!hasAccounts) {
addAccount();
}
}
void addAccount() {
ChooseAccountTypeFragment accountTypesFragment = new ChooseAccountTypeFragment();
accountTypesFragment.show(getSupportFragmentManager(), "AccountsDialog");
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem addAccountItem = menu.add("Add account");
addAccountItem.setIcon(R.drawable.ic_menu_add);
- addAccountItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
+ addAccountItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
addAccountItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
addAccount();
return true;
}
});
MenuItem sendFeedback = menu.add("Send feedback");
sendFeedback.setIcon(R.drawable.ic_menu_start_conversation);
sendFeedback.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
sendFeedback.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
getZubhiumSDK(HomeActivity.this).openFeedbackDialog(HomeActivity.this);
return true;
}
});
return true;
}
boolean isSyncActive() {
for (Bank bank : Bank.values()) {
for (Account account : accountManager.getAccountsByType(bank.getAccountType(this))) {
if (ContentResolver.isSyncActive(account, BankingContract.AUTHORITY)) {
Log.v(TAG, bank + " is syncing");
return true;
}
}
}
Log.v(TAG, "nothing is syncing");
return false;
}
void syncStateChanged(boolean syncActive) {
Log.v(TAG, "syncStateChanged: " + syncActive);
setProgressBarIndeterminateVisibility(syncActive);
}
}
| true | true | public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem addAccountItem = menu.add("Add account");
addAccountItem.setIcon(R.drawable.ic_menu_add);
addAccountItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_NEVER);
addAccountItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
addAccount();
return true;
}
});
MenuItem sendFeedback = menu.add("Send feedback");
sendFeedback.setIcon(R.drawable.ic_menu_start_conversation);
sendFeedback.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
sendFeedback.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
getZubhiumSDK(HomeActivity.this).openFeedbackDialog(HomeActivity.this);
return true;
}
});
return true;
}
| public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuItem addAccountItem = menu.add("Add account");
addAccountItem.setIcon(R.drawable.ic_menu_add);
addAccountItem.setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM);
addAccountItem.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
addAccount();
return true;
}
});
MenuItem sendFeedback = menu.add("Send feedback");
sendFeedback.setIcon(R.drawable.ic_menu_start_conversation);
sendFeedback.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
sendFeedback.setOnMenuItemClickListener(new MenuItem.OnMenuItemClickListener() {
@Override
public boolean onMenuItemClick(MenuItem item) {
getZubhiumSDK(HomeActivity.this).openFeedbackDialog(HomeActivity.this);
return true;
}
});
return true;
}
|
diff --git a/com.hilotec.elexis.kgview/src/com/hilotec/elexis/kgview/medikarte/MedikarteHelpers.java b/com.hilotec.elexis.kgview/src/com/hilotec/elexis/kgview/medikarte/MedikarteHelpers.java
index 2e71076..9c81289 100644
--- a/com.hilotec.elexis.kgview/src/com/hilotec/elexis/kgview/medikarte/MedikarteHelpers.java
+++ b/com.hilotec.elexis.kgview/src/com/hilotec/elexis/kgview/medikarte/MedikarteHelpers.java
@@ -1,166 +1,163 @@
package com.hilotec.elexis.kgview.medikarte;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import com.hilotec.elexis.kgview.Preferences;
import com.hilotec.elexis.kgview.data.FavMedikament;
import ch.elexis.data.Patient;
import ch.elexis.data.PersistentObject;
import ch.elexis.data.Prescription;
import ch.elexis.data.Query;
import ch.rgw.tools.StringTool;
import ch.rgw.tools.TimeTool;
public class MedikarteHelpers {
private final static String PRESC_EI_ORD = "hilotec:ordnungszahl";
private final static String PRESC_EI_ZWECK = "hilotec:zweck";
/**
* Medikation auf der Medikarte des Patienten zusammensuchen.
* Wenn !alle, dann wird nur die noch aktuelle Medikation zurueckgegeben.
*/
public static List<Prescription> medikarteMedikation(
Patient patient, boolean alle)
{
return medikarteMedikation(patient, alle, false);
}
/**
* Medikation auf der Medikarte des Patienten zusammensuchen.
* Wenn !alle, dann wird nur die noch aktuelle Medikation zurueckgegeben.
* Mit geloescht kann gesteuert werden ob auch geloeschte Medikamente
* angezeigt werden sollen.
*/
public static List<Prescription> medikarteMedikation(
Patient patient, boolean alle, boolean geloescht)
{
Query<Prescription> qbe = new Query<Prescription>(Prescription.class);
// FIXME: sollte mit executed with deleted gehen
if (geloescht) {
- boolean sd = PersistentObject.isShowDeleted();
- PersistentObject.setShowDeleted(true);
qbe.clear();
- PersistentObject.setShowDeleted(sd);
}
qbe.add(Prescription.PATIENT_ID, Query.EQUALS, patient.getId());
qbe.add(Prescription.REZEPT_ID, StringTool.leer, null);
if (!alle) {
qbe.startGroup();
String today = new TimeTool().toString(TimeTool.DATE_COMPACT);
if (Preferences.getMedikarteStopdatumInkl()) {
qbe.add(Prescription.DATE_UNTIL, Query.GREATER_OR_EQUAL, today);
} else {
qbe.add(Prescription.DATE_UNTIL, Query.GREATER, today);
}
qbe.or();
qbe.add(Prescription.DATE_UNTIL, StringTool.leer, null);
qbe.or();
qbe.add(Prescription.DATE_UNTIL, Query.EQUALS, "");
qbe.endGroup();
}
// Medikamente ohne Fav-Medi Verknuepfung oder mit falsch formatierter
// Dosis rauswerfen
List<Prescription> pl = qbe.execute();
Iterator<Prescription> i = pl.iterator();
while(i.hasNext()) {
Prescription p = i.next();
if (FavMedikament.load(p.getArtikel()) == null)
i.remove();
else if (p.getDosis().split("-").length != 4)
i.remove();
}
return pl;
}
/**
* Datum der letzten Aenderung der Medikarte (letztes von oder bis datum)
*/
public static String medikarteDatum(Patient patient)
{
// TODO: Koennte man mit einer Query sauberer loesen
List<Prescription> medis = medikarteMedikation(patient, false);
TimeTool max = new TimeTool(0);
TimeTool cur = new TimeTool();
for (Prescription p: medis) {
cur.set(p.getBeginDate());
if (cur.isAfter(max)) max.set(p.getBeginDate());
cur.set(p.getEndDate());
if (cur.isAfter(max)) max.set(p.getEndDate());
}
return max.toString(TimeTool.DATE_GER);
}
/**
* Ordnungszahl fuer Verschreibung holen
*/
@SuppressWarnings("rawtypes")
public static int getOrdnungszahl(Prescription presc) {
Map ht = presc.getMap(Prescription.FLD_EXTINFO);
// Ordnungszahl der Verschreibung
if (ht.containsKey(PRESC_EI_ORD))
return (Integer) ht.get(PRESC_EI_ORD);
// Standard fuers Medikament
FavMedikament fm = FavMedikament.load(presc.getArtikel());
if (fm != null)
return fm.getOrdnungszahl();
return 0;
}
/**
* Ordnungszahl fuer Verschreibung setzen
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void setOrdnungszahl(Prescription presc, int ord) {
Map ht = presc.getMap(Prescription.FLD_EXTINFO);
ht.put(PRESC_EI_ORD, ord);
presc.setMap(Prescription.FLD_EXTINFO, ht);
}
/**
* Zweck fuer Verschreibung holen
*/
@SuppressWarnings("rawtypes")
public static String getPZweck(Prescription presc) {
Map ht = presc.getMap(Prescription.FLD_EXTINFO);
// Ordnungszahl der Verschreibung
if (ht.containsKey(PRESC_EI_ZWECK))
return (String) ht.get(PRESC_EI_ZWECK);
// Standard fuers Medikament
FavMedikament fm = FavMedikament.load(presc.getArtikel());
if (fm != null)
return fm.getZweck();
return "";
}
/**
* Ordnungszahl fuer Verschreibung setzen
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
public static void setPZweck(Prescription presc, String zweck) {
Map ht = presc.getMap(Prescription.FLD_EXTINFO);
// Wenns dem Standard entspricht speichern wir den Eintrag nicht
FavMedikament fm = FavMedikament.load(presc.getArtikel());
if (fm != null && fm.getZweck().equals(zweck)) {
ht.remove(PRESC_EI_ZWECK);
} else {
ht.put(PRESC_EI_ZWECK, zweck);
}
presc.setMap(Prescription.FLD_EXTINFO, ht);
}
}
| false | true | public static List<Prescription> medikarteMedikation(
Patient patient, boolean alle, boolean geloescht)
{
Query<Prescription> qbe = new Query<Prescription>(Prescription.class);
// FIXME: sollte mit executed with deleted gehen
if (geloescht) {
boolean sd = PersistentObject.isShowDeleted();
PersistentObject.setShowDeleted(true);
qbe.clear();
PersistentObject.setShowDeleted(sd);
}
qbe.add(Prescription.PATIENT_ID, Query.EQUALS, patient.getId());
qbe.add(Prescription.REZEPT_ID, StringTool.leer, null);
if (!alle) {
qbe.startGroup();
String today = new TimeTool().toString(TimeTool.DATE_COMPACT);
if (Preferences.getMedikarteStopdatumInkl()) {
qbe.add(Prescription.DATE_UNTIL, Query.GREATER_OR_EQUAL, today);
} else {
qbe.add(Prescription.DATE_UNTIL, Query.GREATER, today);
}
qbe.or();
qbe.add(Prescription.DATE_UNTIL, StringTool.leer, null);
qbe.or();
qbe.add(Prescription.DATE_UNTIL, Query.EQUALS, "");
qbe.endGroup();
}
// Medikamente ohne Fav-Medi Verknuepfung oder mit falsch formatierter
// Dosis rauswerfen
List<Prescription> pl = qbe.execute();
Iterator<Prescription> i = pl.iterator();
while(i.hasNext()) {
Prescription p = i.next();
if (FavMedikament.load(p.getArtikel()) == null)
i.remove();
else if (p.getDosis().split("-").length != 4)
i.remove();
}
return pl;
}
| public static List<Prescription> medikarteMedikation(
Patient patient, boolean alle, boolean geloescht)
{
Query<Prescription> qbe = new Query<Prescription>(Prescription.class);
// FIXME: sollte mit executed with deleted gehen
if (geloescht) {
qbe.clear();
}
qbe.add(Prescription.PATIENT_ID, Query.EQUALS, patient.getId());
qbe.add(Prescription.REZEPT_ID, StringTool.leer, null);
if (!alle) {
qbe.startGroup();
String today = new TimeTool().toString(TimeTool.DATE_COMPACT);
if (Preferences.getMedikarteStopdatumInkl()) {
qbe.add(Prescription.DATE_UNTIL, Query.GREATER_OR_EQUAL, today);
} else {
qbe.add(Prescription.DATE_UNTIL, Query.GREATER, today);
}
qbe.or();
qbe.add(Prescription.DATE_UNTIL, StringTool.leer, null);
qbe.or();
qbe.add(Prescription.DATE_UNTIL, Query.EQUALS, "");
qbe.endGroup();
}
// Medikamente ohne Fav-Medi Verknuepfung oder mit falsch formatierter
// Dosis rauswerfen
List<Prescription> pl = qbe.execute();
Iterator<Prescription> i = pl.iterator();
while(i.hasNext()) {
Prescription p = i.next();
if (FavMedikament.load(p.getArtikel()) == null)
i.remove();
else if (p.getDosis().split("-").length != 4)
i.remove();
}
return pl;
}
|
diff --git a/wallet/src/de/schildbach/wallet/litecoin/service/BlockchainServiceImpl.java b/wallet/src/de/schildbach/wallet/litecoin/service/BlockchainServiceImpl.java
index c38f4af..5ab7668 100644
--- a/wallet/src/de/schildbach/wallet/litecoin/service/BlockchainServiceImpl.java
+++ b/wallet/src/de/schildbach/wallet/litecoin/service/BlockchainServiceImpl.java
@@ -1,842 +1,848 @@
/*
* Copyright 2011-2013 the original author or authors.
*
* 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 de.schildbach.wallet.litecoin.service;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.math.BigInteger;
import java.net.InetSocketAddress;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicLong;
import android.annotation.SuppressLint;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.content.BroadcastReceiver;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.content.SharedPreferences.OnSharedPreferenceChangeListener;
import android.net.ConnectivityManager;
import android.net.Uri;
import android.net.wifi.WifiManager;
import android.net.wifi.WifiManager.WifiLock;
import android.os.BatteryManager;
import android.os.Binder;
import android.os.Handler;
import android.os.IBinder;
import android.os.PowerManager;
import android.os.PowerManager.WakeLock;
import android.preference.PreferenceManager;
import android.support.v4.app.NotificationCompat;
import android.text.format.DateUtils;
import android.util.Log;
import com.google.litecoin.core.AbstractPeerEventListener;
import com.google.litecoin.core.Address;
import com.google.litecoin.core.Block;
import com.google.litecoin.core.BlockChain;
import com.google.litecoin.core.Peer;
import com.google.litecoin.core.PeerEventListener;
import com.google.litecoin.core.PeerGroup;
import com.google.litecoin.core.ScriptException;
import com.google.litecoin.core.StoredBlock;
import com.google.litecoin.core.Transaction;
import com.google.litecoin.core.TransactionConfidence.ConfidenceType;
import com.google.litecoin.core.TransactionInput;
import com.google.litecoin.core.Wallet;
import com.google.litecoin.core.Wallet.BalanceType;
import com.google.litecoin.core.WalletEventListener;
import com.google.litecoin.discovery.DnsDiscovery;
import com.google.litecoin.discovery.IrcDiscovery;
import com.google.litecoin.discovery.PeerDiscovery;
import com.google.litecoin.discovery.PeerDiscoveryException;
import com.google.litecoin.store.BlockStore;
import com.google.litecoin.store.BlockStoreException;
import com.google.litecoin.store.SPVBlockStore;
import de.schildbach.wallet.litecoin.Constants;
import de.schildbach.wallet.litecoin.WalletApplication;
import de.schildbach.wallet.litecoin.WalletBalanceWidgetProvider;
import de.schildbach.wallet.litecoin.ui.WalletActivity;
import de.schildbach.wallet.litecoin.util.ThrottelingWalletChangeListener;
import de.schildbach.wallet.litecoin.util.WalletUtils;
import de.schildbach.wallet.litecoin.R;
/**
* @author Andreas Schildbach
*/
public class BlockchainServiceImpl extends android.app.Service implements BlockchainService
{
private WalletApplication application;
private SharedPreferences prefs;
private BlockStore blockStore;
private File blockChainFile;
private BlockChain blockChain;
private PeerGroup peerGroup;
private final Handler handler = new Handler();
private final Handler delayHandler = new Handler();
private WakeLock wakeLock;
private WifiLock wifiLock;
private PeerConnectivityListener peerConnectivityListener;
private NotificationManager nm;
private static final int NOTIFICATION_ID_CONNECTED = 0;
private static final int NOTIFICATION_ID_COINS_RECEIVED = 1;
private int notificationCount = 0;
private BigInteger notificationAccumulatedAmount = BigInteger.ZERO;
private final List<Address> notificationAddresses = new LinkedList<Address>();
private int bestChainHeightEver;
private boolean resetBlockchainOnShutdown = false;
private static final int MAX_LAST_CHAIN_HEIGHTS = 10;
private static final int IDLE_TIMEOUT_MIN = 2;
private static final long APPWIDGET_THROTTLE_MS = DateUtils.SECOND_IN_MILLIS;
private static final String TAG = BlockchainServiceImpl.class.getSimpleName();
private final WalletEventListener walletEventListener = new ThrottelingWalletChangeListener(APPWIDGET_THROTTLE_MS)
{
@Override
public void onThrotteledWalletChanged()
{
notifyWidgets();
}
@Override
public void onCoinsReceived(final Wallet wallet, final Transaction tx, final BigInteger prevBalance, final BigInteger newBalance)
{
try
{
final Address from;
if (!tx.isCoinBase())
{
final TransactionInput input = tx.getInputs().get(0);
from = input.getFromAddress();
}
else
{
from = null;
}
final BigInteger amount = tx.getValue(wallet);
final ConfidenceType confidenceType = tx.getConfidence().getConfidenceType();
handler.post(new Runnable()
{
public void run()
{
final boolean isReceived = amount.signum() > 0;
final int bestChainHeight = blockChain.getBestChainHeight();
final boolean replaying = bestChainHeight < bestChainHeightEver;
final boolean isReplayedTx = confidenceType == ConfidenceType.BUILDING && replaying;
if (isReceived && !isReplayedTx)
notifyCoinsReceived(from, amount);
}
});
}
catch (final ScriptException x)
{
throw new RuntimeException(x);
}
}
};
private void notifyCoinsReceived(final Address from, final BigInteger amount)
{
if (notificationCount == 1)
nm.cancel(NOTIFICATION_ID_COINS_RECEIVED);
notificationCount++;
notificationAccumulatedAmount = notificationAccumulatedAmount.add(amount);
if (from != null && !notificationAddresses.contains(from))
notificationAddresses.add(from);
final int precision = Integer.parseInt(prefs.getString(Constants.PREFS_KEY_LTC_PRECISION, Integer.toString(Constants.LTC_PRECISION)));
final String tickerMsg = getString(R.string.notification_coins_received_msg, WalletUtils.formatValue(amount, precision))
+ Constants.NETWORK_SUFFIX;
final String msg = getString(R.string.notification_coins_received_msg, WalletUtils.formatValue(notificationAccumulatedAmount, precision))
+ Constants.NETWORK_SUFFIX;
final StringBuilder text = new StringBuilder();
for (final Address address : notificationAddresses)
{
if (text.length() > 0)
text.append(", ");
text.append(address.toString());
}
if (text.length() == 0)
text.append("unknown");
text.insert(0, "From ");
final NotificationCompat.Builder notification = new NotificationCompat.Builder(this);
notification.setSmallIcon(R.drawable.stat_notify_received);
notification.setTicker(tickerMsg);
notification.setContentTitle(msg);
notification.setContentText(text);
notification.setContentIntent(PendingIntent.getActivity(this, 0, new Intent(this, WalletActivity.class), 0));
notification.setNumber(notificationCount == 1 ? 0 : notificationCount);
notification.setWhen(System.currentTimeMillis());
notification.setSound(Uri.parse("android.resource://" + getPackageName() + "/" + R.raw.coins_received));
nm.notify(NOTIFICATION_ID_COINS_RECEIVED, notification.getNotification());
}
private class PeerConnectivityListener extends AbstractPeerEventListener implements OnSharedPreferenceChangeListener
{
private int peerCount;
private AtomicBoolean stopped = new AtomicBoolean(false);
public PeerConnectivityListener()
{
prefs.registerOnSharedPreferenceChangeListener(this);
}
public void stop()
{
stopped.set(true);
prefs.unregisterOnSharedPreferenceChangeListener(this);
nm.cancel(NOTIFICATION_ID_CONNECTED);
}
@Override
public void onPeerConnected(final Peer peer, final int peerCount)
{
this.peerCount = peerCount;
changed(peerCount);
}
@Override
public void onPeerDisconnected(final Peer peer, final int peerCount)
{
this.peerCount = peerCount;
changed(peerCount);
}
public void onSharedPreferenceChanged(final SharedPreferences sharedPreferences, final String key)
{
if (Constants.PREFS_KEY_CONNECTIVITY_NOTIFICATION.equals(key))
changed(peerCount);
}
private void changed(final int numPeers)
{
if (stopped.get())
return;
handler.post(new Runnable()
{
public void run()
{
final boolean connectivityNotification = prefs.getBoolean(Constants.PREFS_KEY_CONNECTIVITY_NOTIFICATION, true);
if (!connectivityNotification || numPeers == 0)
{
nm.cancel(NOTIFICATION_ID_CONNECTED);
}
else
{
final NotificationCompat.Builder notification = new NotificationCompat.Builder(BlockchainServiceImpl.this);
notification.setSmallIcon(R.drawable.stat_sys_peers, numPeers > 4 ? 4 : numPeers);
notification.setContentTitle(getString(R.string.app_name));
notification.setContentText(getString(R.string.notification_peers_connected_msg, numPeers));
notification.setContentIntent(PendingIntent.getActivity(BlockchainServiceImpl.this, 0, new Intent(BlockchainServiceImpl.this,
WalletActivity.class), 0));
notification.setWhen(System.currentTimeMillis());
notification.setOngoing(true);
nm.notify(NOTIFICATION_ID_CONNECTED, notification.getNotification());
}
// send broadcast
sendBroadcastPeerState(numPeers);
}
});
}
}
private final PeerEventListener blockchainDownloadListener = new AbstractPeerEventListener()
{
private final AtomicLong lastMessageTime = new AtomicLong(0);
@Override
public void onBlocksDownloaded(final Peer peer, final Block block, final int blocksLeft)
{
delayHandler.removeCallbacksAndMessages(null);
final long now = System.currentTimeMillis();
if (now - lastMessageTime.get() > Constants.BLOCKCHAIN_STATE_BROADCAST_THROTTLE_MS)
delayHandler.post(runnable);
else
delayHandler.postDelayed(runnable, Constants.BLOCKCHAIN_STATE_BROADCAST_THROTTLE_MS);
}
private final Runnable runnable = new Runnable()
{
public void run()
{
lastMessageTime.set(System.currentTimeMillis());
final Date bestChainDate = new Date(blockChain.getChainHead().getHeader().getTimeSeconds() * DateUtils.SECOND_IN_MILLIS);
final int bestChainHeight = blockChain.getBestChainHeight();
if (bestChainHeight > bestChainHeightEver)
bestChainHeightEver = bestChainHeight;
final boolean replaying = bestChainHeight < bestChainHeightEver;
sendBroadcastBlockchainState(bestChainDate, bestChainHeight, replaying, ACTION_BLOCKCHAIN_STATE_DOWNLOAD_OK);
}
};
};
private final BroadcastReceiver connectivityReceiver = new BroadcastReceiver()
{
private boolean hasConnectivity;
private boolean hasPower;
private boolean hasStorage = true;
@Override
public void onReceive(final Context context, final Intent intent)
{
final String action = intent.getAction();
if (ConnectivityManager.CONNECTIVITY_ACTION.equals(action))
{
hasConnectivity = !intent.getBooleanExtra(ConnectivityManager.EXTRA_NO_CONNECTIVITY, false);
final String reason = intent.getStringExtra(ConnectivityManager.EXTRA_REASON);
// final boolean isFailover = intent.getBooleanExtra(ConnectivityManager.EXTRA_IS_FAILOVER, false);
Log.i(TAG, "network is " + (hasConnectivity ? "up" : "down") + (reason != null ? ": " + reason : ""));
check();
}
else if (Intent.ACTION_BATTERY_CHANGED.equals(action))
{
final int level = intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1);
final int scale = intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
final int plugged = intent.getIntExtra(BatteryManager.EXTRA_PLUGGED, 0);
hasPower = plugged != 0 || level > scale / 10;
Log.i(TAG, "battery changed: level=" + level + "/" + scale + " plugged=" + plugged);
check();
}
else if (Intent.ACTION_DEVICE_STORAGE_LOW.equals(action))
{
hasStorage = false;
Log.i(TAG, "device storage low");
check();
}
else if (Intent.ACTION_DEVICE_STORAGE_OK.equals(action))
{
hasStorage = true;
Log.i(TAG, "device storage ok");
check();
}
}
@SuppressLint("Wakelock")
private void check()
{
final Wallet wallet = application.getWallet();
final boolean hasEverything = hasConnectivity && hasPower && hasStorage;
if (hasEverything && peerGroup == null)
{
Log.d(TAG, "acquiring wakelock");
wakeLock.acquire();
Log.i(TAG, "starting peergroup");
peerGroup = new PeerGroup(Constants.NETWORK_PARAMETERS, blockChain);
- peerGroup.addWallet(wallet);
+ try {
+ peerGroup.addWallet(wallet);
+ } catch(NoSuchMethodError e) {
+ Log.e("Litecoin", "There's no method: " + e.getLocalizedMessage());
+ Log.e("Litecoin", "Litecoinj issue. We're going to ignore this for now and just try and return nicely.");
+ return;
+ }
peerGroup.setUserAgent(Constants.USER_AGENT, application.applicationVersionName());
peerGroup.addEventListener(peerConnectivityListener);
final int maxConnectedPeers = application.maxConnectedPeers();
final String trustedPeerHost = prefs.getString(Constants.PREFS_KEY_TRUSTED_PEER, "").trim();
final boolean hasTrustedPeer = trustedPeerHost.length() > 0;
final boolean connectTrustedPeerOnly = hasTrustedPeer && prefs.getBoolean(Constants.PREFS_KEY_TRUSTED_PEER_ONLY, false);
peerGroup.setMaxConnections(connectTrustedPeerOnly ? 1 : maxConnectedPeers);
peerGroup.addPeerDiscovery(new PeerDiscovery()
{
private final PeerDiscovery normalPeerDiscovery = Constants.TEST ? new IrcDiscovery(Constants.PEER_DISCOVERY_IRC_CHANNEL_TEST)
: new DnsDiscovery(Constants.NETWORK_PARAMETERS);
public InetSocketAddress[] getPeers(final long timeoutValue, final TimeUnit timeoutUnit) throws PeerDiscoveryException
{
final List<InetSocketAddress> peers = new LinkedList<InetSocketAddress>();
boolean needsTrimPeersWorkaround = false;
if (hasTrustedPeer)
{
final InetSocketAddress addr = new InetSocketAddress(trustedPeerHost, Constants.NETWORK_PARAMETERS.port);
if (addr.getAddress() != null)
{
peers.add(addr);
needsTrimPeersWorkaround = true;
}
}
if (!connectTrustedPeerOnly)
peers.addAll(Arrays.asList(normalPeerDiscovery.getPeers(timeoutValue, timeoutUnit)));
// workaround because PeerGroup will shuffle peers
if (needsTrimPeersWorkaround)
while (peers.size() >= maxConnectedPeers)
peers.remove(peers.size() - 1);
return peers.toArray(new InetSocketAddress[0]);
}
public void shutdown()
{
normalPeerDiscovery.shutdown();
}
});
// start peergroup
peerGroup.start();
peerGroup.startBlockChainDownload(blockchainDownloadListener);
}
else if (!hasEverything && peerGroup != null)
{
Log.i(TAG, "stopping peergroup");
peerGroup.removeEventListener(peerConnectivityListener);
peerGroup.removeWallet(wallet);
peerGroup.stop();
peerGroup = null;
Log.d(TAG, "releasing wakelock");
wakeLock.release();
}
final Date bestChainDate = new Date(blockChain.getChainHead().getHeader().getTimeSeconds() * DateUtils.SECOND_IN_MILLIS);
final int bestChainHeight = blockChain.getBestChainHeight();
final int download = (hasConnectivity ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_NETWORK_PROBLEM)
| (hasPower ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_POWER_PROBLEM)
| (hasStorage ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_STORAGE_PROBLEM);
final boolean replaying = bestChainHeight < bestChainHeightEver;
sendBroadcastBlockchainState(bestChainDate, bestChainHeight, replaying, download);
}
};
private final BroadcastReceiver tickReceiver = new BroadcastReceiver()
{
private int lastChainHeight = 0;
private final List<Integer> lastDownloadedHistory = new LinkedList<Integer>();
@Override
public void onReceive(final Context context, final Intent intent)
{
final int chainHeight = blockChain.getBestChainHeight();
if (lastChainHeight > 0)
{
final int downloaded = chainHeight - lastChainHeight;
// push number of downloaded blocks
lastDownloadedHistory.add(0, downloaded);
// trim
while (lastDownloadedHistory.size() > MAX_LAST_CHAIN_HEIGHTS)
lastDownloadedHistory.remove(lastDownloadedHistory.size() - 1);
// print
final StringBuilder builder = new StringBuilder();
for (final int lastDownloaded : lastDownloadedHistory)
{
if (builder.length() > 0)
builder.append(',');
builder.append(lastDownloaded);
}
Log.i(TAG, "Number of blocks downloaded: " + builder);
// determine if download is idling
boolean isIdle = false;
if (lastDownloadedHistory.size() >= IDLE_TIMEOUT_MIN)
{
isIdle = true;
for (int i = 0; i < IDLE_TIMEOUT_MIN; i++)
{
if (lastDownloadedHistory.get(i) > 0)
{
isIdle = false;
break;
}
}
}
// if idling, shutdown service
if (isIdle)
{
Log.i(TAG, "end of block download detected, stopping service");
stopSelf();
}
}
lastChainHeight = chainHeight;
}
};
public class LocalBinder extends Binder
{
public BlockchainService getService()
{
return BlockchainServiceImpl.this;
}
}
private final IBinder mBinder = new LocalBinder();
@Override
public IBinder onBind(final Intent intent)
{
Log.d(TAG, ".onBind()");
return mBinder;
}
@Override
public boolean onUnbind(final Intent intent)
{
Log.d(TAG, ".onUnbind()");
return super.onUnbind(intent);
}
@Override
public void onCreate()
{
Log.d(TAG, ".onCreate()");
super.onCreate();
nm = (NotificationManager) getSystemService(Context.NOTIFICATION_SERVICE);
final String lockName = getPackageName() + " blockchain sync";
final PowerManager pm = (PowerManager) getSystemService(Context.POWER_SERVICE);
wakeLock = pm.newWakeLock(PowerManager.PARTIAL_WAKE_LOCK, lockName);
final WifiManager wifiManager = (WifiManager) getSystemService(Context.WIFI_SERVICE);
wifiLock = wifiManager.createWifiLock(WifiManager.WIFI_MODE_FULL, lockName);
wifiLock.setReferenceCounted(false);
application = (WalletApplication) getApplication();
prefs = PreferenceManager.getDefaultSharedPreferences(this);
final Wallet wallet = application.getWallet();
final int versionCode = application.applicationVersionCode();
prefs.edit().putInt(Constants.PREFS_KEY_LAST_VERSION, versionCode).commit();
bestChainHeightEver = prefs.getInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, 0);
peerConnectivityListener = new PeerConnectivityListener();
sendBroadcastPeerState(0);
final IntentFilter intentFilter = new IntentFilter();
intentFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
intentFilter.addAction(Intent.ACTION_BATTERY_CHANGED);
intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_LOW);
intentFilter.addAction(Intent.ACTION_DEVICE_STORAGE_OK);
registerReceiver(connectivityReceiver, intentFilter);
blockChainFile = new File(getDir("blockstore", Context.MODE_WORLD_READABLE | Context.MODE_WORLD_WRITEABLE), Constants.BLOCKCHAIN_FILENAME);
final boolean blockChainFileExists = blockChainFile.exists();
if (!blockChainFileExists)
{
Log.d(TAG, "blockchain does not exist, resetting wallet");
wallet.clearTransactions(0);
copyBlockchainSnapshot(blockChainFile);
}
try
{
blockStore = new SPVBlockStore(Constants.NETWORK_PARAMETERS, blockChainFile);
blockStore.getChainHead(); // detect corruptions as early as possible
}
catch (final BlockStoreException x)
{
blockChainFile.delete();
x.printStackTrace();
throw new Error("blockstore cannot be created", x);
}
try
{
blockChain = new BlockChain(Constants.NETWORK_PARAMETERS, wallet, blockStore);
}
catch (final BlockStoreException x)
{
throw new Error("blockchain cannot be created", x);
}
application.getWallet().addEventListener(walletEventListener);
registerReceiver(tickReceiver, new IntentFilter(Intent.ACTION_TIME_TICK));
}
@Override
public int onStartCommand(final Intent intent, final int flags, final int startId)
{
if (BlockchainService.ACTION_CANCEL_COINS_RECEIVED.equals(intent.getAction()))
{
notificationCount = 0;
notificationAccumulatedAmount = BigInteger.ZERO;
notificationAddresses.clear();
nm.cancel(NOTIFICATION_ID_COINS_RECEIVED);
}
if (BlockchainService.ACTION_HOLD_WIFI_LOCK.equals(intent.getAction()))
{
Log.d(TAG, "acquiring wifilock");
wifiLock.acquire();
}
else
{
Log.d(TAG, "releasing wifilock");
wifiLock.release();
}
if (BlockchainService.ACTION_RESET_BLOCKCHAIN.equals(intent.getAction()))
{
resetBlockchainOnShutdown = true;
stopSelf();
}
return START_NOT_STICKY;
}
private void copyBlockchainSnapshot(final File file)
{
try
{
final long t = System.currentTimeMillis();
final String blockchainSnapshotFilename = Constants.BLOCKCHAIN_SNAPSHOT_FILENAME;
final InputStream is = getAssets().open(blockchainSnapshotFilename);
final OutputStream os = new FileOutputStream(file);
Log.i(TAG, "copying blockchain snapshot");
final byte[] buf = new byte[8192];
int read;
while (-1 != (read = is.read(buf)))
os.write(buf, 0, read);
os.close();
is.close();
Log.i(TAG, "finished copying, took " + (System.currentTimeMillis() - t) + " ms");
}
catch (final IOException x)
{
Log.w(TAG, "failed copying, starting from genesis");
file.delete();
}
}
@Override
public void onDestroy()
{
Log.d(TAG, ".onDestroy()");
unregisterReceiver(tickReceiver);
application.getWallet().removeEventListener(walletEventListener);
if (peerGroup != null)
{
peerGroup.removeEventListener(peerConnectivityListener);
peerGroup.removeWallet(application.getWallet());
peerGroup.stopAndWait();
Log.i(TAG, "peergroup stopped");
}
peerConnectivityListener.stop();
unregisterReceiver(connectivityReceiver);
removeBroadcastPeerState();
removeBroadcastBlockchainState();
prefs.edit().putInt(Constants.PREFS_KEY_BEST_CHAIN_HEIGHT_EVER, bestChainHeightEver).commit();
delayHandler.removeCallbacksAndMessages(null);
try
{
blockStore.close();
}
catch (final BlockStoreException x)
{
throw new RuntimeException(x);
}
application.saveWallet();
if (wakeLock.isHeld())
{
Log.d(TAG, "wakelock still held, releasing");
wakeLock.release();
}
if (wifiLock.isHeld())
{
Log.d(TAG, "wifilock still held, releasing");
wifiLock.release();
}
if (resetBlockchainOnShutdown)
{
Log.d(TAG, "removing blockchain");
blockChainFile.delete();
}
super.onDestroy();
}
@Override
public void onLowMemory()
{
Log.w(TAG, "low memory detected, stopping service");
stopSelf();
}
public void broadcastTransaction(final Transaction tx)
{
if (peerGroup != null)
peerGroup.broadcastTransaction(tx);
}
public List<Peer> getConnectedPeers()
{
if (peerGroup != null)
return peerGroup.getConnectedPeers();
else
return null;
}
public List<StoredBlock> getRecentBlocks(final int maxBlocks)
{
final List<StoredBlock> blocks = new ArrayList<StoredBlock>(maxBlocks);
try
{
StoredBlock block = blockChain.getChainHead();
while (block != null)
{
blocks.add(block);
if (blocks.size() >= maxBlocks)
break;
block = block.getPrev(blockStore);
}
}
catch (final BlockStoreException x)
{
// swallow
}
return blocks;
}
private void sendBroadcastPeerState(final int numPeers)
{
final Intent broadcast = new Intent(ACTION_PEER_STATE);
broadcast.setPackage(getPackageName());
broadcast.putExtra(ACTION_PEER_STATE_NUM_PEERS, numPeers);
sendStickyBroadcast(broadcast);
}
private void removeBroadcastPeerState()
{
removeStickyBroadcast(new Intent(ACTION_PEER_STATE));
}
private void sendBroadcastBlockchainState(final Date chainDate, final int chainHeight, final boolean replaying, final int download)
{
final Intent broadcast = new Intent(ACTION_BLOCKCHAIN_STATE);
broadcast.setPackage(getPackageName());
broadcast.putExtra(ACTION_BLOCKCHAIN_STATE_BEST_CHAIN_DATE, chainDate);
broadcast.putExtra(ACTION_BLOCKCHAIN_STATE_BEST_CHAIN_HEIGHT, chainHeight);
broadcast.putExtra(ACTION_BLOCKCHAIN_STATE_REPLAYING, replaying);
broadcast.putExtra(ACTION_BLOCKCHAIN_STATE_DOWNLOAD, download);
sendStickyBroadcast(broadcast);
}
private void removeBroadcastBlockchainState()
{
removeStickyBroadcast(new Intent(ACTION_BLOCKCHAIN_STATE));
}
public void notifyWidgets()
{
final AppWidgetManager appWidgetManager = AppWidgetManager.getInstance(this);
final ComponentName providerName = new ComponentName(this, WalletBalanceWidgetProvider.class);
final int[] appWidgetIds;
try {
appWidgetIds = appWidgetManager.getAppWidgetIds(providerName);
} catch(RuntimeException e) {
// Bug #6 - App server dead?
Log.e("Litecoin", "App server appears dead - Runtime Exception when running getAppWidgetIds. Returning..");
return;
}
if (appWidgetIds.length > 0)
{
final Wallet wallet = application.getWallet();
final BigInteger balance = wallet.getBalance(BalanceType.ESTIMATED);
WalletBalanceWidgetProvider.updateWidgets(this, appWidgetManager, appWidgetIds, balance);
}
}
}
| true | true | private void check()
{
final Wallet wallet = application.getWallet();
final boolean hasEverything = hasConnectivity && hasPower && hasStorage;
if (hasEverything && peerGroup == null)
{
Log.d(TAG, "acquiring wakelock");
wakeLock.acquire();
Log.i(TAG, "starting peergroup");
peerGroup = new PeerGroup(Constants.NETWORK_PARAMETERS, blockChain);
peerGroup.addWallet(wallet);
peerGroup.setUserAgent(Constants.USER_AGENT, application.applicationVersionName());
peerGroup.addEventListener(peerConnectivityListener);
final int maxConnectedPeers = application.maxConnectedPeers();
final String trustedPeerHost = prefs.getString(Constants.PREFS_KEY_TRUSTED_PEER, "").trim();
final boolean hasTrustedPeer = trustedPeerHost.length() > 0;
final boolean connectTrustedPeerOnly = hasTrustedPeer && prefs.getBoolean(Constants.PREFS_KEY_TRUSTED_PEER_ONLY, false);
peerGroup.setMaxConnections(connectTrustedPeerOnly ? 1 : maxConnectedPeers);
peerGroup.addPeerDiscovery(new PeerDiscovery()
{
private final PeerDiscovery normalPeerDiscovery = Constants.TEST ? new IrcDiscovery(Constants.PEER_DISCOVERY_IRC_CHANNEL_TEST)
: new DnsDiscovery(Constants.NETWORK_PARAMETERS);
public InetSocketAddress[] getPeers(final long timeoutValue, final TimeUnit timeoutUnit) throws PeerDiscoveryException
{
final List<InetSocketAddress> peers = new LinkedList<InetSocketAddress>();
boolean needsTrimPeersWorkaround = false;
if (hasTrustedPeer)
{
final InetSocketAddress addr = new InetSocketAddress(trustedPeerHost, Constants.NETWORK_PARAMETERS.port);
if (addr.getAddress() != null)
{
peers.add(addr);
needsTrimPeersWorkaround = true;
}
}
if (!connectTrustedPeerOnly)
peers.addAll(Arrays.asList(normalPeerDiscovery.getPeers(timeoutValue, timeoutUnit)));
// workaround because PeerGroup will shuffle peers
if (needsTrimPeersWorkaround)
while (peers.size() >= maxConnectedPeers)
peers.remove(peers.size() - 1);
return peers.toArray(new InetSocketAddress[0]);
}
public void shutdown()
{
normalPeerDiscovery.shutdown();
}
});
// start peergroup
peerGroup.start();
peerGroup.startBlockChainDownload(blockchainDownloadListener);
}
else if (!hasEverything && peerGroup != null)
{
Log.i(TAG, "stopping peergroup");
peerGroup.removeEventListener(peerConnectivityListener);
peerGroup.removeWallet(wallet);
peerGroup.stop();
peerGroup = null;
Log.d(TAG, "releasing wakelock");
wakeLock.release();
}
final Date bestChainDate = new Date(blockChain.getChainHead().getHeader().getTimeSeconds() * DateUtils.SECOND_IN_MILLIS);
final int bestChainHeight = blockChain.getBestChainHeight();
final int download = (hasConnectivity ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_NETWORK_PROBLEM)
| (hasPower ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_POWER_PROBLEM)
| (hasStorage ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_STORAGE_PROBLEM);
final boolean replaying = bestChainHeight < bestChainHeightEver;
sendBroadcastBlockchainState(bestChainDate, bestChainHeight, replaying, download);
}
| private void check()
{
final Wallet wallet = application.getWallet();
final boolean hasEverything = hasConnectivity && hasPower && hasStorage;
if (hasEverything && peerGroup == null)
{
Log.d(TAG, "acquiring wakelock");
wakeLock.acquire();
Log.i(TAG, "starting peergroup");
peerGroup = new PeerGroup(Constants.NETWORK_PARAMETERS, blockChain);
try {
peerGroup.addWallet(wallet);
} catch(NoSuchMethodError e) {
Log.e("Litecoin", "There's no method: " + e.getLocalizedMessage());
Log.e("Litecoin", "Litecoinj issue. We're going to ignore this for now and just try and return nicely.");
return;
}
peerGroup.setUserAgent(Constants.USER_AGENT, application.applicationVersionName());
peerGroup.addEventListener(peerConnectivityListener);
final int maxConnectedPeers = application.maxConnectedPeers();
final String trustedPeerHost = prefs.getString(Constants.PREFS_KEY_TRUSTED_PEER, "").trim();
final boolean hasTrustedPeer = trustedPeerHost.length() > 0;
final boolean connectTrustedPeerOnly = hasTrustedPeer && prefs.getBoolean(Constants.PREFS_KEY_TRUSTED_PEER_ONLY, false);
peerGroup.setMaxConnections(connectTrustedPeerOnly ? 1 : maxConnectedPeers);
peerGroup.addPeerDiscovery(new PeerDiscovery()
{
private final PeerDiscovery normalPeerDiscovery = Constants.TEST ? new IrcDiscovery(Constants.PEER_DISCOVERY_IRC_CHANNEL_TEST)
: new DnsDiscovery(Constants.NETWORK_PARAMETERS);
public InetSocketAddress[] getPeers(final long timeoutValue, final TimeUnit timeoutUnit) throws PeerDiscoveryException
{
final List<InetSocketAddress> peers = new LinkedList<InetSocketAddress>();
boolean needsTrimPeersWorkaround = false;
if (hasTrustedPeer)
{
final InetSocketAddress addr = new InetSocketAddress(trustedPeerHost, Constants.NETWORK_PARAMETERS.port);
if (addr.getAddress() != null)
{
peers.add(addr);
needsTrimPeersWorkaround = true;
}
}
if (!connectTrustedPeerOnly)
peers.addAll(Arrays.asList(normalPeerDiscovery.getPeers(timeoutValue, timeoutUnit)));
// workaround because PeerGroup will shuffle peers
if (needsTrimPeersWorkaround)
while (peers.size() >= maxConnectedPeers)
peers.remove(peers.size() - 1);
return peers.toArray(new InetSocketAddress[0]);
}
public void shutdown()
{
normalPeerDiscovery.shutdown();
}
});
// start peergroup
peerGroup.start();
peerGroup.startBlockChainDownload(blockchainDownloadListener);
}
else if (!hasEverything && peerGroup != null)
{
Log.i(TAG, "stopping peergroup");
peerGroup.removeEventListener(peerConnectivityListener);
peerGroup.removeWallet(wallet);
peerGroup.stop();
peerGroup = null;
Log.d(TAG, "releasing wakelock");
wakeLock.release();
}
final Date bestChainDate = new Date(blockChain.getChainHead().getHeader().getTimeSeconds() * DateUtils.SECOND_IN_MILLIS);
final int bestChainHeight = blockChain.getBestChainHeight();
final int download = (hasConnectivity ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_NETWORK_PROBLEM)
| (hasPower ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_POWER_PROBLEM)
| (hasStorage ? 0 : ACTION_BLOCKCHAIN_STATE_DOWNLOAD_STORAGE_PROBLEM);
final boolean replaying = bestChainHeight < bestChainHeightEver;
sendBroadcastBlockchainState(bestChainDate, bestChainHeight, replaying, download);
}
|
diff --git a/user/test/com/google/gwt/user/cellview/client/AbstractHasDataTestBase.java b/user/test/com/google/gwt/user/cellview/client/AbstractHasDataTestBase.java
index ea33ea75c..31b9c33e8 100644
--- a/user/test/com/google/gwt/user/cellview/client/AbstractHasDataTestBase.java
+++ b/user/test/com/google/gwt/user/cellview/client/AbstractHasDataTestBase.java
@@ -1,136 +1,136 @@
/*
* Copyright 2010 Google Inc.
*
* Licensed under the Apache License, Version 2.0 (the "License"); you may not
* use this file except in compliance with the License. You may obtain a copy of
* the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations under
* the License.
*/
package com.google.gwt.user.cellview.client;
import com.google.gwt.junit.client.GWTTestCase;
import com.google.gwt.regexp.shared.MatchResult;
import com.google.gwt.regexp.shared.RegExp;
import com.google.gwt.user.client.Window;
import com.google.gwt.view.client.ListDataProvider;
import java.util.ArrayList;
import java.util.List;
/**
* Base tests for {@link AbstractHasData}.
*/
public abstract class AbstractHasDataTestBase extends GWTTestCase {
@Override
public String getModuleName() {
return "com.google.gwt.user.cellview.CellView";
}
public void testGetDisplayedItem() {
AbstractHasData<String> display = createAbstractHasData();
ListDataProvider<String> provider = new ListDataProvider<String>(
createData(0, 13));
provider.addDataDisplay(display);
display.setVisibleRange(10, 10);
// No items when no data is present.
assertEquals("test 10", display.getDisplayedItem(0));
assertEquals("test 11", display.getDisplayedItem(1));
assertEquals("test 12", display.getDisplayedItem(2));
// Out of range.
try {
assertEquals("test 10", display.getDisplayedItem(-1));
fail("Expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected.
}
// Within page range, but out of data range.
try {
assertEquals("test 10", display.getDisplayedItem(4));
fail("Expected IndexOutOfBoundsException");
} catch (IndexOutOfBoundsException e) {
// Expected.
}
}
public void testGetDisplayedItems() {
AbstractHasData<String> display = createAbstractHasData();
ListDataProvider<String> provider = new ListDataProvider<String>();
provider.addDataDisplay(display);
display.setVisibleRange(10, 3);
// No items when no data is present.
assertEquals(0, display.getDisplayedItems().size());
// Set some data.
provider.setList(createData(0, 13));
List<String> items = display.getDisplayedItems();
assertEquals(3, items.size());
assertEquals("test 10", items.get(0));
assertEquals("test 11", items.get(1));
assertEquals("test 12", items.get(2));
}
public void testSetTabIndex() {
// Skip this test on Safari 3 because it does not support focusable divs.
String userAgent = Window.Navigator.getUserAgent();
if (userAgent.contains("Safari")) {
RegExp versionRegExp = RegExp.compile("Version/[0-3]", "ig");
MatchResult result = versionRegExp.exec(userAgent);
- if (result.getGroupCount() > 0) {
+ if (result != null && result.getGroupCount() > 0) {
return;
}
}
AbstractHasData<String> display = createAbstractHasData();
ListDataProvider<String> provider = new ListDataProvider<String>(
createData(0, 10));
provider.addDataDisplay(display);
// Default tab index is 0.
assertEquals(0, display.getTabIndex());
assertEquals(0, display.getKeyboardSelectedElement().getTabIndex());
// Set tab index to 2.
display.setTabIndex(2);
assertEquals(2, display.getTabIndex());
assertEquals(2, display.getKeyboardSelectedElement().getTabIndex());
// Push new data.
provider.refresh();
assertEquals(2, display.getTabIndex());
assertEquals(2, display.getKeyboardSelectedElement().getTabIndex());
}
/**
* Create an {@link AbstractHasData} to test.
*
* @return the widget to test
*/
protected abstract AbstractHasData<String> createAbstractHasData();
/**
* Create a list of data for testing.
*
* @param start the start index
* @param length the length
* @return a list of data
*/
protected List<String> createData(int start, int length) {
List<String> toRet = new ArrayList<String>();
for (int i = 0; i < length; i++) {
toRet.add("test " + (i + start));
}
return toRet;
}
}
| true | true | public void testSetTabIndex() {
// Skip this test on Safari 3 because it does not support focusable divs.
String userAgent = Window.Navigator.getUserAgent();
if (userAgent.contains("Safari")) {
RegExp versionRegExp = RegExp.compile("Version/[0-3]", "ig");
MatchResult result = versionRegExp.exec(userAgent);
if (result.getGroupCount() > 0) {
return;
}
}
AbstractHasData<String> display = createAbstractHasData();
ListDataProvider<String> provider = new ListDataProvider<String>(
createData(0, 10));
provider.addDataDisplay(display);
// Default tab index is 0.
assertEquals(0, display.getTabIndex());
assertEquals(0, display.getKeyboardSelectedElement().getTabIndex());
// Set tab index to 2.
display.setTabIndex(2);
assertEquals(2, display.getTabIndex());
assertEquals(2, display.getKeyboardSelectedElement().getTabIndex());
// Push new data.
provider.refresh();
assertEquals(2, display.getTabIndex());
assertEquals(2, display.getKeyboardSelectedElement().getTabIndex());
}
| public void testSetTabIndex() {
// Skip this test on Safari 3 because it does not support focusable divs.
String userAgent = Window.Navigator.getUserAgent();
if (userAgent.contains("Safari")) {
RegExp versionRegExp = RegExp.compile("Version/[0-3]", "ig");
MatchResult result = versionRegExp.exec(userAgent);
if (result != null && result.getGroupCount() > 0) {
return;
}
}
AbstractHasData<String> display = createAbstractHasData();
ListDataProvider<String> provider = new ListDataProvider<String>(
createData(0, 10));
provider.addDataDisplay(display);
// Default tab index is 0.
assertEquals(0, display.getTabIndex());
assertEquals(0, display.getKeyboardSelectedElement().getTabIndex());
// Set tab index to 2.
display.setTabIndex(2);
assertEquals(2, display.getTabIndex());
assertEquals(2, display.getKeyboardSelectedElement().getTabIndex());
// Push new data.
provider.refresh();
assertEquals(2, display.getTabIndex());
assertEquals(2, display.getKeyboardSelectedElement().getTabIndex());
}
|
diff --git a/src/main/java/com/atlassian/example/reviewcreator/CommitListener.java b/src/main/java/com/atlassian/example/reviewcreator/CommitListener.java
index 678ef6f..9ec3356 100644
--- a/src/main/java/com/atlassian/example/reviewcreator/CommitListener.java
+++ b/src/main/java/com/atlassian/example/reviewcreator/CommitListener.java
@@ -1,388 +1,388 @@
package com.atlassian.example.reviewcreator;
import com.atlassian.crucible.spi.data.*;
import com.atlassian.crucible.spi.PermId;
import com.atlassian.crucible.spi.services.*;
import com.atlassian.event.Event;
import com.atlassian.event.EventListener;
import com.atlassian.fisheye.event.CommitEvent;
import com.atlassian.fisheye.spi.data.ChangesetDataFE;
import com.atlassian.fisheye.spi.services.RevisionDataService;
import com.atlassian.sal.api.user.UserManager;
import com.google.common.base.Predicate;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterables;
import org.apache.commons.lang.StringUtils;
import org.apache.log4j.Logger;
import java.util.*;
/**
* <p>
* Event listener that subscribes to commit events and creates a review for
* each commit.
* </p>
* <p>
* Auto review creation can be enabled/disabled by an administrator on a
* per-project basis. Enabled projects must be bound to a FishEye repository
* and must have a default Moderator configured in the admin section.
* </p>
* <p>
* When auto review creation is enabled for a Crucible project, this
* {@link com.atlassian.event.EventListener} will intercept all commits for
* the project's repository and create a review for it. The review's author
* role is set to the committer of the changeset and the review's moderator is
* set to the project's default moderator.
* </p>
* <p>
* When the project has default reviewers configured, these will be added to
* the review.
* </p>
*
* @author Erik van Zijst
*/
public class CommitListener implements EventListener {
private final Logger logger = Logger.getLogger(getClass().getName());
private final RevisionDataService revisionService; // provided by FishEye
private final ReviewService reviewService; // provided by Crucible
private final ProjectService projectService; // provided by Crucible
private final UserService userService; // provided by Crucible
private final UserManager userManager; // provided by SAL
private final ImpersonationService impersonator; // provided by Crucible
private final ConfigurationManager config; // provided by our plugin
private static final ThreadLocal<Map<String, UserData>> committerToCrucibleUser =
new ThreadLocal();
public CommitListener(ConfigurationManager config,
ReviewService reviewService,
ProjectService projectService,
RevisionDataService revisionService,
UserService userService,
UserManager userManager,
ImpersonationService impersonator) {
this.reviewService = reviewService;
this.revisionService = revisionService;
this.projectService = projectService;
this.userService = userService;
this.userManager = userManager;
this.impersonator = impersonator;
this.config = config;
}
public Class[] getHandledEventClasses() {
return new Class[] {CommitEvent.class};
}
public void handleEvent(Event event) {
final CommitEvent commit = (CommitEvent) event;
if (isPluginEnabled()) {
try {
// switch to admin user so we can access all projects and API services:
impersonator.doAsUser(null, config.loadRunAsUser(),
new Operation<Void, ServerException>() {
public Void perform() throws ServerException {
- ChangesetDataFE cs = revisionService.getChangeset(
+ final ChangesetDataFE cs = revisionService.getChangeset(
commit.getRepositoryName(), commit.getChangeSetId());
- ProjectData project = getEnabledProjectForRepository(
+ final ProjectData project = getEnabledProjectForRepository(
commit.getRepositoryName());
- committerToCrucibleUser.set(loadCommitterMappings(project.getDefaultRepositoryName()));
if (project != null) {
+ committerToCrucibleUser.set(loadCommitterMappings(project.getDefaultRepositoryName()));
if (project.getDefaultModerator() != null) {
if (isUnderScrutiny(cs.getAuthor())) {
if (!config.loadIterative() || !appendToReview(commit.getRepositoryName(), cs, project)) {
// create a new review:
createReview(commit.getRepositoryName(), cs, project);
}
} else {
logger.info(String.format("Not creating a review for changeset %s.",
commit.getChangeSetId()));
}
} else {
logger.error(String.format("Unable to auto-create review for changeset %s. " +
"No default moderator configured for project %s.",
commit.getChangeSetId(), project.getKey()));
}
} else {
logger.error(String.format("Unable to auto-create review for changeset %s. " +
"No projects found that bind to repository %s.",
commit.getChangeSetId(), commit.getRepositoryName()));
}
return null;
}
});
} catch (Exception e) {
logger.error(String.format("Unable to auto-create " +
"review for changeset %s: %s.",
commit.getChangeSetId(), e.getMessage()), e);
}
}
}
/**
* Determines whether or not the user that made the commit is exempt from
* automatic reviews, or whether the user is on the list of always having
* its commits automatically reviewed.
*
* @param committer the username that made the commit (the system will use
* the committer mapping information to find the associated Crucible user)
* @return
*/
protected boolean isUnderScrutiny(String committer) {
final UserData crucibleUser = committerToCrucibleUser.get().get(committer);
final boolean userInList = crucibleUser != null &&
config.loadCrucibleUserNames().contains(crucibleUser.getUserName());
final boolean userInGroups = crucibleUser != null &&
Iterables.any(config.loadCrucibleGroups(), new Predicate<String>() {
public boolean apply(String group) {
return userManager.isUserInGroup(crucibleUser.getUserName(), group);
}
});
switch (config.loadCreateMode()) {
case ALWAYS:
return !(userInList || userInGroups);
case NEVER:
return userInList || userInGroups;
default:
throw new AssertionError("Unsupported create mode");
}
}
/**
* Attempts to add the change set to an existing open review by scanning
* the commit message for review IDs in the current project. When multiple
* IDs are found, the first non-closed review is used.
*
* @param repoKey
* @param cs
* @param project
* @return {@code true} if the change set was successfully added to an
* existing review, {@code false} otherwise.
*/
private boolean appendToReview(final String repoKey, final ChangesetDataFE cs, final ProjectData project) {
final ReviewData review = getFirstOpenReview(Utils.extractReviewIds(cs.getComment(), project.getKey()));
if (review != null) {
// impersonate the review's moderator (or creator if there is no moderator set):
return impersonator.doAsUser(null,
Utils.defaultIfNull(review.getModerator(), review.getCreator()).getUserName(),
new Operation<Boolean, RuntimeException>() {
public Boolean perform() throws RuntimeException {
try {
reviewService.addChangesetsToReview(review.getPermaId(), repoKey, Collections.singletonList(new ChangesetData(cs.getCsid())));
addComment(review, String.format(
"The Automatic Review Creator Plugin added changeset {cs:id=%s|rep=%s} to this review.",
cs.getCsid(), repoKey));
return true;
} catch (Exception e) {
logger.warn(String.format("Error appending changeset %s to review %s: %s",
cs.getCsid(), review.getPermaId().getId(), e.getMessage()), e);
}
return false;
}
});
}
return false;
}
/**
* Note that this check is broken in Crucible older than 2.2. In 2.1, the
* review state gets stale and won't always show the current state.
* See: http://jira.atlassian.com/browse/CRUC-2912
*
* @param reviewIds
* @return
*/
private ReviewData getFirstOpenReview(Iterable<String> reviewIds) {
final Collection<ReviewData.State> acceptableStates = ImmutableSet.of(
ReviewData.State.Draft,
ReviewData.State.Approval,
ReviewData.State.Review);
for (String reviewId : reviewIds) {
try {
final ReviewData review = reviewService.getReview(new PermId<ReviewData>(reviewId), false);
if (acceptableStates.contains(review.getState())) {
return review;
}
} catch (NotFoundException nfe) {
/* Exceptions for flow control is bad practice, but the API
* has no exists() method.
*/
}
}
return null;
}
private void createReview(final String repoKey, final ChangesetDataFE cs,
final ProjectData project)
throws ServerException {
final ReviewData template = buildReviewTemplate(cs, project);
// switch to user moderator:
impersonator.doAsUser(null, project.getDefaultModerator(), new Operation<Void, ServerException>() {
public Void perform() throws ServerException {
// create a new review:
final ReviewData review = reviewService.createReviewFromChangeSets(
template,
repoKey,
Collections.singletonList(new ChangesetData(cs.getCsid())));
// add the project's default reviewers:
addReviewers(review, project);
// start the review, so everyone is notified:
reviewService.changeState(review.getPermaId(), "action:approveReview");
addComment(review, "This review was created by the Automatic Review Creator Plugin.");
logger.info(String.format("Auto-created review %s for " +
"commit %s:%s with moderator %s.",
review.getPermaId(), repoKey,
cs.getCsid(), review.getModerator().getUserName()));
return null;
}
});
}
/**
* Must be called within the context of a user.
*
* @param review
* @param message
*/
private void addComment(final ReviewData review, final String message) {
final GeneralCommentData comment = new GeneralCommentData();
comment.setCreateDate(new Date());
comment.setDraft(false);
comment.setDeleted(false);
comment.setMessage(message);
try {
reviewService.addGeneralComment(review.getPermaId(), comment);
} catch (Exception e) {
logger.error(String.format("Unable to add a general comment to review %s: %s",
review.getPermaId().getId(), e.getMessage()), e);
}
}
private void addReviewers(ReviewData review, ProjectData project) {
final List<String> reviewers = project.getDefaultReviewerUsers();
if (reviewers != null && !reviewers.isEmpty()) {
reviewService.addReviewers(review.getPermaId(),
reviewers.toArray(new String[reviewers.size()]));
}
}
/**
* <p>
* This method must be invoked with admin permissions.
* </p>
*
* @param cs
* @param project
* @return
* @throws ServerException
*/
private ReviewData buildReviewTemplate(ChangesetDataFE cs, ProjectData project)
throws ServerException {
final UserData creator = committerToCrucibleUser.get().get(cs.getAuthor()) == null ?
userService.getUser(project.getDefaultModerator()) :
committerToCrucibleUser.get().get(cs.getAuthor());
final Date dueDate = project.getDefaultDuration() == null ? null :
DateHelper.addWorkingDays(new Date(), project.getDefaultDuration());
return new ReviewDataBuilder()
.setProjectKey(project.getKey())
.setName(Utils.firstNonEmptyLine(cs.getComment()))
.setDescription(StringUtils.defaultIfEmpty(project.getDefaultObjectives(), cs.getComment()))
.setAuthor(creator)
.setModerator(userService.getUser(project.getDefaultModerator()))
.setCreator(creator)
.setAllowReviewersToJoin(project.isAllowReviewersToJoin())
.setDueDate(dueDate)
.build();
}
/**
* <p>
* Given a FishEye repository key, returns the Crucible project that has
* this repository configured as its default.
* </p>
* <p>
* When no project is bound to the specified repository, or not enabled
* for automatic review creation, <code>null</code> is returned.
* </p>
* <p>
* This method must be invoked with admin permissions.
* </p>
*
* TODO: What to do when there are multiple projects?
*
* @param repoKey a FishEye repository key (e.g. "CR").
* @return the Crucible project that has the specified repository
* configured as its default repo and has been enabled for automatic
* review creation.
*/
private ProjectData getEnabledProjectForRepository(String repoKey) {
final List<ProjectData> projects = projectService.getAllProjects();
final List<String> enabled = config.loadEnabledProjects();
for (ProjectData project : projects) {
if (repoKey.equals(project.getDefaultRepositoryName()) &&
enabled.contains(project.getKey())) {
return project;
}
}
return null;
}
/**
* Returns a map containing all committer names that are mapped to Crucible
* user accounts.
* This is an expensive operation that will be redundant when the fecru SPI
* gets a <code>CommitterMapperService</code>.
* <p>
* This method must be invoked with admin permissions.
* </p>
*
* @param repoKey
* @return
*/
private Map<String, UserData> loadCommitterMappings(final String repoKey)
throws ServerException {
final Map<String, UserData> committerToUser = new HashMap<String, UserData>();
for (UserData ud : userService.getAllUsers()) {
final UserProfileData profile = userService.getUserProfile(ud.getUserName());
final List<String> committers = profile.getMappedCommitters().get(repoKey);
if (committers != null) {
for (String committer : committers) {
committerToUser.put(committer, ud);
}
}
}
return committerToUser;
}
private boolean isPluginEnabled() {
return !StringUtils.isEmpty(config.loadRunAsUser());
}
}
| false | true | public void handleEvent(Event event) {
final CommitEvent commit = (CommitEvent) event;
if (isPluginEnabled()) {
try {
// switch to admin user so we can access all projects and API services:
impersonator.doAsUser(null, config.loadRunAsUser(),
new Operation<Void, ServerException>() {
public Void perform() throws ServerException {
ChangesetDataFE cs = revisionService.getChangeset(
commit.getRepositoryName(), commit.getChangeSetId());
ProjectData project = getEnabledProjectForRepository(
commit.getRepositoryName());
committerToCrucibleUser.set(loadCommitterMappings(project.getDefaultRepositoryName()));
if (project != null) {
if (project.getDefaultModerator() != null) {
if (isUnderScrutiny(cs.getAuthor())) {
if (!config.loadIterative() || !appendToReview(commit.getRepositoryName(), cs, project)) {
// create a new review:
createReview(commit.getRepositoryName(), cs, project);
}
} else {
logger.info(String.format("Not creating a review for changeset %s.",
commit.getChangeSetId()));
}
} else {
logger.error(String.format("Unable to auto-create review for changeset %s. " +
"No default moderator configured for project %s.",
commit.getChangeSetId(), project.getKey()));
}
} else {
logger.error(String.format("Unable to auto-create review for changeset %s. " +
"No projects found that bind to repository %s.",
commit.getChangeSetId(), commit.getRepositoryName()));
}
return null;
}
});
} catch (Exception e) {
logger.error(String.format("Unable to auto-create " +
"review for changeset %s: %s.",
commit.getChangeSetId(), e.getMessage()), e);
}
}
}
| public void handleEvent(Event event) {
final CommitEvent commit = (CommitEvent) event;
if (isPluginEnabled()) {
try {
// switch to admin user so we can access all projects and API services:
impersonator.doAsUser(null, config.loadRunAsUser(),
new Operation<Void, ServerException>() {
public Void perform() throws ServerException {
final ChangesetDataFE cs = revisionService.getChangeset(
commit.getRepositoryName(), commit.getChangeSetId());
final ProjectData project = getEnabledProjectForRepository(
commit.getRepositoryName());
if (project != null) {
committerToCrucibleUser.set(loadCommitterMappings(project.getDefaultRepositoryName()));
if (project.getDefaultModerator() != null) {
if (isUnderScrutiny(cs.getAuthor())) {
if (!config.loadIterative() || !appendToReview(commit.getRepositoryName(), cs, project)) {
// create a new review:
createReview(commit.getRepositoryName(), cs, project);
}
} else {
logger.info(String.format("Not creating a review for changeset %s.",
commit.getChangeSetId()));
}
} else {
logger.error(String.format("Unable to auto-create review for changeset %s. " +
"No default moderator configured for project %s.",
commit.getChangeSetId(), project.getKey()));
}
} else {
logger.error(String.format("Unable to auto-create review for changeset %s. " +
"No projects found that bind to repository %s.",
commit.getChangeSetId(), commit.getRepositoryName()));
}
return null;
}
});
} catch (Exception e) {
logger.error(String.format("Unable to auto-create " +
"review for changeset %s: %s.",
commit.getChangeSetId(), e.getMessage()), e);
}
}
}
|
diff --git a/myForg/src/com/example/myforg/MainActivity.java b/myForg/src/com/example/myforg/MainActivity.java
index ffe5baa..c08cb43 100644
--- a/myForg/src/com/example/myforg/MainActivity.java
+++ b/myForg/src/com/example/myforg/MainActivity.java
@@ -1,207 +1,208 @@
package com.example.myforg;
import java.util.HashMap;
import java.util.Timer;
import java.util.TimerTask;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
import android.media.AudioManager;
import android.media.SoundPool;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.Menu;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
@SuppressLint("UseSparseArrays")
public class MainActivity extends Activity {
private SoundPool sp;
private int addTarget;
private HashMap<Integer, Integer> spMap;
private int source;
private int tagretsource;
private int timelimit;
private int maxSource;
private boolean hasPlaySound;
private Timer timer;
private Button btnFrog;
private Button btnFrogback;
private boolean start;
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
// TextView totalSouce;
TextView totalCount;
TextView remainTime;
TextView remainCount;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0);
spMap = new HashMap<Integer, Integer>();
spMap.put(1, sp.load(this, R.raw.clap, 1));
totalCount = (TextView) findViewById(R.id.totalSouce);
// totalCount = (TextView) findViewById(R.id.totalCount);
remainTime = (TextView) findViewById(R.id.remainTime);
remainCount = (TextView) findViewById(R.id.remainCount);
source=0;
timelimit=500;
tagretsource=20;
addTarget=0;
maxSource=this.getMaxSource();
hasPlaySound=false;
start=false;
updateText();
updateTime();
//
btnFrog = (Button) findViewById(R.id.button1);// ��ȡ��ť��Դ
btnFrogback = (Button) findViewById(R.id.button2);//��ȡ��ť��Դ
// Btn1���Ӽ���
btnFrog.setOnClickListener(new Button.OnClickListener() {// ��������
@Override
public void onClick(View v) {
if(start==false)
{
start=true;
if(timer==null)
{
timer = new Timer();
timer.schedule(timetask, 0, 10);
}
}
source++;
tagretsource--;
if (tagretsource == 0) {
addTarget++;
tagretsource = 20 + addTarget;
timelimit += 500;
}
if (source > maxSource) {
+ maxSource=source;
setMaxSource(source);
if (hasPlaySound == false) {
hasPlaySound = true;
sp.play(spMap.get(spMap.get(1)), 50, 50, 1, 0, 1);
}
}
updateText();
}
});
btnFrogback.setOnClickListener(new Button.OnClickListener() {// ��������
@Override
public void onClick(View v) {
source=0;
timelimit=500;
tagretsource=20;
addTarget=0;
updateText();
updateTime();
start=false;
-// timer.purge();
+ hasPlaySound = false;
btnFrog.setClickable(true);
}
});
//
//
//
// // BtnGo ���Ӽ���������ҳ�����ת
// BtnGo.setOnClickListener(new Button.OnClickListener() {// ��������
// @Override
// public void onClick(View v) {
// String strTmp = String.valueOf(a++);
// Ev1.setText(strTmp);
// sp.play(spMap.get(spMap.get(1)), 50, 50, 1, 0, 1);
// Intent intentGo = new Intent();
// intentGo.setClass(MainActivity.this, ChronometerActivity.class);
// startActivity(intentGo);
// finish();
// }
//
// });
}
Handler handler = new Handler() {
public void handleMessage(Message msg) {
addTenMMS();
super.handleMessage(msg);
}
};
TimerTask timetask = new TimerTask() {
public void run() {
Message message = new Message();
message.what = 1;
handler.sendMessage(message);
}
};
//��ʮ����
private void addTenMMS() {
if(start)
{
timelimit -= 1;
}
if (timelimit <= 0) {
timelimit=0;
// timer.cancel();
btnFrog.setClickable(false);
}
updateTime();
}
private void updateText() {
totalCount.setText("Source:" + source);
// totalCount.setText("Source:" + tagretsource);
remainCount.setText("Target:" + tagretsource);
}
private void updateTime(){
remainTime.setText("Remain:" + Double.toString((double)timelimit/100) + "s");
}
private int getMaxSource() {
// return 5;
// ��ȡSharedPreferences����
Context ctx = MainActivity.this;
SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
return sp.getInt("maxSource", 0);
}
private void setMaxSource(int source){
Context ctx = MainActivity.this;
SharedPreferences sp = ctx.getSharedPreferences("SP", MODE_PRIVATE);
// ��������
Editor editor = sp.edit();
editor.putInt("maxSource",source );
editor.commit();
return ;
}
}
| false | true | public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0);
spMap = new HashMap<Integer, Integer>();
spMap.put(1, sp.load(this, R.raw.clap, 1));
totalCount = (TextView) findViewById(R.id.totalSouce);
// totalCount = (TextView) findViewById(R.id.totalCount);
remainTime = (TextView) findViewById(R.id.remainTime);
remainCount = (TextView) findViewById(R.id.remainCount);
source=0;
timelimit=500;
tagretsource=20;
addTarget=0;
maxSource=this.getMaxSource();
hasPlaySound=false;
start=false;
updateText();
updateTime();
//
btnFrog = (Button) findViewById(R.id.button1);// ��ȡ��ť��Դ
btnFrogback = (Button) findViewById(R.id.button2);//��ȡ��ť��Դ
// Btn1���Ӽ���
btnFrog.setOnClickListener(new Button.OnClickListener() {// ��������
@Override
public void onClick(View v) {
if(start==false)
{
start=true;
if(timer==null)
{
timer = new Timer();
timer.schedule(timetask, 0, 10);
}
}
source++;
tagretsource--;
if (tagretsource == 0) {
addTarget++;
tagretsource = 20 + addTarget;
timelimit += 500;
}
if (source > maxSource) {
setMaxSource(source);
if (hasPlaySound == false) {
hasPlaySound = true;
sp.play(spMap.get(spMap.get(1)), 50, 50, 1, 0, 1);
}
}
updateText();
}
});
btnFrogback.setOnClickListener(new Button.OnClickListener() {// ��������
@Override
public void onClick(View v) {
source=0;
timelimit=500;
tagretsource=20;
addTarget=0;
updateText();
updateTime();
start=false;
// timer.purge();
btnFrog.setClickable(true);
}
});
//
//
//
// // BtnGo ���Ӽ���������ҳ�����ת
// BtnGo.setOnClickListener(new Button.OnClickListener() {// ��������
// @Override
// public void onClick(View v) {
// String strTmp = String.valueOf(a++);
// Ev1.setText(strTmp);
// sp.play(spMap.get(spMap.get(1)), 50, 50, 1, 0, 1);
// Intent intentGo = new Intent();
// intentGo.setClass(MainActivity.this, ChronometerActivity.class);
// startActivity(intentGo);
// finish();
// }
//
// });
}
| public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
sp = new SoundPool(2, AudioManager.STREAM_SYSTEM, 0);
spMap = new HashMap<Integer, Integer>();
spMap.put(1, sp.load(this, R.raw.clap, 1));
totalCount = (TextView) findViewById(R.id.totalSouce);
// totalCount = (TextView) findViewById(R.id.totalCount);
remainTime = (TextView) findViewById(R.id.remainTime);
remainCount = (TextView) findViewById(R.id.remainCount);
source=0;
timelimit=500;
tagretsource=20;
addTarget=0;
maxSource=this.getMaxSource();
hasPlaySound=false;
start=false;
updateText();
updateTime();
//
btnFrog = (Button) findViewById(R.id.button1);// ��ȡ��ť��Դ
btnFrogback = (Button) findViewById(R.id.button2);//��ȡ��ť��Դ
// Btn1���Ӽ���
btnFrog.setOnClickListener(new Button.OnClickListener() {// ��������
@Override
public void onClick(View v) {
if(start==false)
{
start=true;
if(timer==null)
{
timer = new Timer();
timer.schedule(timetask, 0, 10);
}
}
source++;
tagretsource--;
if (tagretsource == 0) {
addTarget++;
tagretsource = 20 + addTarget;
timelimit += 500;
}
if (source > maxSource) {
maxSource=source;
setMaxSource(source);
if (hasPlaySound == false) {
hasPlaySound = true;
sp.play(spMap.get(spMap.get(1)), 50, 50, 1, 0, 1);
}
}
updateText();
}
});
btnFrogback.setOnClickListener(new Button.OnClickListener() {// ��������
@Override
public void onClick(View v) {
source=0;
timelimit=500;
tagretsource=20;
addTarget=0;
updateText();
updateTime();
start=false;
hasPlaySound = false;
btnFrog.setClickable(true);
}
});
//
//
//
// // BtnGo ���Ӽ���������ҳ�����ת
// BtnGo.setOnClickListener(new Button.OnClickListener() {// ��������
// @Override
// public void onClick(View v) {
// String strTmp = String.valueOf(a++);
// Ev1.setText(strTmp);
// sp.play(spMap.get(spMap.get(1)), 50, 50, 1, 0, 1);
// Intent intentGo = new Intent();
// intentGo.setClass(MainActivity.this, ChronometerActivity.class);
// startActivity(intentGo);
// finish();
// }
//
// });
}
|
diff --git a/benchmark/src/com/sun/sgs/benchmark/client/BenchmarkClient.java b/benchmark/src/com/sun/sgs/benchmark/client/BenchmarkClient.java
index 9c489a750..210c73bb9 100644
--- a/benchmark/src/com/sun/sgs/benchmark/client/BenchmarkClient.java
+++ b/benchmark/src/com/sun/sgs/benchmark/client/BenchmarkClient.java
@@ -1,774 +1,776 @@
/*
* Copyright 2007 Sun Microsystems, Inc. All rights reserved
*/
package com.sun.sgs.benchmark.client;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectOutputStream;
import java.io.PushbackInputStream;
import java.io.UnsupportedEncodingException;
import java.nio.charset.Charset;
import java.text.ParseException;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Properties;
import java.util.Set;
import com.sun.sgs.benchmark.client.listener.*;
import com.sun.sgs.benchmark.shared.MethodRequest;
import com.sun.sgs.client.ClientChannel;
import com.sun.sgs.client.ClientChannelListener;
import com.sun.sgs.client.SessionId;
import com.sun.sgs.client.simple.SimpleClientListener;
import com.sun.sgs.client.simple.SimpleClient;
/**
* A simple GUI chat client that interacts with an SGS server-side app.
* It presents an IRC-like interface, with channels, member lists, and
* private (off-channel) messaging.
* <p>
* The {@code BenchmarkClient} understands the following properties:
* <ul>
* <li><code>{@value #HOST_PROPERTY}</code> <br>
* <i>Default:</i> {@value #DEFAULT_HOST} <br>
* The hostname of the {@code BenchmarkApp} server.<p>
*
* <li><code>{@value #PORT_PROPERTY}</code> <br>
* <i>Default:</i> {@value #DEFAULT_PORT} <br>
* The port of the {@code BenchmarkApp} server.<p>
*
* <li><code>{@value #LOGIN_PROPERTY}</code> <br>
* <i>Default:</i> {@value #DEFAULT_LOGIN} <br>
* The login name used when logging into the server.<p>
*
* <li><code>{@value #PASSWORD_PROPERTY}</code> <br>
* <i>Default:</i> {@value #DEFAULT_PASSWORD} <br>
* The password name used when logging into the server.<p>
*
* </ul>
*/
public class BenchmarkClient
{
/** The version of the serialized form of this class. */
private static final long serialVersionUID = 1L;
/** The name of the host property */
public static final String HOST_PROPERTY = "BenchmarkClient.host";
/** The default hostname */
public static final String DEFAULT_HOST = "localhost";
/** The name of the port property */
public static final String PORT_PROPERTY = "BenchmarkClient.port";
/** The default port */
public static final String DEFAULT_PORT = "2502";
/** The {@link Charset} encoding for client/server messages */
public static final String MESSAGE_CHARSET = "UTF-8";
/** Handles listener multiplexing. */
private BenchmarkClientListener masterListener = new BenchmarkClientListener();
/** Used for communication with the server */
private SimpleClient client = new SimpleClient(masterListener);
/** The mapping between sessions and names */
private final Map<SessionId, String> sessionNames =
new HashMap<SessionId, String>();
/** Provides convenient lookup of channels by name. */
private Map<String,ClientChannel> channels =
new HashMap<String,ClientChannel>();
/** The userName (i.e. login) for this client's session. */
private String login;
/** Used to perform the wait-for operation. */
private Object waitLock = new Object();
/** Variables to keep track of things while processing input: */
/** Whether we are inside a block. */
private boolean inBlock = false;
/**
* The active onEvent command. If this reference is non-null, then either
* we are inside of a block (as indicated by the inblock variable being
* true) or the immediately previous line was an on_event command.
*/
private ScriptingCommand onEventCmd = null;
/**
* The list of commands being stored up following an onEvent command. The
* contents of this list are only valid if onEventCmd is non-null.
*/
private List<ScriptingCommand> onEventCmdList;
// Constructor
/**
* Creates a new {@code BenchmarkClient}.
*/
public BenchmarkClient() {
/** Register ourselves for a few events with the master listener. */
masterListener.registerLoggedInListener(new LoggedInListener() {
public void loggedIn() {
SessionId session = client.getSessionId();
sessionNames.put(session, login);
System.out.println("Notice: Logged in with session ID " + session);
}
});
masterListener.registerLoginFailedListener(new LoginFailedListener() {
public void loginFailed(String reason) {
System.out.println("Notice: Login failed: " + reason);
}
});
masterListener.registerDisconnectedListener(new DisconnectedListener() {
public void disconnected(boolean graceful, String reason) {
System.out.println("Notice: Disconnected " +
(graceful ? "gracefully" : "ungracefully") +
": " + reason);
}
});
masterListener.registerJoinedChannelListener(new JoinedChannelListener() {
public void joinedChannel(ClientChannel channel) {
channels.put(channel.getName(), channel);
}
});
masterListener.registerServerMessageListener(new ServerMessageListener() {
public void receivedMessage(byte[] message) {
System.out.println("Notice: (from server) " +
fromMessageBytes(message));
}
});
}
// Main
/**
* Runs a new {@code BenchmarkClient} application.
*
* @param args the commandline arguments (not used)
*/
public static void main(String[] args) {
PushbackInputStream stdin = new PushbackInputStream(System.in, 100);
String line;
int lineNum = 0;
BenchmarkClient client = new BenchmarkClient();
try {
while (!isEOF(stdin)) {
line = getInputLine(stdin, 100);
if (line != null) {
lineNum++;
line = line.trim();
if (line.length() > 0 && (!line.startsWith("#"))) {
try {
client.processInput(line);
} catch (ParseException e) {
System.err.println("Syntax error on line " +
lineNum + ": " + e.getMessage());
}
}
}
else {
try {
Thread.currentThread().sleep(100); // ms
} catch (InterruptedException e) { }
}
}
} catch (IOException e) {
System.err.println("Reading stdin: " + e);
System.exit(-1);
return;
}
System.exit(0);
}
/** Public Methods */
public void processInput(String line) throws ParseException {
ScriptingCommand cmd = ScriptingCommand.parse(line);
/** Check for control flow commands */
switch (cmd.getType()) {
case END_BLOCK:
if (!inBlock) {
throw new ParseException("Close brace with no matching" +
" open brace.", 0);
}
assignEventHandler(onEventCmd.getEvent(), onEventCmdList);
onEventCmd = null;
inBlock = false;
break;
case ON_EVENT:
if (inBlock) {
throw new ParseException("Nested blocks are not supported.", 0);
}
if (onEventCmd != null) {
throw new ParseException("Sequential on_event commands; " +
"perhaps a command is missing in between?", 0);
}
onEventCmd = cmd;
onEventCmdList = new LinkedList<ScriptingCommand>();
break;
case START_BLOCK:
if (inBlock) {
throw new ParseException("Nested blocks are not supported.", 0);
}
if (onEventCmd == null) {
throw new ParseException("Blocks can only start immediately" +
" following on_event commands.", 0);
}
inBlock = true;
break;
default:
/**
* If we are not in a block, but onEventCmd is not null, then this
* command immediately followed an onEvent command.
*/
if (!inBlock && onEventCmd != null) {
onEventCmdList.add(cmd);
assignEventHandler(onEventCmd.getEvent(), onEventCmdList);
onEventCmd = null;
}
/** Else, if we are in a block, then just store this command. */
else if (inBlock) {
onEventCmdList.add(cmd);
}
/** Else, just a normal situation: execute command now. */
else {
executeCommand(cmd);
}
}
}
/*
* PRIVATE METHODS
*/
private void assignEventHandler(ScriptingEvent event,
final List<ScriptingCommand> cmds)
{
/*
* TODO - some of these commands might want to take the arguments of the
* event call in as arguments themselves. Not sure best way to do that.
*/
switch (event) {
case DISCONNECTED:
masterListener.registerDisconnectedListener(new DisconnectedListener() {
public void disconnected(boolean graceful, String reason) {
executeCommands(cmds);
}
});
break;
case JOINED_CHANNEL:
masterListener.registerJoinedChannelListener(new JoinedChannelListener() {
public void joinedChannel(ClientChannel channel) {
executeCommands(cmds);
}
});
break;
case LEFT_CHANNEL:
masterListener.registerLeftChannelListener(new LeftChannelListener() {
public void leftChannel(String channelName) {
executeCommands(cmds);
}
});
break;
case LOGGED_IN:
masterListener.registerLoggedInListener(new LoggedInListener() {
public void loggedIn() {
executeCommands(cmds);
}
});
break;
case LOGIN_FAILED:
masterListener.registerLoginFailedListener(new LoginFailedListener() {
public void loginFailed(String reason) {
executeCommands(cmds);
}
});
break;
case RECONNECTED:
masterListener.registerReconnectedListener(new ReconnectedListener() {
public void reconnected() {
executeCommands(cmds);
}
});
break;
case RECONNECTING:
masterListener.registerReconnectingListener(new ReconnectingListener() {
public void reconnecting() {
executeCommands(cmds);
}
});
break;
case RECV_CHANNEL:
masterListener.registerChannelMessageListener(new ChannelMessageListener() {
public void receivedMessage(String channelName,
SessionId sender, byte[] message)
{
executeCommands(cmds);
}
});
break;
case RECV_DIRECT:
masterListener.registerServerMessageListener(new ServerMessageListener() {
public void receivedMessage(byte[] message) {
executeCommands(cmds);
}
});
break;
default:
throw new IllegalArgumentException("Unsupported event: " + event);
}
}
/*
* TODO - since this handles calls from both SimpleClientListener and
* ClientChannelListener, could calls on those 2 interfaces be mixed,
* meaning we should synchronize to protect member variables?
*/
private void executeCommand(ScriptingCommand cmd) {
try {
System.out.println("# Executing: " + cmd.getType());
for (int i=0; i < cmd.getCount(); i++) {
switch (cmd.getType()) {
case CPU:
sendServerMessage(new MethodRequest("CPU",
new Object[] { cmd.getDuration() } ));
break;
case CREATE_CHANNEL:
sendServerMessage(new MethodRequest("CREATE_CHANNEL",
new Object[] { cmd.getChannelName() } ));
break;
case DATASTORE:
System.out.println("not yet implemented - TODO");
break;
case DISCONNECT:
client.logout(true); /* force */
break;
case EXIT:
System.exit(0);
break;
case HELP:
if (cmd.getTopic() == null) {
System.out.println(ScriptingCommand.getHelpString());
} else {
System.out.println(ScriptingCommand.getHelpString(cmd.getTopic()));
}
break;
case JOIN_CHANNEL:
sendServerMessage(new MethodRequest("JOIN_CHANNEL",
new Object[] { cmd.getChannelName() }));
break;
case LEAVE_CHANNEL:
sendServerMessage("/leave " + cmd.getChannelName());
break;
case LOGIN:
sendLogin(cmd.getLogin(), cmd.getPassword());
break;
case LOGOUT:
client.logout(false); /* non-force */
break;
case MALLOC:
cmd.getSize();
System.out.println("not yet implemented - TODO");
break;
case PRINT:
boolean first = true;
StringBuilder sb = new StringBuilder("PRINT: ");
for (String arg : cmd.getPrintArgs()) {
if (first) first = false;
else sb.append(", ");
sb.append(arg);
}
System.out.println(sb);
return;
case SEND_CHANNEL:
// need to somehow get a handle to the channel -- probably will need
// to save a map of channel-names to ClientChannel objects (which
// get passed to you in joinedChannel() event call)
cmd.getChannelName();
cmd.getMessage();
cmd.getRecipients();
//sendServerMessage("/chsend ");
System.out.println("not yet implemented - TODO");
break;
case SEND_DIRECT:
sendServerMessage(cmd.getMessage());
break;
case WAIT_FOR:
/** Register listener to call notify() when event happens. */
modifyNotificationEventHandler(cmd.getEvent(), true);
while (true) {
try {
- waitLock.wait();
+ synchronized(waitLock) {
+ waitLock.wait();
+ }
/**
* Unregister listener so it doesn't screw up
* future WAIT_FOR commands.
*/
modifyNotificationEventHandler(cmd.getEvent(), false);
break; /** Only break after wait() returns normally. */
}
catch (InterruptedException e) { }
}
break;
default:
throw new IllegalStateException("ERROR! executeCommand() does" +
" not support command type " + cmd.getType());
}
}
} catch (IOException e) {
System.err.println(e);
}
}
private void executeCommands(List<ScriptingCommand> cmds) {
for (ScriptingCommand cmd : cmds)
executeCommand(cmd);
}
private void modifyNotificationEventHandler(ScriptingEvent event,
boolean register)
{
switch (event) {
case DISCONNECTED:
masterListener.registerDisconnectedListener(new DisconnectedListener() {
public void disconnected(boolean graceful, String reason) {
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
case JOINED_CHANNEL:
masterListener.registerJoinedChannelListener(new JoinedChannelListener() {
public void joinedChannel(ClientChannel channel) {
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
case LEFT_CHANNEL:
masterListener.registerLeftChannelListener(new LeftChannelListener() {
public void leftChannel(String channelName) {
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
case LOGGED_IN:
masterListener.registerLoggedInListener(new LoggedInListener() {
public void loggedIn() {
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
case LOGIN_FAILED:
masterListener.registerLoginFailedListener(new LoginFailedListener() {
public void loginFailed(String reason) {
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
case RECONNECTED:
masterListener.registerReconnectedListener(new ReconnectedListener() {
public void reconnected() {
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
case RECONNECTING:
masterListener.registerReconnectingListener(new ReconnectingListener() {
public void reconnecting() {
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
case RECV_CHANNEL:
masterListener.registerChannelMessageListener(new ChannelMessageListener() {
public void receivedMessage(String channelName,
SessionId sender, byte[] message)
{
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
case RECV_DIRECT:
masterListener.registerServerMessageListener(new ServerMessageListener() {
public void receivedMessage(byte[] message) {
synchronized(waitLock) {
waitLock.notifyAll();
}
}
});
break;
default:
throw new IllegalArgumentException("Unsupported event: " + event);
}
}
private void sendLogin(String login, String password) throws IOException {
String host = System.getProperty(HOST_PROPERTY, DEFAULT_HOST);
String port = System.getProperty(PORT_PROPERTY, DEFAULT_PORT);
/**
* The "master listener" needs the login and password for
* SimpleClientListener.getPasswordAuthentication()
*/
masterListener.setPasswordAuthentication(login, password);
this.login = login;
System.out.println("Notice: Connecting to " + host + ":" + port);
Properties props = new Properties();
props.put("host", host);
props.put("port", port);
client.login(props);
}
private void sendServerMessage(MethodRequest req) throws IOException {
ByteArrayOutputStream baos = new ByteArrayOutputStream();
ObjectOutputStream oos = new ObjectOutputStream(baos);
oos.writeObject(req);
oos.close();
client.send(baos.toByteArray());
}
private void sendServerMessage(String message) throws IOException {
client.send(toMessageBytes(message));
}
/**
* Nicely format a {@link SessionId} for printed display.
*
* @param session the {@code SessionId} to format
* @return the formatted string
*/
private String formatSession(SessionId session) {
return sessionNames.get(session) + " [" +
toHexString(session.toBytes()) + "]";
}
/**
* Returns a string constructed with the contents of the byte
* array converted to hex format.
*
* @param bytes a byte array to convert
* @return the converted byte array as a hex-formatted string
*/
public static String toHexString(byte[] bytes) {
StringBuilder buf = new StringBuilder(2 * bytes.length);
for (byte b : bytes) {
buf.append(String.format("%02X", b));
}
return buf.toString();
}
/**
* Returns a byte array constructed with the contents of the given
* string, which contains a series of byte values in hex format.
*
* @param hexString a string to convert
* @return the byte array corresponding to the hex-formatted string
*/
public static byte[] fromHexString(String hexString) {
byte[] bytes = new byte[hexString.length() / 2];
for (int i = 0; i < bytes.length; ++i) {
String hexByte = hexString.substring(2*i, 2*i+2);
bytes[i] = Integer.valueOf(hexByte, 16).byteValue();
}
return bytes;
}
private static String getInputLine(PushbackInputStream is, int readAheadLimit)
throws IOException
{
int readTotal = 0;
byte ba[] = new byte[readAheadLimit];
while (readTotal < readAheadLimit) {
if (is.available() == 0) break;
int readlen = is.read(ba, readTotal, readAheadLimit - readTotal);
for (int i=0; i < readlen; i++) {
if (ba[readTotal + i] == '\n') {
is.unread(ba, readTotal + i + 1, readlen - (i + 1));
return new String(ba, 0, readTotal + i);
}
}
readTotal += readlen;
}
is.unread(ba, 0, readTotal);
return null;
}
private static boolean isEOF(PushbackInputStream is)
throws IOException
{
if (is.available() > 0) {
int c = is.read();
if (c == -1) return true;
is.unread(c);
}
return false;
}
private void userLogin(String memberString) {
System.err.println("userLogin: " + memberString);
}
private void userLogout(String idString) {
System.err.println("userLogout: " + idString);
SessionId session = SessionId.fromBytes(fromHexString(idString));
sessionNames.remove(session);
}
// Implement ClientChannelListener
/**
* {@inheritDoc}
*/
/*
public void receivedMessage(ClientChannel channel, SessionId sender,
byte[] message)
{
try {
String messageString = fromMessageBytes(message);
System.err.format("Recv on %s from %s: %s\n",
channel.getName(), sender, messageString);
String[] args = messageString.split(" ", 2);
String command = args[0];
if (command.equals("/joined")) {
userLogin(args[1]);
} else if (command.equals("/left")) {
userLogout(args[1]);
} else if (command.equals("/members")) {
List<String> members = Arrays.asList(args[1].split(" "));
if (! members.isEmpty()) {
//
}
} else if (command.equals("/pm")) {
pmReceived(sender, args[1]);
} else if (command.startsWith("/")) {
System.err.format("Unknown command: %s\n", command);
} else {
System.err.format("Not a command: %s\n", messageString);
}
} catch (Exception e) {
e.printStackTrace();
}
}
*/
/**
* Decodes the given {@code bytes} into a message string.
*
* @param bytes the encoded message
* @return the decoded message string
*/
public static String fromMessageBytes(byte[] bytes) {
try {
return new String(bytes, MESSAGE_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new Error("Required charset UTF-8 not found", e);
}
}
/**
* Encodes the given message string into a byte array.
*
* @param s the message string to encode
* @return the encoded message as a byte array
*/
public static byte[] toMessageBytes(String s) {
try {
return s.getBytes(MESSAGE_CHARSET);
} catch (UnsupportedEncodingException e) {
throw new Error("Required charset UTF-8 not found", e);
}
}
}
| true | true | private void executeCommand(ScriptingCommand cmd) {
try {
System.out.println("# Executing: " + cmd.getType());
for (int i=0; i < cmd.getCount(); i++) {
switch (cmd.getType()) {
case CPU:
sendServerMessage(new MethodRequest("CPU",
new Object[] { cmd.getDuration() } ));
break;
case CREATE_CHANNEL:
sendServerMessage(new MethodRequest("CREATE_CHANNEL",
new Object[] { cmd.getChannelName() } ));
break;
case DATASTORE:
System.out.println("not yet implemented - TODO");
break;
case DISCONNECT:
client.logout(true); /* force */
break;
case EXIT:
System.exit(0);
break;
case HELP:
if (cmd.getTopic() == null) {
System.out.println(ScriptingCommand.getHelpString());
} else {
System.out.println(ScriptingCommand.getHelpString(cmd.getTopic()));
}
break;
case JOIN_CHANNEL:
sendServerMessage(new MethodRequest("JOIN_CHANNEL",
new Object[] { cmd.getChannelName() }));
break;
case LEAVE_CHANNEL:
sendServerMessage("/leave " + cmd.getChannelName());
break;
case LOGIN:
sendLogin(cmd.getLogin(), cmd.getPassword());
break;
case LOGOUT:
client.logout(false); /* non-force */
break;
case MALLOC:
cmd.getSize();
System.out.println("not yet implemented - TODO");
break;
case PRINT:
boolean first = true;
StringBuilder sb = new StringBuilder("PRINT: ");
for (String arg : cmd.getPrintArgs()) {
if (first) first = false;
else sb.append(", ");
sb.append(arg);
}
System.out.println(sb);
return;
case SEND_CHANNEL:
// need to somehow get a handle to the channel -- probably will need
// to save a map of channel-names to ClientChannel objects (which
// get passed to you in joinedChannel() event call)
cmd.getChannelName();
cmd.getMessage();
cmd.getRecipients();
//sendServerMessage("/chsend ");
System.out.println("not yet implemented - TODO");
break;
case SEND_DIRECT:
sendServerMessage(cmd.getMessage());
break;
case WAIT_FOR:
/** Register listener to call notify() when event happens. */
modifyNotificationEventHandler(cmd.getEvent(), true);
while (true) {
try {
waitLock.wait();
/**
* Unregister listener so it doesn't screw up
* future WAIT_FOR commands.
*/
modifyNotificationEventHandler(cmd.getEvent(), false);
break; /** Only break after wait() returns normally. */
}
catch (InterruptedException e) { }
}
break;
default:
throw new IllegalStateException("ERROR! executeCommand() does" +
" not support command type " + cmd.getType());
}
}
} catch (IOException e) {
System.err.println(e);
}
}
| private void executeCommand(ScriptingCommand cmd) {
try {
System.out.println("# Executing: " + cmd.getType());
for (int i=0; i < cmd.getCount(); i++) {
switch (cmd.getType()) {
case CPU:
sendServerMessage(new MethodRequest("CPU",
new Object[] { cmd.getDuration() } ));
break;
case CREATE_CHANNEL:
sendServerMessage(new MethodRequest("CREATE_CHANNEL",
new Object[] { cmd.getChannelName() } ));
break;
case DATASTORE:
System.out.println("not yet implemented - TODO");
break;
case DISCONNECT:
client.logout(true); /* force */
break;
case EXIT:
System.exit(0);
break;
case HELP:
if (cmd.getTopic() == null) {
System.out.println(ScriptingCommand.getHelpString());
} else {
System.out.println(ScriptingCommand.getHelpString(cmd.getTopic()));
}
break;
case JOIN_CHANNEL:
sendServerMessage(new MethodRequest("JOIN_CHANNEL",
new Object[] { cmd.getChannelName() }));
break;
case LEAVE_CHANNEL:
sendServerMessage("/leave " + cmd.getChannelName());
break;
case LOGIN:
sendLogin(cmd.getLogin(), cmd.getPassword());
break;
case LOGOUT:
client.logout(false); /* non-force */
break;
case MALLOC:
cmd.getSize();
System.out.println("not yet implemented - TODO");
break;
case PRINT:
boolean first = true;
StringBuilder sb = new StringBuilder("PRINT: ");
for (String arg : cmd.getPrintArgs()) {
if (first) first = false;
else sb.append(", ");
sb.append(arg);
}
System.out.println(sb);
return;
case SEND_CHANNEL:
// need to somehow get a handle to the channel -- probably will need
// to save a map of channel-names to ClientChannel objects (which
// get passed to you in joinedChannel() event call)
cmd.getChannelName();
cmd.getMessage();
cmd.getRecipients();
//sendServerMessage("/chsend ");
System.out.println("not yet implemented - TODO");
break;
case SEND_DIRECT:
sendServerMessage(cmd.getMessage());
break;
case WAIT_FOR:
/** Register listener to call notify() when event happens. */
modifyNotificationEventHandler(cmd.getEvent(), true);
while (true) {
try {
synchronized(waitLock) {
waitLock.wait();
}
/**
* Unregister listener so it doesn't screw up
* future WAIT_FOR commands.
*/
modifyNotificationEventHandler(cmd.getEvent(), false);
break; /** Only break after wait() returns normally. */
}
catch (InterruptedException e) { }
}
break;
default:
throw new IllegalStateException("ERROR! executeCommand() does" +
" not support command type " + cmd.getType());
}
}
} catch (IOException e) {
System.err.println(e);
}
}
|
diff --git a/temp2/CA/src/Datapath.java b/temp2/CA/src/Datapath.java
index 391ac1a..0399153 100644
--- a/temp2/CA/src/Datapath.java
+++ b/temp2/CA/src/Datapath.java
@@ -1,307 +1,307 @@
public class Datapath {
long pc = 0;
Adder adder = new Adder();
Control control = new Control();
IM im = new IM();
Registers registerFile = new Registers();
ALU alu = new ALU();
DM dm = new DM();
Mux mux = new Mux();
reg $zero = new reg();
reg $at = new reg();
reg $v0 = new reg();
reg $v1 = new reg();
reg $a0 = new reg();
reg $a1 = new reg();
reg $a2 = new reg();
reg $a3 = new reg();
reg $t0 = new reg();
reg $t1 = new reg();
reg $t2 = new reg();
reg $t3 = new reg();
reg $t4 = new reg();
reg $t5 = new reg();
reg $t6 = new reg();
reg $t7 = new reg();
reg $s0 = new reg();
reg $s1 = new reg();
reg $s2 = new reg();
reg $s3 = new reg();
reg $s4 = new reg();
reg $s5 = new reg();
reg $s6 = new reg();
reg $s7 = new reg();
reg $t8 = new reg();
reg $t9 = new reg();
reg $k0 = new reg();
reg $k1 = new reg();
reg $gp = new reg();
reg $sp = new reg();
reg $fp = new reg();
reg $ra = new reg();
boolean zero = false;
public void performInstruction(String ins) {
// String Instruction = im.getInstruction(pc);
pc = adder.add(pc, 4);
String[] z = ins.split(" ");
String in = z[0];
if (z.length == 2) {
control.set_controler("000010");
if (z[0].equals("000011")) {
long y = pc + 4;
String x = Long.toBinaryString(y);
this.$ra.data = x;
}
String nPC = Long.toBinaryString(pc);
nPC = nPC.charAt(0) + nPC.charAt(1) + nPC.charAt(2) + nPC.charAt(3)
+ z[1] + "00";
String w=Long.toBinaryString(pc);
String q = mux.select(w, nPC, control.jump);
long PC=Long.parseLong(q);
pc=PC;
} else {
control.set_controler(in);
registerFile.setRregister1(this.findRegByOpcode(z[1]));
registerFile.setRregister2(this.findRegByOpcode(z[2]));
String resultMux = mux.select(z[2], z[3], control.regDst);
registerFile.setWregister(this.findRegByOpcode(resultMux));
String r2 = registerFile.rregister2.data;
String signExtend = "";
if (z[3].charAt(0) == '1') {
signExtend = "1111111111111111" + z[3];
} else {
signExtend = "0000000000000000" + z[3];
}
String resultMux2 = mux.select(r2, signExtend, control.ALUSrc);
String signExtendedShiftedByTwo = Long.toBinaryString(Long
.parseLong(signExtend, 2) << 2);
long resultAdder2 = adder.add(pc,
Long.parseLong(signExtendedShiftedByTwo, 2));
String aluRes = "";
if (in.equals("000000")) {
if(z[5].equals("000000")||z[5].equals("000010")){
- aluRes = alu.performOperation(registerFile.rregister1.data, z[4], Integer.parseInt(z[5]));
+ aluRes = alu.performOperation(registerFile.rregister2.data, z[4], Integer.parseInt(z[5]));
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
else{
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, Integer.parseInt(z[5]));
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
}
if (in.equals("000100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100010);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
if (in.equals("001000")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
}
if (in.equals("001101")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100101);
}
if (in.equals("001100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100100);
}
String dataRead = "";
if (control.MemRead == 1) {
if (in.equals("100011")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
if (in.equals("100001")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
String part0 = aluRes;
String part1 = Long.toBinaryString(Long
.parseLong(aluRes, 2) + 1);
dataRead = dm.readData(part0) + dm.readData(part1);
}
if (in.equals("001100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
dataRead = dm.readData(aluRes);
}
}
if (control.MemWrite == 1) {
if (in.equals("101011")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100010);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
dataRead = "";
if (control.MemRead == 1) {
if (in.equals("100011")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
String part0 = aluRes;
String part1 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 1);
String part2 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 2);
String part3 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 3);
dataRead = dm.readData(part0) + dm.readData(part1)
+ dm.readData(part2) + dm.readData(part3);
}
}
if (control.MemWrite == 1) {
if (in.equals("101011")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(0, 8));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 1), registerFile.rregister1.data
.substring(8, 16));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 2), registerFile.rregister1.data
.substring(16, 25));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 3), registerFile.rregister1.data
.substring(25, 32));
}
if (in.equals("101001")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(8, 16));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 1), registerFile.rregister1.data
.substring(0, 8));
}
if (in.equals("101000")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(0, 8));
}
}
}
boolean branch = false;
if (control.branch == 0) {
branch = true;
} else {
branch = false;
}
int controlAdderTwo = 0;
if (branch && zero) {
controlAdderTwo = 1;
}
pc = mux.select(pc, resultAdder2, controlAdderTwo);
String resultMux3 = mux.select(aluRes, dataRead, control.MemToReg);
if (control.RegWrite == 1) {
registerFile.setWdata(resultMux3);
this.findRegByOpcode(resultMux).data = registerFile.getWdata();
System.out.println("Result of operation: "
+ registerFile.wregister.data);
}
}
}
public reg findRegByOpcode(String s) {
if (s.equals("10001")) {
return this.$s1;
} else if (s.equals("10010")) {
return this.$s2;
} else {
return this.$s3;
}
}
public String translate(String x) {
String result = "";
String[] a;
a = x.split(" ");
if (a[0].equals("ADD")) {
result += "0000000";
}
result += getRegOpcode(a[2]);
result += getRegOpcode(a[3]);
result += getRegOpcode(a[1]);
return result;
}
public String getRegOpcode(String a) {
if (a.equals("$s1")) {
return "10001";
} else if (a.equals("$s2")) {
return "10010";
} else {
/* $s3 */return "10011";
}
}
public static void main(String[] args) {
Datapath p = new Datapath();
p.$s1.set("00001000000000000000000000000110");
p.$s2.set("11010000000000000000000000000011");
p.$s3.set("10");
p.performInstruction("000000 10001 10010 10011 00000 100111");
p.performInstruction("101011 10010 10010 000000000000000001");
p.performInstruction("100011 10010 10010 000000000000000001");
p.performInstruction("001000 10001 10010 000000000001100100");
}
}
| true | true | public void performInstruction(String ins) {
// String Instruction = im.getInstruction(pc);
pc = adder.add(pc, 4);
String[] z = ins.split(" ");
String in = z[0];
if (z.length == 2) {
control.set_controler("000010");
if (z[0].equals("000011")) {
long y = pc + 4;
String x = Long.toBinaryString(y);
this.$ra.data = x;
}
String nPC = Long.toBinaryString(pc);
nPC = nPC.charAt(0) + nPC.charAt(1) + nPC.charAt(2) + nPC.charAt(3)
+ z[1] + "00";
String w=Long.toBinaryString(pc);
String q = mux.select(w, nPC, control.jump);
long PC=Long.parseLong(q);
pc=PC;
} else {
control.set_controler(in);
registerFile.setRregister1(this.findRegByOpcode(z[1]));
registerFile.setRregister2(this.findRegByOpcode(z[2]));
String resultMux = mux.select(z[2], z[3], control.regDst);
registerFile.setWregister(this.findRegByOpcode(resultMux));
String r2 = registerFile.rregister2.data;
String signExtend = "";
if (z[3].charAt(0) == '1') {
signExtend = "1111111111111111" + z[3];
} else {
signExtend = "0000000000000000" + z[3];
}
String resultMux2 = mux.select(r2, signExtend, control.ALUSrc);
String signExtendedShiftedByTwo = Long.toBinaryString(Long
.parseLong(signExtend, 2) << 2);
long resultAdder2 = adder.add(pc,
Long.parseLong(signExtendedShiftedByTwo, 2));
String aluRes = "";
if (in.equals("000000")) {
if(z[5].equals("000000")||z[5].equals("000010")){
aluRes = alu.performOperation(registerFile.rregister1.data, z[4], Integer.parseInt(z[5]));
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
else{
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, Integer.parseInt(z[5]));
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
}
if (in.equals("000100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100010);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
if (in.equals("001000")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
}
if (in.equals("001101")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100101);
}
if (in.equals("001100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100100);
}
String dataRead = "";
if (control.MemRead == 1) {
if (in.equals("100011")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
if (in.equals("100001")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
String part0 = aluRes;
String part1 = Long.toBinaryString(Long
.parseLong(aluRes, 2) + 1);
dataRead = dm.readData(part0) + dm.readData(part1);
}
if (in.equals("001100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
dataRead = dm.readData(aluRes);
}
}
if (control.MemWrite == 1) {
if (in.equals("101011")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100010);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
dataRead = "";
if (control.MemRead == 1) {
if (in.equals("100011")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
String part0 = aluRes;
String part1 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 1);
String part2 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 2);
String part3 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 3);
dataRead = dm.readData(part0) + dm.readData(part1)
+ dm.readData(part2) + dm.readData(part3);
}
}
if (control.MemWrite == 1) {
if (in.equals("101011")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(0, 8));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 1), registerFile.rregister1.data
.substring(8, 16));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 2), registerFile.rregister1.data
.substring(16, 25));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 3), registerFile.rregister1.data
.substring(25, 32));
}
if (in.equals("101001")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(8, 16));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 1), registerFile.rregister1.data
.substring(0, 8));
}
if (in.equals("101000")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(0, 8));
}
}
}
boolean branch = false;
if (control.branch == 0) {
branch = true;
} else {
branch = false;
}
int controlAdderTwo = 0;
if (branch && zero) {
controlAdderTwo = 1;
}
pc = mux.select(pc, resultAdder2, controlAdderTwo);
String resultMux3 = mux.select(aluRes, dataRead, control.MemToReg);
if (control.RegWrite == 1) {
registerFile.setWdata(resultMux3);
this.findRegByOpcode(resultMux).data = registerFile.getWdata();
System.out.println("Result of operation: "
+ registerFile.wregister.data);
}
}
}
| public void performInstruction(String ins) {
// String Instruction = im.getInstruction(pc);
pc = adder.add(pc, 4);
String[] z = ins.split(" ");
String in = z[0];
if (z.length == 2) {
control.set_controler("000010");
if (z[0].equals("000011")) {
long y = pc + 4;
String x = Long.toBinaryString(y);
this.$ra.data = x;
}
String nPC = Long.toBinaryString(pc);
nPC = nPC.charAt(0) + nPC.charAt(1) + nPC.charAt(2) + nPC.charAt(3)
+ z[1] + "00";
String w=Long.toBinaryString(pc);
String q = mux.select(w, nPC, control.jump);
long PC=Long.parseLong(q);
pc=PC;
} else {
control.set_controler(in);
registerFile.setRregister1(this.findRegByOpcode(z[1]));
registerFile.setRregister2(this.findRegByOpcode(z[2]));
String resultMux = mux.select(z[2], z[3], control.regDst);
registerFile.setWregister(this.findRegByOpcode(resultMux));
String r2 = registerFile.rregister2.data;
String signExtend = "";
if (z[3].charAt(0) == '1') {
signExtend = "1111111111111111" + z[3];
} else {
signExtend = "0000000000000000" + z[3];
}
String resultMux2 = mux.select(r2, signExtend, control.ALUSrc);
String signExtendedShiftedByTwo = Long.toBinaryString(Long
.parseLong(signExtend, 2) << 2);
long resultAdder2 = adder.add(pc,
Long.parseLong(signExtendedShiftedByTwo, 2));
String aluRes = "";
if (in.equals("000000")) {
if(z[5].equals("000000")||z[5].equals("000010")){
aluRes = alu.performOperation(registerFile.rregister2.data, z[4], Integer.parseInt(z[5]));
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
else{
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, Integer.parseInt(z[5]));
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
}
if (in.equals("000100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100010);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
if (in.equals("001000")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
}
if (in.equals("001101")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100101);
}
if (in.equals("001100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100100);
}
String dataRead = "";
if (control.MemRead == 1) {
if (in.equals("100011")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
if (in.equals("100001")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
String part0 = aluRes;
String part1 = Long.toBinaryString(Long
.parseLong(aluRes, 2) + 1);
dataRead = dm.readData(part0) + dm.readData(part1);
}
if (in.equals("001100")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100000);
dataRead = dm.readData(aluRes);
}
}
if (control.MemWrite == 1) {
if (in.equals("101011")) {
aluRes = alu.performOperation(registerFile.rregister1.data,
resultMux2, 100010);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
}
dataRead = "";
if (control.MemRead == 1) {
if (in.equals("100011")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
String part0 = aluRes;
String part1 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 1);
String part2 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 2);
String part3 = Long.toBinaryString(Long.parseLong(
aluRes, 2) + 3);
dataRead = dm.readData(part0) + dm.readData(part1)
+ dm.readData(part2) + dm.readData(part3);
}
}
if (control.MemWrite == 1) {
if (in.equals("101011")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(0, 8));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 1), registerFile.rregister1.data
.substring(8, 16));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 2), registerFile.rregister1.data
.substring(16, 25));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 3), registerFile.rregister1.data
.substring(25, 32));
}
if (in.equals("101001")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(8, 16));
dm.writeData(Long.toBinaryString(Long.parseLong(aluRes,
2) + 1), registerFile.rregister1.data
.substring(0, 8));
}
if (in.equals("101000")) {
aluRes = alu.performOperation(
registerFile.rregister1.data, resultMux2,
100000);
if (Long.parseLong(aluRes, 2) == 0) {
zero = true;
}
dm.writeData(
Long.toBinaryString(Long.parseLong(aluRes, 2)),
registerFile.rregister1.data.substring(0, 8));
}
}
}
boolean branch = false;
if (control.branch == 0) {
branch = true;
} else {
branch = false;
}
int controlAdderTwo = 0;
if (branch && zero) {
controlAdderTwo = 1;
}
pc = mux.select(pc, resultAdder2, controlAdderTwo);
String resultMux3 = mux.select(aluRes, dataRead, control.MemToReg);
if (control.RegWrite == 1) {
registerFile.setWdata(resultMux3);
this.findRegByOpcode(resultMux).data = registerFile.getWdata();
System.out.println("Result of operation: "
+ registerFile.wregister.data);
}
}
}
|
diff --git a/src/enderdom/eddie/tools/bio/Tools_Panther.java b/src/enderdom/eddie/tools/bio/Tools_Panther.java
index 539360c..90959d5 100644
--- a/src/enderdom/eddie/tools/bio/Tools_Panther.java
+++ b/src/enderdom/eddie/tools/bio/Tools_Panther.java
@@ -1,110 +1,110 @@
package enderdom.eddie.tools.bio;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.net.URI;
import java.net.URISyntaxException;
import java.net.URL;
import java.util.LinkedList;
import org.apache.log4j.Logger;
import enderdom.eddie.bio.homology.PantherGene;
import enderdom.eddie.tools.Tools_String;
public class Tools_Panther {
private static String panthr = "pantherdb.org";
private static String search = "/webservices/garuda/search.jsp";
/**
*
* @param pantherterm eg PTHR22751
* @return list of genes attached to panther term as PantherGene objects
* @throws EddieException
* @throws URISyntaxException
* @throws IOException
*/
public static PantherGene[] getGeneList(String pantherterm) throws EddieException, URISyntaxException, IOException{
//Check actually a panther acc
if(!pantherterm.startsWith("PTHR")){
Logger.getRootLogger().warn("Panther term does not start with PTHR, adding");
if(Tools_String.parseString2Int(pantherterm) == null){
throw new EddieException("Panther term "+pantherterm+"is not correct, should be like PTHR22751");
}
else{
pantherterm="PTHR"+pantherterm;
}
}
else Logger.getRootLogger().debug("Panther term is good");
//Get uRL
- URI uri = new URI("http", panthr, search, "keyword=PTHR22751&listType=gene&type=getList", null);
+ URI uri = new URI("http", panthr, search, "keyword="+pantherterm+"&listType=gene&type=getList", null);
URL site = uri.toURL();
//Read into buffer
Logger.getRootLogger().debug("Accessing Panther databse via http...");
BufferedReader in = new BufferedReader(new InputStreamReader(site.openStream()));
//Url shoudl have returned a column file such as:
/*
Gene Accession Gene Name Gene Symbol
SCHMA|Gene=Smp_149580|UniProtKB=G4LXZ6 Peptide (FMRFamide/somatostatin)-like receptor,putative G4LXZ6
SCHMA|Gene=Smp_041700|UniProtKB=G4M0H4 Rhodopsin-like orphan GPCR,putative G4M0H4
SCHMA|Gene=Smp_161500|UniProtKB=G4LXX9 Rhodopsin-like orphan GPCR, putative G4LXX9
...
*/
//Skip Header
String inputLine;
LinkedList<PantherGene> genes =new LinkedList<PantherGene>();
Logger.getRootLogger().debug("Parsing Panther Gene list");
while ((inputLine = in.readLine()) != null){
if(inputLine.length() > 0 && !inputLine.startsWith("Gene Accession")){
PantherGene gene = new PantherGene();
String[] split = inputLine.split("\\|");
if(split.length != 3){
throw new EddieException("Line should be splittable with '|', line is not. (Line: " + inputLine+")");
}
gene.setShortSpecies(split[0]);
gene.setDbLink(split[0]);
String[] resplit = split[2].split("\\t");
if(split.length != 3){
throw new EddieException("Line should be splittable with '\\t', line is not. (Line: " + split[2]+")");
}
gene.setGeneAcc(resplit[0]);
gene.setGeneName(resplit[1]);
gene.setGeneSymbol(resplit[2]);
genes.add(gene);
}
System.out.print("\r"+ genes.size()+" genes from panther ");
}
System.out.println();
Logger.getRootLogger().info(genes.size()+" Panther Gene objects retrieved");
in.close();
return genes.toArray(new PantherGene[0]);
}
/**
*
* @param longname species longname, must only be 2 words ie Xenopus tropicalis
* @return the Panther short name species or null if the species is not available int the panther database
* @throws EddieException
* @throws URISyntaxException
* @throws IOException
*/
public static String getShortSpeciesName(String longname) throws EddieException, URISyntaxException, IOException{
URI uri = new URI("http", panthr, search, "type=organism", null);
URL site = uri.toURL();
BufferedReader in = new BufferedReader(new InputStreamReader(site.openStream()));
String inputLine;
while ((inputLine = in.readLine()) != null){
if(inputLine.length() > 0 && !inputLine.startsWith("Long Name")){
if(inputLine.toLowerCase().contains(longname.toLowerCase())){
String[] splits = inputLine.split("\\t");
return splits[splits.length-1];
}
}
}
return null;
}
}
| true | true | public static PantherGene[] getGeneList(String pantherterm) throws EddieException, URISyntaxException, IOException{
//Check actually a panther acc
if(!pantherterm.startsWith("PTHR")){
Logger.getRootLogger().warn("Panther term does not start with PTHR, adding");
if(Tools_String.parseString2Int(pantherterm) == null){
throw new EddieException("Panther term "+pantherterm+"is not correct, should be like PTHR22751");
}
else{
pantherterm="PTHR"+pantherterm;
}
}
else Logger.getRootLogger().debug("Panther term is good");
//Get uRL
URI uri = new URI("http", panthr, search, "keyword=PTHR22751&listType=gene&type=getList", null);
URL site = uri.toURL();
//Read into buffer
Logger.getRootLogger().debug("Accessing Panther databse via http...");
BufferedReader in = new BufferedReader(new InputStreamReader(site.openStream()));
//Url shoudl have returned a column file such as:
/*
Gene Accession Gene Name Gene Symbol
SCHMA|Gene=Smp_149580|UniProtKB=G4LXZ6 Peptide (FMRFamide/somatostatin)-like receptor,putative G4LXZ6
SCHMA|Gene=Smp_041700|UniProtKB=G4M0H4 Rhodopsin-like orphan GPCR,putative G4M0H4
SCHMA|Gene=Smp_161500|UniProtKB=G4LXX9 Rhodopsin-like orphan GPCR, putative G4LXX9
...
*/
//Skip Header
String inputLine;
LinkedList<PantherGene> genes =new LinkedList<PantherGene>();
Logger.getRootLogger().debug("Parsing Panther Gene list");
while ((inputLine = in.readLine()) != null){
if(inputLine.length() > 0 && !inputLine.startsWith("Gene Accession")){
PantherGene gene = new PantherGene();
String[] split = inputLine.split("\\|");
if(split.length != 3){
throw new EddieException("Line should be splittable with '|', line is not. (Line: " + inputLine+")");
}
gene.setShortSpecies(split[0]);
gene.setDbLink(split[0]);
String[] resplit = split[2].split("\\t");
if(split.length != 3){
throw new EddieException("Line should be splittable with '\\t', line is not. (Line: " + split[2]+")");
}
gene.setGeneAcc(resplit[0]);
gene.setGeneName(resplit[1]);
gene.setGeneSymbol(resplit[2]);
genes.add(gene);
}
System.out.print("\r"+ genes.size()+" genes from panther ");
}
System.out.println();
Logger.getRootLogger().info(genes.size()+" Panther Gene objects retrieved");
in.close();
return genes.toArray(new PantherGene[0]);
}
| public static PantherGene[] getGeneList(String pantherterm) throws EddieException, URISyntaxException, IOException{
//Check actually a panther acc
if(!pantherterm.startsWith("PTHR")){
Logger.getRootLogger().warn("Panther term does not start with PTHR, adding");
if(Tools_String.parseString2Int(pantherterm) == null){
throw new EddieException("Panther term "+pantherterm+"is not correct, should be like PTHR22751");
}
else{
pantherterm="PTHR"+pantherterm;
}
}
else Logger.getRootLogger().debug("Panther term is good");
//Get uRL
URI uri = new URI("http", panthr, search, "keyword="+pantherterm+"&listType=gene&type=getList", null);
URL site = uri.toURL();
//Read into buffer
Logger.getRootLogger().debug("Accessing Panther databse via http...");
BufferedReader in = new BufferedReader(new InputStreamReader(site.openStream()));
//Url shoudl have returned a column file such as:
/*
Gene Accession Gene Name Gene Symbol
SCHMA|Gene=Smp_149580|UniProtKB=G4LXZ6 Peptide (FMRFamide/somatostatin)-like receptor,putative G4LXZ6
SCHMA|Gene=Smp_041700|UniProtKB=G4M0H4 Rhodopsin-like orphan GPCR,putative G4M0H4
SCHMA|Gene=Smp_161500|UniProtKB=G4LXX9 Rhodopsin-like orphan GPCR, putative G4LXX9
...
*/
//Skip Header
String inputLine;
LinkedList<PantherGene> genes =new LinkedList<PantherGene>();
Logger.getRootLogger().debug("Parsing Panther Gene list");
while ((inputLine = in.readLine()) != null){
if(inputLine.length() > 0 && !inputLine.startsWith("Gene Accession")){
PantherGene gene = new PantherGene();
String[] split = inputLine.split("\\|");
if(split.length != 3){
throw new EddieException("Line should be splittable with '|', line is not. (Line: " + inputLine+")");
}
gene.setShortSpecies(split[0]);
gene.setDbLink(split[0]);
String[] resplit = split[2].split("\\t");
if(split.length != 3){
throw new EddieException("Line should be splittable with '\\t', line is not. (Line: " + split[2]+")");
}
gene.setGeneAcc(resplit[0]);
gene.setGeneName(resplit[1]);
gene.setGeneSymbol(resplit[2]);
genes.add(gene);
}
System.out.print("\r"+ genes.size()+" genes from panther ");
}
System.out.println();
Logger.getRootLogger().info(genes.size()+" Panther Gene objects retrieved");
in.close();
return genes.toArray(new PantherGene[0]);
}
|
diff --git a/src-plugins/FFMPEG_IO/plugin/src/main/java/fiji/ffmpeg/IO.java b/src-plugins/FFMPEG_IO/plugin/src/main/java/fiji/ffmpeg/IO.java
index 35570c4..f143627 100644
--- a/src-plugins/FFMPEG_IO/plugin/src/main/java/fiji/ffmpeg/IO.java
+++ b/src-plugins/FFMPEG_IO/plugin/src/main/java/fiji/ffmpeg/IO.java
@@ -1,661 +1,661 @@
package fiji.ffmpeg;
import ij.IJ;
import ij.ImagePlus;
import ij.ImageStack;
import ij.VirtualStack;
import ij.process.ByteProcessor;
import ij.process.ColorProcessor;
import ij.process.ImageProcessor;
import ij.process.ShortProcessor;
import java.io.File;
import java.io.IOException;
import com.sun.jna.Library;
import com.sun.jna.Memory;
import com.sun.jna.Native;
import com.sun.jna.Platform;
import com.sun.jna.Pointer;
import com.sun.jna.ptr.IntByReference;
import com.sun.jna.ptr.PointerByReference;
import fiji.ffmpeg.AVCODEC.AVCodec;
import fiji.ffmpeg.AVCODEC.AVCodecContext;
import fiji.ffmpeg.AVCODEC.AVFrame;
import fiji.ffmpeg.AVCODEC.AVPacket;
import fiji.ffmpeg.AVCODEC.AVPicture;
import fiji.ffmpeg.AVFORMAT.AVFormatContext;
import fiji.ffmpeg.AVFORMAT.AVOutputFormat;
import fiji.ffmpeg.AVFORMAT.AVStream;
import fiji.ffmpeg.AVLOG.AvLog;
public class IO extends FFMPEG implements Progress {
protected AVFormatContext formatContext;
protected AVCodecContext codecContext;
protected AVCodec codec;
protected IntByReference gotPicture = new IntByReference();
protected int bufferFramePixelFormat = AVUTIL.PIX_FMT_RGB24;
protected AVFrame frame, bufferFrame;
protected Pointer swsContext;
protected byte[] videoOutbut;
protected Memory videoOutbutMemory;
protected AVPacket packet = new AVPacket();
protected Progress progress;
public interface C extends Library {
int snprintf(Pointer buffer, Long size, String fmt, Pointer va_list);
}
protected C C;
public IO() throws IOException {
super();
if (!loadFFMPEG())
throw new IOException("Could not load the FFMPEG library!");
AVLOG.avSetLogCallback(new AvLog() {
public void callback(String line) {
IJ.log(line);
}
});
}
public IO(Progress progress) throws IOException {
this();
setProgress(progress);
}
public void setProgress(Progress progress) {
this.progress = progress;
}
public void start(String message) {
if (progress != null)
progress.start(message);
}
public void step(String message, double progress) {
if (this.progress != null)
this.progress.step(message, progress);
}
public void done(String message) {
if (progress != null)
progress.done(message);
}
public void log(String message) {
if (progress != null)
progress.log(message);
}
/**
* Based on the AVCodecSample example from ffmpeg-java by Ken Larson.
*/
public ImagePlus readMovie(String path, boolean useVirtualStack, final int first, final int last) throws IOException {
/* Need to do this because we already extend ImagePlus */
if (!loadFFMPEG())
throw new IOException("Could not load the FFMPEG library!");
if (AVCODEC.avcodec_version() != AVCODEC.LIBAVCODEC_VERSION_INT)
throw new IOException("ffmpeg versions mismatch: native " + AVCODEC.avcodec_version()
+ " != Java-bindings " + AVCODEC.LIBAVCODEC_VERSION_INT);
step("Opening " + path, 0);
AVFORMAT.av_register_all();
// Open video file
final PointerByReference formatContextPointer = new PointerByReference();
if (AVFORMAT.av_open_input_file(formatContextPointer, path, null, 0, null) != 0)
throw new IOException("Could not open " + path);
formatContext = new AVFormatContext(formatContextPointer.getValue());
// Retrieve stream information
if (AVFORMAT.av_find_stream_info(formatContext) < 0)
throw new IOException("No stream in " + path);
// Find the first video stream
int videoStream = -1;
for (int i = 0; i < formatContext.nb_streams; i++) {
final AVStream stream = new AVStream(formatContext.streams[i]);
codecContext = new AVCodecContext(stream.codec);
if (codecContext.codec_type == AVCODEC.CODEC_TYPE_VIDEO) {
videoStream = i;
break;
}
}
if (codecContext == null)
throw new IOException("No video stream in " + path);
if (codecContext.codec_id == 0)
throw new IOException("Codec not available");
// Find and open the decoder for the video stream
codec = AVCODEC.avcodec_find_decoder(codecContext.codec_id);
if (codec == null || AVCODEC.avcodec_open(codecContext, codec) < 0)
throw new IOException("Codec not available");
allocateFrames(false);
final AVStream stream = new AVStream(formatContext.streams[videoStream]);
if (useVirtualStack) {
// TODO: handle stream.duration == 0 by counting the frames
if (stream.duration == 0)
throw new IOException("Cannot determine stack size (duration is 0)");
final int videoStreamIndex = videoStream;
ImageStack stack = new VirtualStack(codecContext.width, codecContext.height, null, null) {
int previousSlice = -1;
long frameDuration = guessFrameDuration();
public void finalize() {
free();
}
public int getSize() {
int size = (int)(stream.duration / frameDuration);
if (last >= 0)
size = Math.min(last, size);
if (first > 0)
size -= first;
return size;
}
public String getSliceLabel(int slice) {
return ""; // maybe calculate the time?
}
public long guessFrameDuration() {
if (AVFORMAT.av_read_frame(formatContext, packet) < 0)
return 1;
long firstPTS = packet.pts;
int frameCount = 5;
for (int i = 0; i < frameCount; previousSlice = i++)
if (AVFORMAT.av_read_frame(formatContext, packet) < 0)
return 1;
return (packet.pts - firstPTS) / frameCount;
}
// TODO: cache two
public ImageProcessor getProcessor(int slice) {
long time = (first + slice - 1) * frameDuration;
if (time > 0)
time -= frameDuration / 2;
if (stream.start_time != 0x8000000000000000l /* TODO: AVUTIL.AV_NOPTS_VALUE */)
time += stream.start_time;
if (previousSlice != slice - 1)
AVFORMAT.av_seek_frame(formatContext, videoStreamIndex, time,
AVFORMAT.AVSEEK_FLAG_BACKWARD);
for (;;) {
if (AVFORMAT.av_read_frame(formatContext, packet) < 0) {
packet.data = null;
packet.size = 0;
break;
}
if (packet.stream_index != videoStreamIndex)
continue;
if (previousSlice == slice - 1 || packet.pts >= time)
break;
AVCODEC.avcodec_decode_video2(codecContext, frame, gotPicture, packet);
}
previousSlice = slice;
return readOneFrame(packet);
}
};
done("Opened " + path + " as virtual stack");
return new ImagePlus(path, stack);
}
double factor = stream.duration > 0 ? 1.0 / stream.duration : 0;
if (last >= 0)
factor = 1.0 / last;
ImageStack stack = new ImageStack(codecContext.width, codecContext.height);
int frameCounter = 0;
- start("Writing " + path);
+ start("Reading " + path);
while (AVFORMAT.av_read_frame(formatContext, packet) >= 0 &&
(last < 0 || frameCounter < last)) {
// Is this a packet from the video stream?
if (packet.stream_index != videoStream)
continue;
step(null, frameCounter * factor);
ImageProcessor ip = readOneFrame(packet);
if (ip != null && frameCounter++ >= first)
stack.addSlice(null, ip);
}
// Read the last frame
packet.data = null;
packet.size = 0;
ImageProcessor ip = readOneFrame(packet);
if (ip != null)
stack.addSlice(null, ip);
free();
done("Opened " + path);
return new ImagePlus(path, stack);
}
protected void allocateFrames(boolean forEncoding) {
// Allocate video frame
if (frame == null) {
frame = AVCODEC.avcodec_alloc_frame();
if (frame == null)
throw new OutOfMemoryError("Could not allocate frame");
if (forEncoding) {
// Allocate buffer
if (AVCODEC.avpicture_alloc(new AVPicture(frame.getPointer()),
codecContext.pix_fmt, codecContext.width, codecContext.height) < 0)
throw new OutOfMemoryError("Could not allocate tmp frame");
frame.read();
}
}
// Allocate an AVFrame structure
if (bufferFrame == null) {
bufferFramePixelFormat = AVUTIL.PIX_FMT_RGB24;
if (codecContext.pix_fmt == AVUTIL.PIX_FMT_GRAY8 ||
codecContext.pix_fmt == AVUTIL.PIX_FMT_MONOWHITE ||
codecContext.pix_fmt == AVUTIL.PIX_FMT_MONOBLACK ||
codecContext.pix_fmt == AVUTIL.PIX_FMT_PAL8)
bufferFramePixelFormat = AVUTIL.PIX_FMT_GRAY8;
else if (codecContext.pix_fmt == AVUTIL.PIX_FMT_GRAY16BE ||
codecContext.pix_fmt == AVUTIL.PIX_FMT_GRAY16LE)
bufferFramePixelFormat = AVUTIL.PIX_FMT_GRAY16BE;
bufferFrame = AVCODEC.avcodec_alloc_frame();
if (bufferFrame == null)
throw new RuntimeException("Could not allocate frame");
// Allocate buffer
if (AVCODEC.avpicture_alloc(new AVPicture(bufferFrame.getPointer()),
bufferFramePixelFormat, codecContext.width, codecContext.height) < 0)
throw new OutOfMemoryError("Could not allocate tmp frame");
bufferFrame.read();
}
if (swsContext == null) {
swsContext = SWSCALE.sws_getContext(codecContext.width, codecContext.height,
forEncoding ? bufferFramePixelFormat : codecContext.pix_fmt,
codecContext.width, codecContext.height,
forEncoding ? codecContext.pix_fmt : bufferFramePixelFormat,
SWSCALE.SWS_BICUBIC, null, null, null);
if (swsContext == null)
throw new OutOfMemoryError("Could not allocate swscale context");
}
}
protected ImageProcessor readOneFrame(AVPacket packet) {
// Decode video frame
AVCODEC.avcodec_decode_video2(codecContext, frame, gotPicture, packet);
// Did we get a video frame?
if (gotPicture.getValue() == 0)
return null;
// Convert the image from its native format to RGB
convertTo();
return toSlice(bufferFrame, codecContext.width, codecContext.height);
}
protected void convertTo() {
SWSCALE.sws_scale(swsContext, frame.data, frame.linesize, 0, codecContext.height, bufferFrame.data, bufferFrame.linesize);
}
protected void convertFrom() {
SWSCALE.sws_scale(swsContext, bufferFrame.data, bufferFrame.linesize, 0, codecContext.height, frame.data, frame.linesize);
}
protected void free() {
// Free the RGB image
if (bufferFrame != null) {
AVUTIL.av_free(bufferFrame.getPointer());
bufferFrame = null;
}
// Close the codec
if (codecContext != null) {
AVCODEC.avcodec_close(codecContext);
codecContext = null;
}
// Close the video file
if (formatContext != null) {
if (formatContext.iformat != null)
AVFORMAT.av_close_input_file(formatContext);
formatContext = null;
}
if (swsContext != null) {
SWSCALE.sws_freeContext(swsContext);
swsContext = null;
}
}
protected ImageProcessor toSlice(AVFrame frame, int width, int height) {
final int len = height * frame.linesize[0];
final byte[] data = frame.data[0].getByteArray(0, len);
if (bufferFramePixelFormat == AVUTIL.PIX_FMT_RGB24) {
int[] pixels = new int[width * height];
for (int j = 0; j < height; j++) {
final int off = j * frame.linesize[0];
for (int i = 0; i < width; i++)
pixels[i + j * width] =
((data[off + 3 * i]) & 0xff) << 16 |
((data[off + 3 * i + 1]) & 0xff) << 8 |
((data[off + 3 * i + 2]) & 0xff);
}
return new ColorProcessor(width, height, pixels);
}
if (bufferFramePixelFormat == AVUTIL.PIX_FMT_GRAY16BE) {
short[] pixels = new short[width * height];
for (int j = 0; j < height; j++) {
final int off = j * frame.linesize[0];
for (int i = 0; i < width; i++)
pixels[i + j * width] = (short)
(((data[off + 2 * i]) & 0xff) << 8 |
((data[off + 2 * i + 1]) & 0xff));
}
return new ShortProcessor(width, height, pixels, null);
}
if (bufferFramePixelFormat == AVUTIL.PIX_FMT_GRAY8 ||
bufferFramePixelFormat == AVUTIL.PIX_FMT_PAL8) {
byte[] pixels = new byte[width * height];
for (int j = 0; j < height; j++) {
final int off = j * frame.linesize[0];
for (int i = 0; i < width; i++)
pixels[i + j * width] = (byte)
((data[off + i]) & 0xff);
}
/* TODO: in case of PAL8, we should get a colormap */
return new ByteProcessor(width, height, pixels, null);
}
throw new RuntimeException("Unhandled pixel format: " + bufferFramePixelFormat);
}
public static int strncpy(byte[] dst, String src) {
int len = Math.min(src.length(), dst.length - 1);
System.arraycopy(src.getBytes(), 0, dst, 0, len);
dst[len] = 0;
return len;
}
public void writeMovie(ImagePlus image, String path, int frameRate, int bitRate) throws IOException {
final int STREAM_PIX_FMT = AVUTIL.PIX_FMT_YUV420P;
//int swsFlags = SWScaleLibrary.SWS_BICUBIC;
AVOutputFormat fmt = null;
double videoPts;
int i;
ImageStack stack;
stack = image.getStack();
start("Writing " + path);
/* initialize libavcodec, and register all codecs and formats */
AVFORMAT.av_register_all();
/* auto detect the output format from the name. default is
mpeg. */
fmt = AVFORMAT.guess_format(null, new File(path).getName(), null);
if (fmt == null) {
IJ.log("Could not deduce output format from file extension: using MPEG.");
fmt = AVFORMAT.guess_format("mpeg2video", null, null);
}
if (fmt == null)
throw new IOException("Could not find suitable output format");
/* allocate the output media context */
formatContext = AVFORMAT.av_alloc_format_context();
if (formatContext == null)
throw new OutOfMemoryError("Could not allocate format context");
formatContext.oformat = fmt.getPointer();
strncpy(formatContext.filename, path);
/* add the video stream using the default format
* codec and initialize the codec */
if (fmt.video_codec == AVCODEC.CODEC_ID_NONE)
throw new IOException("Could not determine codec for " + path);
AVStream videoSt = addVideoStream(formatContext, fmt.video_codec, stack.getWidth(), stack.getHeight(), frameRate, bitRate, STREAM_PIX_FMT);
if (videoSt == null)
throw new IOException("Could not add a video stream");
/* set the output parameters (mustbe done even if no
* parameters). */
if (AVFORMAT.av_set_parameters(formatContext, null) < 0)
throw new IOException("Invalid output format parameters.");
/* now that all the parameters are set, we can open the
* video codec and allocate the necessary encode buffer */
openVideo(formatContext, videoSt);
// Dump the format to stderr
AVFORMAT.dump_format(formatContext, 0, path, 1);
AVOutputFormat tmpFmt = new AVOutputFormat(formatContext.oformat);
if ((tmpFmt.flags & AVFORMAT.AVFMT_RAWPICTURE) == 0) {
/* allocate output buffer */
/* buffers passed into lav* can be allocated any way you prefer,
as long as they're aligned enough for the architecture, and
they're freed appropriately (such as using av_free for buffers
allocated with av_malloc) */
videoOutbut = new byte[200000];
}
/* open the output file, if needed */
if ((fmt.flags & AVFORMAT.AVFMT_NOFILE) == 0) {
final PointerByReference p = new PointerByReference();
if (AVFORMAT.url_fopen(p, path, AVFORMAT.URL_WRONLY) < 0)
throw new IOException("Could not open " + path);
formatContext.pb = p.getValue();
}
bufferFramePixelFormat = AVUTIL.PIX_FMT_RGB24;
switch (image.getType()) {
case ImagePlus.GRAY8:
bufferFramePixelFormat = AVUTIL.PIX_FMT_PAL8;
case ImagePlus.GRAY16:
bufferFramePixelFormat = AVUTIL.PIX_FMT_GRAY16BE;
}
allocateFrames(true);
AVFORMAT.av_write_header(formatContext);
videoPts = (double)videoSt.pts.val * videoSt.time_base.num / videoSt.time_base.den;
for (int frameCount = 1; frameCount <= stack.getSize(); frameCount++) {
/* write video frame */
step(null, frameCount / (double)stack.getSize());
writeVideoFrame(stack.getProcessor(frameCount), formatContext, videoSt);
}
// flush last frame
//writeVideoFrame(null, formatContext, videoSt);
/* write the trailer, if any */
AVFORMAT.av_write_trailer(formatContext);
/* close codec */
//closeVideo(formatContext, videoSt);
/* free the streams */
for (i = 0; i < formatContext.nb_streams; i++) {
AVStream tmpStream = new AVStream(formatContext.streams[i]);
AVUTIL.av_free(tmpStream.codec);
AVUTIL.av_free(formatContext.streams[i]);
}
if ((fmt.flags & AVFORMAT.AVFMT_NOFILE) == 0) {
/* close the output file */
AVFORMAT.url_fclose(formatContext.pb);
}
//free();
}
protected void writeVideoFrame(ImageProcessor ip, AVFormatContext formatContext, AVStream st) throws IOException {
int outSize = 0;
//SwsContext imgConvertCtx = null;
if (ip == null) {
/* no more frame to compress. The codec has a latency of a few
frames if using B frames, so we get the last frames by
passing the same picture again */
} else {
if (codecContext.pix_fmt == bufferFramePixelFormat)
fillImage(frame, ip);
else {
fillImage(bufferFrame, ip);
convertFrom();
}
}
AVOutputFormat tmpFmt = new AVOutputFormat(formatContext.oformat);
if ((tmpFmt.flags & AVFORMAT.AVFMT_RAWPICTURE) != 0) {
/* raw video case. The API will change slightly in the near
future for that */
AVCODEC.av_init_packet(packet);
packet.flags |= AVCODEC.PKT_FLAG_KEY;
packet.stream_index = st.index;
packet.data = frame.getPointer();
packet.size = frame.size();
if (AVFORMAT.av_interleaved_write_frame(formatContext, packet) != 0)
throw new IOException("Error while writing video frame");
} else {
/* encode the image */
if (videoOutbutMemory == null)
videoOutbutMemory = new Memory(videoOutbut.length);
// TODO: special-case avcodec_encode_video() to take a Pointer to avoid frequent copying
outSize = AVCODEC.avcodec_encode_video(codecContext, videoOutbut, videoOutbut.length, frame);
/* if zero size, it means the image was buffered */
if (outSize > 0) {
AVCODEC.av_init_packet(packet);
AVFrame tmpFrame = new AVFrame(codecContext.coded_frame);
packet.pts = AVUTIL.av_rescale_q(tmpFrame.pts, new AVUTIL.AVRational.ByValue(codecContext.time_base), new AVUTIL.AVRational.ByValue(st.time_base));
if (tmpFrame.key_frame == 1)
packet.flags |= AVCODEC.PKT_FLAG_KEY;
packet.stream_index = st.index;
videoOutbutMemory.write(0, videoOutbut, 0, outSize);
packet.data = videoOutbutMemory;
packet.size = outSize;
/* write the compressed frame in the media file */
if (AVFORMAT.av_interleaved_write_frame(formatContext, packet) != 0)
throw new IOException("Error while writing video frame");
st.pts.val = packet.pts; // necessary for calculation of video length
}
}
}
protected void fillImage(AVFrame pict, ImageProcessor ip) {
if (bufferFramePixelFormat == AVUTIL.PIX_FMT_RGB24) {
if (!(ip instanceof ColorProcessor))
ip = ip.convertToRGB();
int[] pixels = (int[])ip.getPixels();
int i = 0, total = ip.getWidth() * ip.getHeight();
for (int j = 0; j < total; j++) {
int v = pixels[j];
pict.data[0].setByte(i++, (byte)((v >> 16) & 0xff));
pict.data[0].setByte(i++, (byte)((v >> 8) & 0xff));
pict.data[0].setByte(i++, (byte)(v & 0xff));
}
}
else if (bufferFramePixelFormat == AVUTIL.PIX_FMT_GRAY16BE) {
if (!(ip instanceof ShortProcessor))
ip = ip.convertToShort(false);
short[] pixels = (short[])ip.getPixels();
int i = 0, total = ip.getWidth() * ip.getHeight();
for (int j = 0; j < total; j++) {
int v = pixels[j] & 0xffff;
pict.data[0].setByte(i++, (byte)((v >> 8) & 0xff));
pict.data[0].setByte(i++, (byte)(v & 0xff));
}
}
else if (bufferFramePixelFormat == AVUTIL.PIX_FMT_GRAY8 ||
bufferFramePixelFormat == AVUTIL.PIX_FMT_PAL8) {
if (!(ip instanceof ByteProcessor))
ip = ip.convertToByte(false);
byte[] pixels = (byte[])ip.getPixels();
int i = 0, total = ip.getWidth() * ip.getHeight();
for (int j = 0; j < total; j++) {
int v = pixels[j] & 0xff;
pict.data[0].setByte(i++, (byte)(v & 0xff));
}
}
else
throw new RuntimeException("Unhandled pixel format: " + bufferFramePixelFormat);
}
protected void openVideo(AVFormatContext formatContext, AVStream st) throws IOException {
AVCodec codec;
/* find the video encoder */
codec = AVCODEC.avcodec_find_encoder(codecContext.codec_id);
if (codec == null)
throw new IOException("video codec not found for codec id: " + codecContext.codec_id);
/* open the codec */
if (AVCODEC.avcodec_open(codecContext, codec) < 0)
throw new IOException("Could not open video codec");
}
protected static void closeVideo(AVFormatContext formatContext, AVStream st) {
AVCodecContext tmpCodec = new AVCodecContext(st.codec);
AVCODEC.avcodec_close(tmpCodec);
}
protected AVStream addVideoStream(AVFormatContext formatContext, int codecId, int width, int height, int frameRate, int bitRate, int pixelFormat) {
AVStream st;
st = AVFORMAT.av_new_stream(formatContext, 0);
if (st == null) {
IJ.error("Could not alloc video stream.");
return null;
}
codecContext = new AVCodecContext(st.codec);
codecContext.codec_id = codecId;
codecContext.codec_type = AVCODEC.CODEC_TYPE_VIDEO;
/* put sample parameters */
codecContext.bit_rate = bitRate;
/* resolution must be a multiple of two */
codecContext.width = width; //352;
codecContext.height = height; //288;
/* time base: this is the fundamental unit of time (in seconds) in terms
of which frame timestamps are represented. for fixed-fps content,
timebase should be 1/framerate and timestamp increments should be
identically 1. */
codecContext.time_base.den = frameRate;
codecContext.time_base.num = 1;
codecContext.gop_size = 12;
codecContext.pix_fmt = pixelFormat;
if (codecContext.codec_id == AVCODEC.CODEC_ID_MPEG2VIDEO) {
/* just for testing, we also add B frames */
codecContext.max_b_frames = 2;
}
if (codecContext.codec_id == AVCODEC.CODEC_ID_MPEG1VIDEO) {
/* Needed to avoid using macroblocks in which some coeffs overflow.
This does not happen with normal video, it just happens here as
the motion of the chroma plane does not match the luma plane. */
codecContext.mb_decision = 2;
}
// some formats want stream headers to be separate
if ((new AVFORMAT.AVOutputFormat(formatContext.oformat).flags & AVFORMAT.AVFMT_GLOBALHEADER) != 0)
codecContext.flags |= AVCODEC.CODEC_FLAG_GLOBAL_HEADER;
return st;
}
}
| true | true | public ImagePlus readMovie(String path, boolean useVirtualStack, final int first, final int last) throws IOException {
/* Need to do this because we already extend ImagePlus */
if (!loadFFMPEG())
throw new IOException("Could not load the FFMPEG library!");
if (AVCODEC.avcodec_version() != AVCODEC.LIBAVCODEC_VERSION_INT)
throw new IOException("ffmpeg versions mismatch: native " + AVCODEC.avcodec_version()
+ " != Java-bindings " + AVCODEC.LIBAVCODEC_VERSION_INT);
step("Opening " + path, 0);
AVFORMAT.av_register_all();
// Open video file
final PointerByReference formatContextPointer = new PointerByReference();
if (AVFORMAT.av_open_input_file(formatContextPointer, path, null, 0, null) != 0)
throw new IOException("Could not open " + path);
formatContext = new AVFormatContext(formatContextPointer.getValue());
// Retrieve stream information
if (AVFORMAT.av_find_stream_info(formatContext) < 0)
throw new IOException("No stream in " + path);
// Find the first video stream
int videoStream = -1;
for (int i = 0; i < formatContext.nb_streams; i++) {
final AVStream stream = new AVStream(formatContext.streams[i]);
codecContext = new AVCodecContext(stream.codec);
if (codecContext.codec_type == AVCODEC.CODEC_TYPE_VIDEO) {
videoStream = i;
break;
}
}
if (codecContext == null)
throw new IOException("No video stream in " + path);
if (codecContext.codec_id == 0)
throw new IOException("Codec not available");
// Find and open the decoder for the video stream
codec = AVCODEC.avcodec_find_decoder(codecContext.codec_id);
if (codec == null || AVCODEC.avcodec_open(codecContext, codec) < 0)
throw new IOException("Codec not available");
allocateFrames(false);
final AVStream stream = new AVStream(formatContext.streams[videoStream]);
if (useVirtualStack) {
// TODO: handle stream.duration == 0 by counting the frames
if (stream.duration == 0)
throw new IOException("Cannot determine stack size (duration is 0)");
final int videoStreamIndex = videoStream;
ImageStack stack = new VirtualStack(codecContext.width, codecContext.height, null, null) {
int previousSlice = -1;
long frameDuration = guessFrameDuration();
public void finalize() {
free();
}
public int getSize() {
int size = (int)(stream.duration / frameDuration);
if (last >= 0)
size = Math.min(last, size);
if (first > 0)
size -= first;
return size;
}
public String getSliceLabel(int slice) {
return ""; // maybe calculate the time?
}
public long guessFrameDuration() {
if (AVFORMAT.av_read_frame(formatContext, packet) < 0)
return 1;
long firstPTS = packet.pts;
int frameCount = 5;
for (int i = 0; i < frameCount; previousSlice = i++)
if (AVFORMAT.av_read_frame(formatContext, packet) < 0)
return 1;
return (packet.pts - firstPTS) / frameCount;
}
// TODO: cache two
public ImageProcessor getProcessor(int slice) {
long time = (first + slice - 1) * frameDuration;
if (time > 0)
time -= frameDuration / 2;
if (stream.start_time != 0x8000000000000000l /* TODO: AVUTIL.AV_NOPTS_VALUE */)
time += stream.start_time;
if (previousSlice != slice - 1)
AVFORMAT.av_seek_frame(formatContext, videoStreamIndex, time,
AVFORMAT.AVSEEK_FLAG_BACKWARD);
for (;;) {
if (AVFORMAT.av_read_frame(formatContext, packet) < 0) {
packet.data = null;
packet.size = 0;
break;
}
if (packet.stream_index != videoStreamIndex)
continue;
if (previousSlice == slice - 1 || packet.pts >= time)
break;
AVCODEC.avcodec_decode_video2(codecContext, frame, gotPicture, packet);
}
previousSlice = slice;
return readOneFrame(packet);
}
};
done("Opened " + path + " as virtual stack");
return new ImagePlus(path, stack);
}
double factor = stream.duration > 0 ? 1.0 / stream.duration : 0;
if (last >= 0)
factor = 1.0 / last;
ImageStack stack = new ImageStack(codecContext.width, codecContext.height);
int frameCounter = 0;
start("Writing " + path);
while (AVFORMAT.av_read_frame(formatContext, packet) >= 0 &&
(last < 0 || frameCounter < last)) {
// Is this a packet from the video stream?
if (packet.stream_index != videoStream)
continue;
step(null, frameCounter * factor);
ImageProcessor ip = readOneFrame(packet);
if (ip != null && frameCounter++ >= first)
stack.addSlice(null, ip);
}
// Read the last frame
packet.data = null;
packet.size = 0;
ImageProcessor ip = readOneFrame(packet);
if (ip != null)
stack.addSlice(null, ip);
free();
done("Opened " + path);
return new ImagePlus(path, stack);
}
| public ImagePlus readMovie(String path, boolean useVirtualStack, final int first, final int last) throws IOException {
/* Need to do this because we already extend ImagePlus */
if (!loadFFMPEG())
throw new IOException("Could not load the FFMPEG library!");
if (AVCODEC.avcodec_version() != AVCODEC.LIBAVCODEC_VERSION_INT)
throw new IOException("ffmpeg versions mismatch: native " + AVCODEC.avcodec_version()
+ " != Java-bindings " + AVCODEC.LIBAVCODEC_VERSION_INT);
step("Opening " + path, 0);
AVFORMAT.av_register_all();
// Open video file
final PointerByReference formatContextPointer = new PointerByReference();
if (AVFORMAT.av_open_input_file(formatContextPointer, path, null, 0, null) != 0)
throw new IOException("Could not open " + path);
formatContext = new AVFormatContext(formatContextPointer.getValue());
// Retrieve stream information
if (AVFORMAT.av_find_stream_info(formatContext) < 0)
throw new IOException("No stream in " + path);
// Find the first video stream
int videoStream = -1;
for (int i = 0; i < formatContext.nb_streams; i++) {
final AVStream stream = new AVStream(formatContext.streams[i]);
codecContext = new AVCodecContext(stream.codec);
if (codecContext.codec_type == AVCODEC.CODEC_TYPE_VIDEO) {
videoStream = i;
break;
}
}
if (codecContext == null)
throw new IOException("No video stream in " + path);
if (codecContext.codec_id == 0)
throw new IOException("Codec not available");
// Find and open the decoder for the video stream
codec = AVCODEC.avcodec_find_decoder(codecContext.codec_id);
if (codec == null || AVCODEC.avcodec_open(codecContext, codec) < 0)
throw new IOException("Codec not available");
allocateFrames(false);
final AVStream stream = new AVStream(formatContext.streams[videoStream]);
if (useVirtualStack) {
// TODO: handle stream.duration == 0 by counting the frames
if (stream.duration == 0)
throw new IOException("Cannot determine stack size (duration is 0)");
final int videoStreamIndex = videoStream;
ImageStack stack = new VirtualStack(codecContext.width, codecContext.height, null, null) {
int previousSlice = -1;
long frameDuration = guessFrameDuration();
public void finalize() {
free();
}
public int getSize() {
int size = (int)(stream.duration / frameDuration);
if (last >= 0)
size = Math.min(last, size);
if (first > 0)
size -= first;
return size;
}
public String getSliceLabel(int slice) {
return ""; // maybe calculate the time?
}
public long guessFrameDuration() {
if (AVFORMAT.av_read_frame(formatContext, packet) < 0)
return 1;
long firstPTS = packet.pts;
int frameCount = 5;
for (int i = 0; i < frameCount; previousSlice = i++)
if (AVFORMAT.av_read_frame(formatContext, packet) < 0)
return 1;
return (packet.pts - firstPTS) / frameCount;
}
// TODO: cache two
public ImageProcessor getProcessor(int slice) {
long time = (first + slice - 1) * frameDuration;
if (time > 0)
time -= frameDuration / 2;
if (stream.start_time != 0x8000000000000000l /* TODO: AVUTIL.AV_NOPTS_VALUE */)
time += stream.start_time;
if (previousSlice != slice - 1)
AVFORMAT.av_seek_frame(formatContext, videoStreamIndex, time,
AVFORMAT.AVSEEK_FLAG_BACKWARD);
for (;;) {
if (AVFORMAT.av_read_frame(formatContext, packet) < 0) {
packet.data = null;
packet.size = 0;
break;
}
if (packet.stream_index != videoStreamIndex)
continue;
if (previousSlice == slice - 1 || packet.pts >= time)
break;
AVCODEC.avcodec_decode_video2(codecContext, frame, gotPicture, packet);
}
previousSlice = slice;
return readOneFrame(packet);
}
};
done("Opened " + path + " as virtual stack");
return new ImagePlus(path, stack);
}
double factor = stream.duration > 0 ? 1.0 / stream.duration : 0;
if (last >= 0)
factor = 1.0 / last;
ImageStack stack = new ImageStack(codecContext.width, codecContext.height);
int frameCounter = 0;
start("Reading " + path);
while (AVFORMAT.av_read_frame(formatContext, packet) >= 0 &&
(last < 0 || frameCounter < last)) {
// Is this a packet from the video stream?
if (packet.stream_index != videoStream)
continue;
step(null, frameCounter * factor);
ImageProcessor ip = readOneFrame(packet);
if (ip != null && frameCounter++ >= first)
stack.addSlice(null, ip);
}
// Read the last frame
packet.data = null;
packet.size = 0;
ImageProcessor ip = readOneFrame(packet);
if (ip != null)
stack.addSlice(null, ip);
free();
done("Opened " + path);
return new ImagePlus(path, stack);
}
|
diff --git a/src/main/java/org/gestern/gringotts/Commands.java b/src/main/java/org/gestern/gringotts/Commands.java
index 89c9023..47ce08e 100644
--- a/src/main/java/org/gestern/gringotts/Commands.java
+++ b/src/main/java/org/gestern/gringotts/Commands.java
@@ -1,234 +1,234 @@
package org.gestern.gringotts;
import java.util.logging.Logger;
import org.bukkit.Bukkit;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import org.gestern.gringotts.accountholder.PlayerAccountHolder;
import static org.gestern.gringotts.Util.*;
/**
* Handlers for player and console commands.
*
* @author jast
*
*/
public class Commands {
Logger log = Bukkit.getServer().getLogger();
private Gringotts plugin;
private Configuration conf = Configuration.config;
private final AccountHolderFactory ahf = new AccountHolderFactory();
public Commands(Gringotts plugin) {
this.plugin = plugin;
}
/**
* Player commands.
*/
public class Money implements CommandExecutor{
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Accounting accounting = plugin.accounting;
Player player;
if (sender instanceof Player) {
player = (Player)sender;
} else {
sender.sendMessage("This command can only be run by a player.");
return false;
// TODO actually, refactor the whole thing already!
}
AccountHolder accountOwner = new PlayerAccountHolder(player);
Account account = accounting.getAccount(accountOwner);
if (args.length == 0) {
// same as balance
balanceMessage(account, accountOwner);
return true;
}
String command = "";
if (args.length >= 1) {
command = args[0];
}
double value = 0;
if (args.length >= 2) {
try {
value = Double.parseDouble(args[1]);
// cutoff base value when fractions are disabled, so that nothing is taxed that isn't being paid
- if (conf.currencyFractional)
+ if (!conf.currencyFractional)
value = Math.floor(value);
}
catch (NumberFormatException e) { return false; }
}
if(args.length == 3) {
// /money pay <amount> <player>
if (command.equals("pay")) {
if (!player.hasPermission("gringotts.transfer")) {
player.sendMessage("You do not have permission to transfer money.");
}
String recipientName = args[2];
AccountHolder recipient = ahf.get(recipientName);
if (recipient == null) {
invalidAccount(sender, recipientName);
return true;
}
Account recipientAccount = accounting.getAccount(recipient);
double tax = conf.transactionTaxFlat + value * conf.transactionTaxRate;
// round tax value when fractions are disabled
- if (conf.currencyFractional)
+ if (!conf.currencyFractional)
tax = Math.round(tax);
double balance = account.balance();
double valueAdded = value + tax;
if (balance < valueAdded) {
accountOwner.sendMessage(
"Your account has insufficient balance. Current balance: " + balance + " " + currencyName(balance)
- + ". Required: " + (valueAdded) + " " + currencyName(valueAdded));
+ + ". Required: " + valueAdded + " " + currencyName(valueAdded));
return true;
}
if (recipientAccount.capacity() < value) {
accountOwner.sendMessage(recipientName + " has insufficient storage space for this amount");
return true;
} else if (account.remove(value)) {
if (recipientAccount.add(value)) {
account.remove(tax);
String currencyName = currencyName(balance);
String taxMessage = "Transaction tax deducted from your account: " + tax + " " + currencyName(tax);
accountOwner.sendMessage("Sent " + value + " " + currencyName + " to " + recipientName +". " + (tax>0? taxMessage : ""));
recipient.sendMessage("Received " + value + " " + currencyName + " from " + accountOwner.getName() +".");
return true;
}
}
}
}
return false;
}
}
/**
* Admin commands for managing ingame aspects.
*/
public class Moneyadmin implements CommandExecutor {
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Accounting accounting = plugin.accounting;
if (cmd.getName().equalsIgnoreCase("money") || cmd.getName().equalsIgnoreCase("balance")) {
} else if (cmd.getName().equalsIgnoreCase("moneyadmin")) {
String command;
if (args.length >= 2) {
command = args[0];
} else return false;
// admin command: balance of player / faction
if (args.length == 2 && command.equalsIgnoreCase("b")) {
String targetAccountHolderStr = args[1];
AccountHolder targetAccountHolder = ahf.get(targetAccountHolderStr);
if (targetAccountHolder == null) {
invalidAccount(sender, targetAccountHolderStr);
return true;
}
Account targetAccount = accounting.getAccount(targetAccountHolder);
sender.sendMessage("Balance of account " + targetAccountHolder.getName() + ": " + targetAccount.balance());
return true;
}
// moneyadmin add/remove
if (args.length == 3) {
String amountStr = args[1];
double value;
try {
value = Double.parseDouble(amountStr);
if (!conf.currencyFractional)
value = Math.floor(value);
}
catch(NumberFormatException x) { return false; }
String targetAccountHolderStr = args[2];
AccountHolder targetAccountHolder = ahf.get(targetAccountHolderStr);
if (targetAccountHolder == null) {
invalidAccount(sender, targetAccountHolderStr);
return true;
}
Account targetAccount = accounting.getAccount(targetAccountHolder);
if (command.equalsIgnoreCase("add")) {
if (targetAccount.add(value)) {
sender.sendMessage("Added " + value + " to account " + targetAccountHolder.getName());
targetAccountHolder.sendMessage("Added to your account: " + value);
} else {
sender.sendMessage("Could not add " + value + " to account " + targetAccountHolder.getName());
}
return true;
} else if (command.equalsIgnoreCase("rm")) {
if (targetAccount.remove(value)) {
sender.sendMessage("Removed " + value + " from account " + targetAccountHolder.getName());
targetAccountHolder.sendMessage("Removed from your account: " + value);
} else {
sender.sendMessage("Could not remove " + value + " from account " + targetAccountHolder.getName());
}
return true;
}
}
}
return false;
}
}
/**
* Administrative commands not related to ingame money.
*/
public class GringottsCmd implements CommandExecutor {
@Override
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
if (args.length >=1 && "reload".equalsIgnoreCase(args[0])) {
plugin.reloadConfig();
conf.readConfig(plugin.getConfig());
sender.sendMessage("[Gringotts] Reloaded configuration!");
return true;
}
return false;
}
}
private static void balanceMessage(Account account, AccountHolder owner) {
double balance = account.balance();
owner.sendMessage("Your current balance: " + balance + " " + currencyName(balance) + ".");
}
private static void invalidAccount(CommandSender sender, String accountName) {
sender.sendMessage("Invalid account: " + accountName);
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Accounting accounting = plugin.accounting;
Player player;
if (sender instanceof Player) {
player = (Player)sender;
} else {
sender.sendMessage("This command can only be run by a player.");
return false;
// TODO actually, refactor the whole thing already!
}
AccountHolder accountOwner = new PlayerAccountHolder(player);
Account account = accounting.getAccount(accountOwner);
if (args.length == 0) {
// same as balance
balanceMessage(account, accountOwner);
return true;
}
String command = "";
if (args.length >= 1) {
command = args[0];
}
double value = 0;
if (args.length >= 2) {
try {
value = Double.parseDouble(args[1]);
// cutoff base value when fractions are disabled, so that nothing is taxed that isn't being paid
if (conf.currencyFractional)
value = Math.floor(value);
}
catch (NumberFormatException e) { return false; }
}
if(args.length == 3) {
// /money pay <amount> <player>
if (command.equals("pay")) {
if (!player.hasPermission("gringotts.transfer")) {
player.sendMessage("You do not have permission to transfer money.");
}
String recipientName = args[2];
AccountHolder recipient = ahf.get(recipientName);
if (recipient == null) {
invalidAccount(sender, recipientName);
return true;
}
Account recipientAccount = accounting.getAccount(recipient);
double tax = conf.transactionTaxFlat + value * conf.transactionTaxRate;
// round tax value when fractions are disabled
if (conf.currencyFractional)
tax = Math.round(tax);
double balance = account.balance();
double valueAdded = value + tax;
if (balance < valueAdded) {
accountOwner.sendMessage(
"Your account has insufficient balance. Current balance: " + balance + " " + currencyName(balance)
+ ". Required: " + (valueAdded) + " " + currencyName(valueAdded));
return true;
}
if (recipientAccount.capacity() < value) {
accountOwner.sendMessage(recipientName + " has insufficient storage space for this amount");
return true;
} else if (account.remove(value)) {
if (recipientAccount.add(value)) {
account.remove(tax);
String currencyName = currencyName(balance);
String taxMessage = "Transaction tax deducted from your account: " + tax + " " + currencyName(tax);
accountOwner.sendMessage("Sent " + value + " " + currencyName + " to " + recipientName +". " + (tax>0? taxMessage : ""));
recipient.sendMessage("Received " + value + " " + currencyName + " from " + accountOwner.getName() +".");
return true;
}
}
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
Accounting accounting = plugin.accounting;
Player player;
if (sender instanceof Player) {
player = (Player)sender;
} else {
sender.sendMessage("This command can only be run by a player.");
return false;
// TODO actually, refactor the whole thing already!
}
AccountHolder accountOwner = new PlayerAccountHolder(player);
Account account = accounting.getAccount(accountOwner);
if (args.length == 0) {
// same as balance
balanceMessage(account, accountOwner);
return true;
}
String command = "";
if (args.length >= 1) {
command = args[0];
}
double value = 0;
if (args.length >= 2) {
try {
value = Double.parseDouble(args[1]);
// cutoff base value when fractions are disabled, so that nothing is taxed that isn't being paid
if (!conf.currencyFractional)
value = Math.floor(value);
}
catch (NumberFormatException e) { return false; }
}
if(args.length == 3) {
// /money pay <amount> <player>
if (command.equals("pay")) {
if (!player.hasPermission("gringotts.transfer")) {
player.sendMessage("You do not have permission to transfer money.");
}
String recipientName = args[2];
AccountHolder recipient = ahf.get(recipientName);
if (recipient == null) {
invalidAccount(sender, recipientName);
return true;
}
Account recipientAccount = accounting.getAccount(recipient);
double tax = conf.transactionTaxFlat + value * conf.transactionTaxRate;
// round tax value when fractions are disabled
if (!conf.currencyFractional)
tax = Math.round(tax);
double balance = account.balance();
double valueAdded = value + tax;
if (balance < valueAdded) {
accountOwner.sendMessage(
"Your account has insufficient balance. Current balance: " + balance + " " + currencyName(balance)
+ ". Required: " + valueAdded + " " + currencyName(valueAdded));
return true;
}
if (recipientAccount.capacity() < value) {
accountOwner.sendMessage(recipientName + " has insufficient storage space for this amount");
return true;
} else if (account.remove(value)) {
if (recipientAccount.add(value)) {
account.remove(tax);
String currencyName = currencyName(balance);
String taxMessage = "Transaction tax deducted from your account: " + tax + " " + currencyName(tax);
accountOwner.sendMessage("Sent " + value + " " + currencyName + " to " + recipientName +". " + (tax>0? taxMessage : ""));
recipient.sendMessage("Received " + value + " " + currencyName + " from " + accountOwner.getName() +".");
return true;
}
}
}
}
return false;
}
|
diff --git a/src/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java b/src/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java
index b0667dd7..ee9aec1d 100644
--- a/src/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java
+++ b/src/org/jcp/xml/dsig/internal/dom/DOMURIDereferencer.java
@@ -1,103 +1,101 @@
/*
* Copyright 2005 The Apache Software Foundation.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
/*
* Copyright 2005 Sun Microsystems, Inc. All rights reserved.
*/
/*
* $Id$
*/
package org.jcp.xml.dsig.internal.dom;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.Node;
import org.apache.xml.security.Init;
import org.apache.xml.security.utils.IdResolver;
import org.apache.xml.security.utils.resolver.ResourceResolver;
import org.apache.xml.security.signature.XMLSignatureInput;
import javax.xml.crypto.*;
import javax.xml.crypto.dom.*;
import javax.xml.crypto.dsig.*;
/**
* DOM-based implementation of URIDereferencer.
*
* @author Sean Mullan
*/
public class DOMURIDereferencer implements URIDereferencer {
static final URIDereferencer INSTANCE = new DOMURIDereferencer();
private DOMURIDereferencer() {
// need to call org.apache.xml.security.Init.init()
// before calling any apache security code
Init.init();
}
public Data dereference(URIReference uriRef, XMLCryptoContext context)
throws URIReferenceException {
if (uriRef == null) {
throw new NullPointerException("uriRef cannot be null");
}
if (context == null) {
throw new NullPointerException("context cannot be null");
}
DOMURIReference domRef = (DOMURIReference) uriRef;
Attr uriAttr = (Attr) domRef.getHere();
String uri = uriRef.getURI();
DOMCryptoContext dcc = (DOMCryptoContext) context;
// Check if same-document URI and register ID
if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') {
String id = uri.substring(1);
if (id.startsWith("xpointer(id(")) {
int i1 = id.indexOf('\'');
int i2 = id.indexOf('\'', i1+1);
id = id.substring(i1+1, i2);
}
// this is a bit of a hack to check for registered
// IDRefs and manually register them with Apache's IdResolver
// map which includes builtin schema knowledge of DSig/Enc IDs
- if (context instanceof XMLSignContext) {
- Node referencedElem = dcc.getElementById(id);
- if (referencedElem != null) {
- IdResolver.registerElementById((Element) referencedElem, id);
- }
+ Node referencedElem = dcc.getElementById(id);
+ if (referencedElem != null) {
+ IdResolver.registerElementById((Element) referencedElem, id);
}
}
try {
String baseURI = context.getBaseURI();
ResourceResolver apacheResolver =
ResourceResolver.getInstance(uriAttr, baseURI);
XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI);
if (in.isOctetStream()) {
return new ApacheOctetStreamData(in);
} else {
return new ApacheNodeSetData(in);
}
} catch (Exception e) {
throw new URIReferenceException(e);
}
}
}
| true | true | public Data dereference(URIReference uriRef, XMLCryptoContext context)
throws URIReferenceException {
if (uriRef == null) {
throw new NullPointerException("uriRef cannot be null");
}
if (context == null) {
throw new NullPointerException("context cannot be null");
}
DOMURIReference domRef = (DOMURIReference) uriRef;
Attr uriAttr = (Attr) domRef.getHere();
String uri = uriRef.getURI();
DOMCryptoContext dcc = (DOMCryptoContext) context;
// Check if same-document URI and register ID
if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') {
String id = uri.substring(1);
if (id.startsWith("xpointer(id(")) {
int i1 = id.indexOf('\'');
int i2 = id.indexOf('\'', i1+1);
id = id.substring(i1+1, i2);
}
// this is a bit of a hack to check for registered
// IDRefs and manually register them with Apache's IdResolver
// map which includes builtin schema knowledge of DSig/Enc IDs
if (context instanceof XMLSignContext) {
Node referencedElem = dcc.getElementById(id);
if (referencedElem != null) {
IdResolver.registerElementById((Element) referencedElem, id);
}
}
}
try {
String baseURI = context.getBaseURI();
ResourceResolver apacheResolver =
ResourceResolver.getInstance(uriAttr, baseURI);
XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI);
if (in.isOctetStream()) {
return new ApacheOctetStreamData(in);
} else {
return new ApacheNodeSetData(in);
}
} catch (Exception e) {
throw new URIReferenceException(e);
}
}
| public Data dereference(URIReference uriRef, XMLCryptoContext context)
throws URIReferenceException {
if (uriRef == null) {
throw new NullPointerException("uriRef cannot be null");
}
if (context == null) {
throw new NullPointerException("context cannot be null");
}
DOMURIReference domRef = (DOMURIReference) uriRef;
Attr uriAttr = (Attr) domRef.getHere();
String uri = uriRef.getURI();
DOMCryptoContext dcc = (DOMCryptoContext) context;
// Check if same-document URI and register ID
if (uri != null && uri.length() != 0 && uri.charAt(0) == '#') {
String id = uri.substring(1);
if (id.startsWith("xpointer(id(")) {
int i1 = id.indexOf('\'');
int i2 = id.indexOf('\'', i1+1);
id = id.substring(i1+1, i2);
}
// this is a bit of a hack to check for registered
// IDRefs and manually register them with Apache's IdResolver
// map which includes builtin schema knowledge of DSig/Enc IDs
Node referencedElem = dcc.getElementById(id);
if (referencedElem != null) {
IdResolver.registerElementById((Element) referencedElem, id);
}
}
try {
String baseURI = context.getBaseURI();
ResourceResolver apacheResolver =
ResourceResolver.getInstance(uriAttr, baseURI);
XMLSignatureInput in = apacheResolver.resolve(uriAttr, baseURI);
if (in.isOctetStream()) {
return new ApacheOctetStreamData(in);
} else {
return new ApacheNodeSetData(in);
}
} catch (Exception e) {
throw new URIReferenceException(e);
}
}
|
diff --git a/chronicle/src/main/java/com/higherfrequencytrading/chronicle/tcp/InProcessChronicleSource.java b/chronicle/src/main/java/com/higherfrequencytrading/chronicle/tcp/InProcessChronicleSource.java
index 0b01979..af86ddb 100644
--- a/chronicle/src/main/java/com/higherfrequencytrading/chronicle/tcp/InProcessChronicleSource.java
+++ b/chronicle/src/main/java/com/higherfrequencytrading/chronicle/tcp/InProcessChronicleSource.java
@@ -1,277 +1,277 @@
/*
* Copyright 2013 Peter Lawrey
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.higherfrequencytrading.chronicle.tcp;
import com.higherfrequencytrading.chronicle.Chronicle;
import com.higherfrequencytrading.chronicle.EnumeratedMarshaller;
import com.higherfrequencytrading.chronicle.Excerpt;
import com.higherfrequencytrading.chronicle.impl.WrappedExcerpt;
import java.io.EOFException;
import java.io.IOException;
import java.net.InetSocketAddress;
import java.net.SocketException;
import java.nio.ByteBuffer;
import java.nio.ByteOrder;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.logging.Level;
import java.util.logging.Logger;
/**
* A Chronicle as a service to be replicated to any number of clients. Clients can restart from where ever they are up to.
* <p/>
* Can be used an in process component which wraps the underlying Chronicle
* and offers lower overhead than using ChronicleSource
*
* @author peter.lawrey
*/
public class InProcessChronicleSource implements Chronicle {
static final int IN_SYNC_LEN = -128;
static final long HEARTBEAT_INTERVAL_MS = 2500;
private static final int MAX_MESSAGE = 128;
private final Chronicle chronicle;
private final ServerSocketChannel server;
private final String name;
private final ExecutorService service;
private final Logger logger;
private volatile boolean closed = false;
private Boolean tcpNoDelay;
public InProcessChronicleSource(Chronicle chronicle, int port) throws IOException {
this.chronicle = chronicle;
server = ServerSocketChannel.open();
server.socket().setReuseAddress(true);
server.socket().bind(new InetSocketAddress(port));
name = chronicle.name() + "@" + port;
logger = Logger.getLogger(getClass().getName() + "." + name);
service = Executors.newCachedThreadPool(new NamedThreadFactory(name));
service.execute(new Acceptor());
}
public void setTcpNoDelay(Boolean tcpNoDelay) {
this.tcpNoDelay = tcpNoDelay;
}
public Boolean getTcpNoDelay() {
return tcpNoDelay;
}
private class Acceptor implements Runnable {
@Override
public void run() {
Thread.currentThread().setName(name + "-acceptor");
try {
while (!closed) {
SocketChannel socket = server.accept();
service.execute(new Handler(socket));
}
} catch (IOException e) {
if (!closed)
logger.log(Level.SEVERE, "Acceptor dying", e);
}
}
}
class Handler implements Runnable {
private final SocketChannel socket;
public Handler(SocketChannel socket) throws SocketException {
this.socket = socket;
socket.socket().setSendBufferSize(256 * 1024);
Boolean tcpNoDelay = getTcpNoDelay();
if (tcpNoDelay != null)
socket.socket().setTcpNoDelay(tcpNoDelay);
}
@Override
public void run() {
try {
long index = readIndex(socket);
Excerpt excerpt = chronicle.createExcerpt();
ByteBuffer bb = TcpUtil.createBuffer(1, chronicle); // minimum size
long sendInSync = 0;
boolean first = true;
OUTER:
while (!closed) {
while (!excerpt.index(index)) {
// System.out.println("Waiting for " + index);
long now = System.currentTimeMillis();
- if (sendInSync <= now) {
+ if (sendInSync <= now && !first) {
bb.clear();
bb.putInt(IN_SYNC_LEN);
bb.flip();
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
sendInSync = now + HEARTBEAT_INTERVAL_MS;
}
pause();
if (closed) break OUTER;
}
// System.out.println("Writing " + index);
final int size = excerpt.capacity();
int remaining;
bb.clear();
if (first) {
// System.out.println("wi " + index);
bb.putLong(index);
first = false;
remaining = size + TcpUtil.HEADER_SIZE;
} else {
remaining = size + 4;
}
bb.putInt(size);
// for large objects send one at a time.
if (size > bb.capacity() / 2) {
while (remaining > 0) {
int size2 = Math.min(remaining, bb.capacity());
bb.limit(size2);
excerpt.read(bb);
bb.flip();
// System.out.println("w " + ChronicleTools.asString(bb));
remaining -= bb.remaining();
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
}
} else {
bb.limit(remaining);
excerpt.read(bb);
int count = 1;
while (excerpt.index(index + 1) && count++ < MAX_MESSAGE) {
if (excerpt.remaining() + 4 >= bb.capacity() - bb.position())
break;
// if there is free space, copy another one.
int size2 = excerpt.capacity();
// System.out.println("W+ "+size);
bb.limit(bb.position() + size2 + 4);
bb.putInt(size2);
excerpt.read(bb);
index++;
}
bb.flip();
// System.out.println("W " + size + " wb " + bb);
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
}
if (bb.remaining() > 0) throw new EOFException("Failed to send index=" + index);
index++;
sendInSync = 0;
// if (index % 20000 == 0)
// System.out.println(System.currentTimeMillis() + ": wrote " + index);
}
} catch (IOException e) {
if (!closed) {
if (e.getMessage().contains("reset by peer") || e.getMessage().contains("Broken pipe")
|| e.getMessage().contains("was aborted by"))
logger.log(Level.INFO, "Connect " + socket + " closed from the other end " + e);
else
logger.log(Level.INFO, "Connect " + socket + " died", e);
}
}
}
private long readIndex(SocketChannel socket) throws IOException {
ByteBuffer bb = ByteBuffer.allocate(8);
while (bb.remaining() > 0 && socket.read(bb) > 0) ;
if (bb.remaining() > 0) throw new EOFException();
return bb.getLong(0);
}
}
private final Object notifier = new Object();
protected void pause() {
try {
synchronized (notifier) {
notifier.wait(HEARTBEAT_INTERVAL_MS / 2);
}
} catch (InterruptedException ie) {
logger.warning("Interrupt ignored");
}
}
void wakeSessionHandlers() {
synchronized (notifier) {
notifier.notifyAll();
}
}
@Override
public String name() {
return chronicle.name();
}
@Override
public Excerpt createExcerpt() {
return new SourceExcerpt();
}
@Override
public long size() {
return chronicle.size();
}
@Override
public long sizeInBytes() {
return chronicle.sizeInBytes();
}
@Override
public ByteOrder byteOrder() {
return chronicle.byteOrder();
}
@Override
public void close() {
closed = true;
chronicle.close();
try {
server.close();
} catch (IOException e) {
logger.warning("Error closing server port " + e);
}
}
@Override
public <E> void setEnumeratedMarshaller(EnumeratedMarshaller<E> marshaller) {
chronicle.setEnumeratedMarshaller(marshaller);
}
private class SourceExcerpt extends WrappedExcerpt {
@SuppressWarnings("unchecked")
public SourceExcerpt() {
super(InProcessChronicleSource.this.chronicle.createExcerpt());
}
@Override
public void finish() {
super.finish();
wakeSessionHandlers();
// System.out.println("Wrote " + index());
}
}
@Override
public <E> EnumeratedMarshaller<E> getMarshaller(Class<E> eClass) {
return chronicle.getMarshaller(eClass);
}
}
| true | true | public void run() {
try {
long index = readIndex(socket);
Excerpt excerpt = chronicle.createExcerpt();
ByteBuffer bb = TcpUtil.createBuffer(1, chronicle); // minimum size
long sendInSync = 0;
boolean first = true;
OUTER:
while (!closed) {
while (!excerpt.index(index)) {
// System.out.println("Waiting for " + index);
long now = System.currentTimeMillis();
if (sendInSync <= now) {
bb.clear();
bb.putInt(IN_SYNC_LEN);
bb.flip();
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
sendInSync = now + HEARTBEAT_INTERVAL_MS;
}
pause();
if (closed) break OUTER;
}
// System.out.println("Writing " + index);
final int size = excerpt.capacity();
int remaining;
bb.clear();
if (first) {
// System.out.println("wi " + index);
bb.putLong(index);
first = false;
remaining = size + TcpUtil.HEADER_SIZE;
} else {
remaining = size + 4;
}
bb.putInt(size);
// for large objects send one at a time.
if (size > bb.capacity() / 2) {
while (remaining > 0) {
int size2 = Math.min(remaining, bb.capacity());
bb.limit(size2);
excerpt.read(bb);
bb.flip();
// System.out.println("w " + ChronicleTools.asString(bb));
remaining -= bb.remaining();
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
}
} else {
bb.limit(remaining);
excerpt.read(bb);
int count = 1;
while (excerpt.index(index + 1) && count++ < MAX_MESSAGE) {
if (excerpt.remaining() + 4 >= bb.capacity() - bb.position())
break;
// if there is free space, copy another one.
int size2 = excerpt.capacity();
// System.out.println("W+ "+size);
bb.limit(bb.position() + size2 + 4);
bb.putInt(size2);
excerpt.read(bb);
index++;
}
bb.flip();
// System.out.println("W " + size + " wb " + bb);
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
}
if (bb.remaining() > 0) throw new EOFException("Failed to send index=" + index);
index++;
sendInSync = 0;
// if (index % 20000 == 0)
// System.out.println(System.currentTimeMillis() + ": wrote " + index);
}
} catch (IOException e) {
if (!closed) {
if (e.getMessage().contains("reset by peer") || e.getMessage().contains("Broken pipe")
|| e.getMessage().contains("was aborted by"))
logger.log(Level.INFO, "Connect " + socket + " closed from the other end " + e);
else
logger.log(Level.INFO, "Connect " + socket + " died", e);
}
}
}
| public void run() {
try {
long index = readIndex(socket);
Excerpt excerpt = chronicle.createExcerpt();
ByteBuffer bb = TcpUtil.createBuffer(1, chronicle); // minimum size
long sendInSync = 0;
boolean first = true;
OUTER:
while (!closed) {
while (!excerpt.index(index)) {
// System.out.println("Waiting for " + index);
long now = System.currentTimeMillis();
if (sendInSync <= now && !first) {
bb.clear();
bb.putInt(IN_SYNC_LEN);
bb.flip();
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
sendInSync = now + HEARTBEAT_INTERVAL_MS;
}
pause();
if (closed) break OUTER;
}
// System.out.println("Writing " + index);
final int size = excerpt.capacity();
int remaining;
bb.clear();
if (first) {
// System.out.println("wi " + index);
bb.putLong(index);
first = false;
remaining = size + TcpUtil.HEADER_SIZE;
} else {
remaining = size + 4;
}
bb.putInt(size);
// for large objects send one at a time.
if (size > bb.capacity() / 2) {
while (remaining > 0) {
int size2 = Math.min(remaining, bb.capacity());
bb.limit(size2);
excerpt.read(bb);
bb.flip();
// System.out.println("w " + ChronicleTools.asString(bb));
remaining -= bb.remaining();
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
}
} else {
bb.limit(remaining);
excerpt.read(bb);
int count = 1;
while (excerpt.index(index + 1) && count++ < MAX_MESSAGE) {
if (excerpt.remaining() + 4 >= bb.capacity() - bb.position())
break;
// if there is free space, copy another one.
int size2 = excerpt.capacity();
// System.out.println("W+ "+size);
bb.limit(bb.position() + size2 + 4);
bb.putInt(size2);
excerpt.read(bb);
index++;
}
bb.flip();
// System.out.println("W " + size + " wb " + bb);
while (bb.remaining() > 0 && socket.write(bb) > 0) ;
}
if (bb.remaining() > 0) throw new EOFException("Failed to send index=" + index);
index++;
sendInSync = 0;
// if (index % 20000 == 0)
// System.out.println(System.currentTimeMillis() + ": wrote " + index);
}
} catch (IOException e) {
if (!closed) {
if (e.getMessage().contains("reset by peer") || e.getMessage().contains("Broken pipe")
|| e.getMessage().contains("was aborted by"))
logger.log(Level.INFO, "Connect " + socket + " closed from the other end " + e);
else
logger.log(Level.INFO, "Connect " + socket + " died", e);
}
}
}
|
diff --git a/src/java/DatabaseConnector.java b/src/java/DatabaseConnector.java
index 98cb3c5..10e70e9 100644
--- a/src/java/DatabaseConnector.java
+++ b/src/java/DatabaseConnector.java
@@ -1,340 +1,340 @@
import java.sql.*;
import javax.sql.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.Properties;
class DatabaseConnector {
private static final String JDBC_DRIVER = "com.mysql.jdbc.Driver";
private static final String DB_URL = "jdbc:mysql://localhost/vcf_analyzer";
static final String USER = "vcf_user";
static final String PASS = "vcf";
private static final ArrayList<String> EntryFixedInfo = new ArrayList<String>(
Arrays.asList("CHROM", "FILTER", "ID", "POS", "REF", "QUAL", "ALT"));
private Connection conn;
private Statement stmt;
private ArrayList<Statement> stmtList;
public DatabaseConnector() throws SQLException, ClassNotFoundException {
try{
this.conn = null;
this.stmt = null;
Class.forName(JDBC_DRIVER);
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
}
catch (Exception e) {
throw new SQLException("Could not connect to database");
}
}
public long getVcfId(String vcfName) throws IllegalArgumentException,
SQLException {
String sql = "";
try {
sql = "SELECT `VcfId` FROM `vcf_analyzer`.`Vcf` WHERE `VcfName` = '"
+ vcfName + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
long id = Long.parseLong(rs.getString("VcfId"));
rs.close();
return id;
}
throw new IllegalArgumentException("VCF: " + vcfName + " not found");
} catch (SQLException se) {
throw new SQLException("Invalid Query " + sql);
}
}
public String getVcfHeader(long vcfId) throws IllegalArgumentException,
SQLException {
String sql = "";
try {
sql = "SELECT `Header` FROM `vcf_analyzer`.`VcfHeader` WHERE `VcfId` = '"
+ vcfId + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
String result = rs.getString("Header");
rs.close();
return result;
}
throw new IllegalArgumentException("VCF header for: " + vcfId
+ " not found");
} catch (SQLException se) {
throw new SQLException("Invalid Query: " + sql);
}
}
public int createFilter(String filterName) throws SQLException, ClassNotFoundException {
String sql = null;
try {
sql = String.format("INSERT into `Filter` VALUES (NULL, '%s', '0');", filterName);
this.stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = this.stmt.getGeneratedKeys();
rs.next();
return rs.getInt(1);
} catch(SQLException se) {
throw new SQLException(se.getMessage());
}
}
public int createFilterEntry(int filterID, int operator, String infoName, String[] operands) throws SQLException {
String sql = null;
try {
if (operands.length == 1) {
- sql = String.format("INSERT INTO `vcf_analyzer`.`FilterEntry` VALUES (NULL, '%s', '%s', '%d', '%s');",
+ sql = String.format("INSERT INTO `vcf_analyzer`.`FilterEntry` VALUES (NULL, '%s', '%s', '%d', '%s', NULL);",
filterID, infoName, operator, operands[0]);
} else if (operands.length == 2) {
sql = String.format("INSERT INTO `vcf_analyzer`.`FilterEntry` VALUES (NULL, '%s', '%s', '%d', '%s', '%s');",
filterID, infoName, operator, operands[0], operands[1]);
} else if (operands.length == 0) {
System.out.println("No operands given");
return 0;
} else {
System.out.println("Too many operands given");
return 0;
}
System.out.println(sql);
this.stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = this.stmt.getGeneratedKeys();
rs.next();
int filterEntryID = rs.getInt(1);
return filterEntryID;
} catch(SQLException se) {
throw new SQLException(se.getMessage());
}
}
public int getFilterID(String filterName) throws IllegalArgumentException,
SQLException {
String sql = "";
try {
sql = "SELECT `FilID` FROM `vcf_analyzer`.`Filter` WHERE `FilName` = '"
+ filterName + "'";
ResultSet rs = stmt.executeQuery(sql);
if (rs.next()) {
int id = Integer.parseInt(rs.getString("FilId"));
rs.close();
return id;
}
throw new IllegalArgumentException("Filter: " + filterName
+ " not found");
} catch (SQLException se) {
throw new SQLException("Invalid Query " + sql);
}
}
public ResultSet getVcfEntries(long vcfId) throws SQLException {
String sql = "";
try {
sql = "SELECT * FROM `vcf_analyzer`.`VcfEntry` WHERE `VcfId` = '"
+ vcfId + "' ORDER BY `EntryId` ASC";
ResultSet rs = stmt.executeQuery(sql);
return rs;
} catch (SQLException se) {
throw new SQLException("Invalid Query " + sql);
}
}
public ArrayList<String> getInfoTableNames() throws SQLException
{
String sql = "";
ArrayList<String> tables = new ArrayList<String>();
try
{
sql = "SELECT `InfoName` FROM `vcf_analyzer`.`InfoTable` ORDER BY `InfoName` ASC";
ResultSet rs = this.stmt.executeQuery(sql);
while (rs.next()) {
String infoName = rs.getString("InfoName");
if (! EntryFixedInfo.contains(infoName) ) {
tables.add(infoName);
}
}
rs.close();
return tables;
} catch (SQLException se) {
throw new SQLException("Invalid Query " + sql);
}
}
public ResultSet getInfoDatum(long entryId, String infoTableName ) throws SQLException {
String sql = "";
try {
if (! EntryFixedInfo.contains(infoTableName)) {
sql = String
.format("SELECT * FROM `vcf_analyzer`.`%s` WHERE `EntryId` = '%d'",
infoTableName, entryId);
ResultSet infoSet = this.stmt.executeQuery(sql);
return infoSet;
}
return null;
} catch (SQLException se) {
throw new SQLException("Invalid Query " + sql);
}
}
public ResultSet getIndividuals(long entryId) throws SQLException {
String sql = "";
try {
sql = "SELECT * FROM `vcf_analyzer`.`IndividualEntry` WHERE `EntryId` = '"
+ entryId + "' ORDER BY `IndID` ASC";
ResultSet rs = this.stmt.executeQuery(sql);
return rs;
} catch (SQLException se) {
throw new SQLException("Invalid Query " + sql);
}
}
public ResultSet getIndividualDatum(long indId,
String genotypeTableName) throws SQLException {
String sql = "";
try
{
sql = String
.format("SELECT * FROM `vcf_analyzer`.`%s` WHERE `IndID` = '%d'",
genotypeTableName, indId);
ResultSet infoSet = this.stmt.executeQuery(sql);
/*
if (!infoSet.isBeforeFirst()) {
// not empty
return infoSet;
}
*/
//return null;
return infoSet;
} catch (SQLException se) {
throw new SQLException("Invalid Query " + sql);
}
}
public void CloseConnection() throws SQLException {
if (this.conn != null) {
this.conn.close();
}
if (this.stmt != null) {
this.stmt.close();
}
if (this.stmtList != null )
{
for( Statement state : this.stmtList)
{
state.close();
}
}
}
private boolean hasOpenStatementAndConnection() throws SQLException {
return !this.conn.isClosed() && !this.stmt.isClosed();
}
private void reopenConnectionAndStatement() throws SQLException,
ClassNotFoundException {
if (this.conn == null || this.conn.isClosed())
this.conn = DriverManager.getConnection(DB_URL, USER, PASS);
if (this.stmt == null || this.stmt.isClosed())
this.stmt = this.conn.createStatement();
}
/**
*
* TODO consider refactoring to one general upload method
*
* @param name
*
* @param chromosome
* @param position
* @param divValue
* @return TODO
* @throws ClassNotFoundException
* @throws SQLException
*/
protected int uploadDivergence(String name, String chromosome,
int position, int divValue) throws ClassNotFoundException,
SQLException {
if (!hasOpenStatementAndConnection())
reopenConnectionAndStatement();
String sql = String
.format("INSERT into `Divergence` (`DivName`, `Chromosome`, `Position`, `DivValue`) VALUES ('%s','%s','%d','%d');",
name, chromosome, position, divValue);
int rs = this.stmt.executeUpdate(sql);
return rs;
}
/**
* TODO: Finish Testing
*
* @param tableName
* , String idName
*
* @return
* @throws SQLException
* @throws ClassNotFoundException
*/
private int getHighestId(String tableName, String idName)
throws ClassNotFoundException, SQLException {
if (!hasOpenStatementAndConnection())
reopenConnectionAndStatement();
String sql = String.format(
"SELECT %s FROM %s ORDER BY %s desc LIMIT 0,1;", idName,
tableName, idName);
ResultSet rs = this.stmt.executeQuery(sql);
return Integer.parseInt(rs.getString("DivID"));
}
/**
* TODO consider refactoring to one general upload method
*
* @param annoName
* @return TODO
* @throws ClassNotFoundException
* @throws SQLException
*/
protected int uploadAnnotation(String annoName, String chromosome,
int startPosition, int endPosition, String geneName, String geneDirection) throws ClassNotFoundException,
SQLException {
if (!hasOpenStatementAndConnection())
reopenConnectionAndStatement();
String sql = String
.format("INSERT into `Annotation` (`Chromosome`, `StartPosition`, `EndPosition`, `GeneName`, `GeneDirection`, `AnnoName`) VALUES ('%s','%d','%d','%s','%s','%s');",
chromosome, startPosition, endPosition,geneName, geneDirection,annoName);
int rs = this.stmt.executeUpdate(sql);
return rs;
}
}
| true | true | public int createFilterEntry(int filterID, int operator, String infoName, String[] operands) throws SQLException {
String sql = null;
try {
if (operands.length == 1) {
sql = String.format("INSERT INTO `vcf_analyzer`.`FilterEntry` VALUES (NULL, '%s', '%s', '%d', '%s');",
filterID, infoName, operator, operands[0]);
} else if (operands.length == 2) {
sql = String.format("INSERT INTO `vcf_analyzer`.`FilterEntry` VALUES (NULL, '%s', '%s', '%d', '%s', '%s');",
filterID, infoName, operator, operands[0], operands[1]);
} else if (operands.length == 0) {
System.out.println("No operands given");
return 0;
} else {
System.out.println("Too many operands given");
return 0;
}
System.out.println(sql);
this.stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = this.stmt.getGeneratedKeys();
rs.next();
int filterEntryID = rs.getInt(1);
return filterEntryID;
} catch(SQLException se) {
throw new SQLException(se.getMessage());
}
}
| public int createFilterEntry(int filterID, int operator, String infoName, String[] operands) throws SQLException {
String sql = null;
try {
if (operands.length == 1) {
sql = String.format("INSERT INTO `vcf_analyzer`.`FilterEntry` VALUES (NULL, '%s', '%s', '%d', '%s', NULL);",
filterID, infoName, operator, operands[0]);
} else if (operands.length == 2) {
sql = String.format("INSERT INTO `vcf_analyzer`.`FilterEntry` VALUES (NULL, '%s', '%s', '%d', '%s', '%s');",
filterID, infoName, operator, operands[0], operands[1]);
} else if (operands.length == 0) {
System.out.println("No operands given");
return 0;
} else {
System.out.println("Too many operands given");
return 0;
}
System.out.println(sql);
this.stmt.executeUpdate(sql, Statement.RETURN_GENERATED_KEYS);
ResultSet rs = this.stmt.getGeneratedKeys();
rs.next();
int filterEntryID = rs.getInt(1);
return filterEntryID;
} catch(SQLException se) {
throw new SQLException(se.getMessage());
}
}
|
diff --git a/net.mysocio.packs/net.mysocio.rss-pack/src/main/java/net/mysocio/utils/rss/RssUtils.java b/net.mysocio.packs/net.mysocio.rss-pack/src/main/java/net/mysocio/utils/rss/RssUtils.java
index 12a372c..d78112f 100644
--- a/net.mysocio.packs/net.mysocio.rss-pack/src/main/java/net/mysocio/utils/rss/RssUtils.java
+++ b/net.mysocio.packs/net.mysocio.rss-pack/src/main/java/net/mysocio/utils/rss/RssUtils.java
@@ -1,106 +1,116 @@
/**
*
*/
package net.mysocio.utils.rss;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.List;
import net.mysocio.connection.rss.RssSource;
import net.mysocio.data.IDataManager;
import net.mysocio.data.SocioTag;
import net.mysocio.data.UserTags;
import net.mysocio.data.management.DataManagerFactory;
import org.jdom.Document;
import org.jdom.input.SAXBuilder;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.sun.syndication.feed.opml.Opml;
import com.sun.syndication.feed.opml.Outline;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;
import com.sun.syndication.io.impl.OPML20Parser;
/**
* @author Aladdin
*
*/
public class RssUtils {
private static final Logger logger = LoggerFactory
.getLogger(RssUtils.class);
public static void addRssFeed(String userId, String url, String title, SocioTag parent, UserTags userTags)
throws AddingRssException {
RssSource source = new RssSource();
source.setUrl(url);
source.setName(title);
try {
IDataManager dataManager = DataManagerFactory.getDataManager();
dataManager.addSourceToUser(userId, source);
userTags.createTag(url, title, parent);
dataManager.saveObject(userTags);
} catch (Exception e) {
logger.error("Source couldn't be added to user.", e);
throw new AddingRssException(e);
}
}
public static void addRssFeed(String userId, String url, UserTags userTags)
throws AddingRssException {
try {
SyndFeed feed = buldFeed(url);
String title = feed.getTitle();
SocioTag rssFeeds = getRssTag(userTags);
addRssFeed(userId, url, title, rssFeeds, userTags);
} catch (Exception e) {
String message = "Error adding RSS title for url " + url;
logger.error(message, e);
throw new AddingRssException(message, e);
}
}
public static SyndFeed buldFeed(String url) throws FeedException,
IOException, MalformedURLException {
SyndFeedInput input = new SyndFeedInput();
SyndFeed feed = input.build(new XmlReader(new URL(url)));
return feed;
}
public static void importOpml(String userId, String url) throws Exception{
URL feedURL = new URL(url);
importOpml(userId, feedURL.openStream());
}
public static void importOpml(String userId, InputStream stream) throws Exception{
SAXBuilder builder = new SAXBuilder();
Document document = builder.build(new InputStreamReader(stream, "UTF-8"));
importOpml(userId, document);
}
private static void importOpml(String userId, Document document) throws Exception {
OPML20Parser parser = new OPML20Parser();
Opml feed = (Opml) parser.parse(document, true);
List<Outline> outlines = (List<Outline>) feed.getOutlines();
IDataManager dataManager = DataManagerFactory.getDataManager();
UserTags userTags = dataManager.getUserTags(userId);
SocioTag rssFeeds = getRssTag(userTags);
for (Outline outline : outlines) {
List<Outline> children = outline.getChildren();
+ String title = outline.getTitle();
+ if (title == null){
+ title = outline.getText();
+ }
if (children.size() > 0) {
- SocioTag parent = userTags.createTag("RSS_" + outline.getTitle().replace(" ", "_"), outline.getTitle(), rssFeeds);
+ SocioTag parent = userTags.createTag("RSS_" + title.replace(" ", "_"), title, rssFeeds);
for (Outline child : children) {
- addRssFeed(userId, child.getXmlUrl(), child.getTitle(), parent, userTags);
+ String childTitle = child.getTitle();
+ if (childTitle == null){
+ childTitle = child.getText();
+ }
+ addRssFeed(userId, child.getXmlUrl(), childTitle, parent, userTags);
}
+ }else{
+ addRssFeed(userId, outline.getXmlUrl(), title, rssFeeds, userTags);
}
}
}
public static SocioTag getRssTag(UserTags userTags) throws Exception {
IDataManager dataManager = DataManagerFactory.getDataManager();
SocioTag rssFeeds = userTags.createTag("rss.tag", "rss.tag", "rss.icon");
dataManager.saveObject(userTags);
return rssFeeds;
}
}
| false | true | private static void importOpml(String userId, Document document) throws Exception {
OPML20Parser parser = new OPML20Parser();
Opml feed = (Opml) parser.parse(document, true);
List<Outline> outlines = (List<Outline>) feed.getOutlines();
IDataManager dataManager = DataManagerFactory.getDataManager();
UserTags userTags = dataManager.getUserTags(userId);
SocioTag rssFeeds = getRssTag(userTags);
for (Outline outline : outlines) {
List<Outline> children = outline.getChildren();
if (children.size() > 0) {
SocioTag parent = userTags.createTag("RSS_" + outline.getTitle().replace(" ", "_"), outline.getTitle(), rssFeeds);
for (Outline child : children) {
addRssFeed(userId, child.getXmlUrl(), child.getTitle(), parent, userTags);
}
}
}
}
| private static void importOpml(String userId, Document document) throws Exception {
OPML20Parser parser = new OPML20Parser();
Opml feed = (Opml) parser.parse(document, true);
List<Outline> outlines = (List<Outline>) feed.getOutlines();
IDataManager dataManager = DataManagerFactory.getDataManager();
UserTags userTags = dataManager.getUserTags(userId);
SocioTag rssFeeds = getRssTag(userTags);
for (Outline outline : outlines) {
List<Outline> children = outline.getChildren();
String title = outline.getTitle();
if (title == null){
title = outline.getText();
}
if (children.size() > 0) {
SocioTag parent = userTags.createTag("RSS_" + title.replace(" ", "_"), title, rssFeeds);
for (Outline child : children) {
String childTitle = child.getTitle();
if (childTitle == null){
childTitle = child.getText();
}
addRssFeed(userId, child.getXmlUrl(), childTitle, parent, userTags);
}
}else{
addRssFeed(userId, outline.getXmlUrl(), title, rssFeeds, userTags);
}
}
}
|
diff --git a/src/net/java/sip/communicator/util/xml/DOMElementWriter.java b/src/net/java/sip/communicator/util/xml/DOMElementWriter.java
index 22955b250..1bd86eaa5 100644
--- a/src/net/java/sip/communicator/util/xml/DOMElementWriter.java
+++ b/src/net/java/sip/communicator/util/xml/DOMElementWriter.java
@@ -1,330 +1,330 @@
package net.java.sip.communicator.util.xml;
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*
* The code in this class was borrowed from the ant libs and included the
* following copyright notice:
* Copyright 2000-2004 The Apache Software Foundation
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
import java.io.IOException;
import java.io.OutputStream;
import java.io.OutputStreamWriter;
import java.io.Writer;
import org.w3c.dom.Attr;
import org.w3c.dom.Element;
import org.w3c.dom.NamedNodeMap;
import org.w3c.dom.Node;
import org.w3c.dom.NodeList;
import org.w3c.dom.Text;
/**
* Writes a DOM tree to a given Writer.
*
* <p>Utility class used by {@link net.java.sip.communicator.util.xml.XMLUtils
* XMLUtils}
* and the {@link net.java.sip.communicator.slick.runner.SipCommunicatorSlickRunner
* SipCommunicatorSlickRunner}.
* </p>
*
*/
public class DOMElementWriter {
private static String lSep = System.getProperty("line.separator");
/**
* Don't try to be too smart but at least recognize the predefined
* entities.
*/
protected String[] knownEntities = {"gt", "amp", "lt", "apos", "quot"};
/**
* Writes a DOM tree to a stream in UTF8 encoding. Note that
* it prepends the <?xml version='1.0' encoding='UTF-8'?>.
* The indent number is set to 0 and a 2-space indent.
* @param root the root element of the DOM tree.
* @param out the outputstream to write to.
* @throws IOException if an error happens while writing to the stream.
*/
public void write(Element root, OutputStream out) throws IOException {
Writer wri = new OutputStreamWriter(out, "UTF8");
wri.write("<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n");
write(root, wri, 0, " ");
wri.flush();
}
/**
* Writes a DOM tree to a stream.
*
* @param element the Root DOM element of the tree
* @param out where to send the output
* @param indent number of
* @param indentWith string that should be used to indent the corresponding tag.
* @throws IOException if an error happens while writing to the stream.
*/
public void write(Element element, Writer out, int indent,
String indentWith)
throws IOException {
// Write indent characters
for (int i = 0; i < indent; i++) {
out.write(indentWith);
}
// Write element
out.write("<");
out.write(element.getTagName());
// Write attributes
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
out.write(" ");
out.write(attr.getName());
out.write("=\"");
out.write(encode(attr.getValue()));
out.write("\"");
}
out.write(">");
// Write child elements and text
boolean hasChildren = false;
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
if (!hasChildren) {
out.write(lSep);
hasChildren = true;
}
write((Element) child, out, indent + 1, indentWith);
break;
case Node.TEXT_NODE:
//if this is a new line don't print it as we print our own.
- if(child.getNodeValue().indexOf(lSep) == -1)
+ if(child.getNodeValue() != null && child.getNodeValue().indexOf(lSep) == -1)
out.write(encode(child.getNodeValue()));
break;
case Node.COMMENT_NODE:
out.write("<!--");
out.write(encode(child.getNodeValue()));
out.write("-->");
break;
case Node.CDATA_SECTION_NODE:
out.write("<![CDATA[");
out.write(encodedata(((Text) child).getData()));
out.write("]]>");
break;
case Node.ENTITY_REFERENCE_NODE:
out.write('&');
out.write(child.getNodeName());
out.write(';');
break;
case Node.PROCESSING_INSTRUCTION_NODE:
out.write("<?");
out.write(child.getNodeName());
String data = child.getNodeValue();
if (data != null && data.length() > 0) {
out.write(' ');
out.write(data);
}
out.write("?>");
break;
}
}
// If we had child elements, we need to indent before we close
// the element, otherwise we're on the same line and don't need
// to indent
if (hasChildren) {
for (int i = 0; i < indent; i++) {
out.write(indentWith);
}
}
// Write element close
out.write("</");
out.write(element.getTagName());
out.write(">");
out.write(lSep);
out.flush();
}
/**
* Escape <, > & ', " as their entities and
* drop characters that are illegal in XML documents.
*
* @param value the value to encode
*
* @return a String containing the encoded element.
*/
public String encode(String value) {
StringBuffer sb = new StringBuffer();
int len = value.length();
for (int i = 0; i < len; i++) {
char c = value.charAt(i);
switch (c) {
case '<':
sb.append("<");
break;
case '>':
sb.append(">");
break;
case '\'':
sb.append("'");
break;
case '\"':
sb.append(""");
break;
case '&':
int nextSemi = value.indexOf(";", i);
if (nextSemi < 0
|| !isReference(value.substring(i, nextSemi + 1))) {
sb.append("&");
} else {
sb.append('&');
}
break;
default:
if (isLegalCharacter(c)) {
sb.append(c);
}
break;
}
}
return sb.substring(0);
}
/**
* Drop characters that are illegal in XML documents.
*
* <p>Also ensure that we are not including an <tt>]]></tt>
* marker by replacing that sequence with
* <tt>&#x5d;&#x5d;&gt;</tt>.</p>
*
* <p>See XML 1.0 2.2 <a
* href="http://www.w3.org/TR/1998/REC-xml-19980210#charsets">http://www.w3.org/TR/1998/REC-xml-19980210#charsets</a> and
* 2.7 <a
* href="http://www.w3.org/TR/1998/REC-xml-19980210#sec-cdata-sect">http://www.w3.org/TR/1998/REC-xml-19980210#sec-cdata-sect</a>.</p>
*
* @param value the value to encode
*
* @return a String containing the encoded value.
*/
public String encodedata(final String value) {
StringBuffer sb = new StringBuffer();
int len = value.length();
for (int i = 0; i < len; ++i) {
char c = value.charAt(i);
if (isLegalCharacter(c)) {
sb.append(c);
}
}
String result = sb.substring(0);
int cdEnd = result.indexOf("]]>");
while (cdEnd != -1) {
sb.setLength(cdEnd);
sb.append("]]>")
.append(result.substring(cdEnd + 3));
result = sb.substring(0);
cdEnd = result.indexOf("]]>");
}
return result;
}
/**
* Is the given argument a character or entity reference?
*
*
* @param ent the string whose nature we need to determine.
*
* @return true if ent is an entity reference and false otherwise.
*/
public boolean isReference(String ent) {
if (!(ent.charAt(0) == '&') || !ent.endsWith(";")) {
return false;
}
if (ent.charAt(1) == '#') {
if (ent.charAt(2) == 'x') {
try {
Integer.parseInt(ent.substring(3, ent.length() - 1), 16);
return true;
} catch (NumberFormatException nfe) {
return false;
}
} else {
try {
Integer.parseInt(ent.substring(2, ent.length() - 1));
return true;
} catch (NumberFormatException nfe) {
return false;
}
}
}
String name = ent.substring(1, ent.length() - 1);
for (int i = 0; i < knownEntities.length; i++) {
if (name.equals(knownEntities[i])) {
return true;
}
}
return false;
}
/**
* Is the given character allowed inside an XML document?
*
* <p>See XML 1.0 2.2 <a
* href="http://www.w3.org/TR/1998/REC-xml-19980210#charsets">
* http://www.w3.org/TR/1998/REC-xml-19980210#charsets</a>.</p>
*
* @since 1.10, Ant 1.5
*
* @param c the character hose nature we'd like to determine.
*
* @return true if c is a legal character and false otherwise
*/
public boolean isLegalCharacter(char c) {
if (c == 0x9 || c == 0xA || c == 0xD) {
return true;
} else if (c < 0x20) {
return false;
} else if (c <= 0xD7FF) {
return true;
} else if (c < 0xE000) {
return false;
} else if (c <= 0xFFFD) {
return true;
}
return false;
}
}
| true | true | public void write(Element element, Writer out, int indent,
String indentWith)
throws IOException {
// Write indent characters
for (int i = 0; i < indent; i++) {
out.write(indentWith);
}
// Write element
out.write("<");
out.write(element.getTagName());
// Write attributes
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
out.write(" ");
out.write(attr.getName());
out.write("=\"");
out.write(encode(attr.getValue()));
out.write("\"");
}
out.write(">");
// Write child elements and text
boolean hasChildren = false;
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
if (!hasChildren) {
out.write(lSep);
hasChildren = true;
}
write((Element) child, out, indent + 1, indentWith);
break;
case Node.TEXT_NODE:
//if this is a new line don't print it as we print our own.
if(child.getNodeValue().indexOf(lSep) == -1)
out.write(encode(child.getNodeValue()));
break;
case Node.COMMENT_NODE:
out.write("<!--");
out.write(encode(child.getNodeValue()));
out.write("-->");
break;
case Node.CDATA_SECTION_NODE:
out.write("<![CDATA[");
out.write(encodedata(((Text) child).getData()));
out.write("]]>");
break;
case Node.ENTITY_REFERENCE_NODE:
out.write('&');
out.write(child.getNodeName());
out.write(';');
break;
case Node.PROCESSING_INSTRUCTION_NODE:
out.write("<?");
out.write(child.getNodeName());
String data = child.getNodeValue();
if (data != null && data.length() > 0) {
out.write(' ');
out.write(data);
}
out.write("?>");
break;
}
}
// If we had child elements, we need to indent before we close
// the element, otherwise we're on the same line and don't need
// to indent
if (hasChildren) {
for (int i = 0; i < indent; i++) {
out.write(indentWith);
}
}
// Write element close
out.write("</");
out.write(element.getTagName());
out.write(">");
out.write(lSep);
out.flush();
}
| public void write(Element element, Writer out, int indent,
String indentWith)
throws IOException {
// Write indent characters
for (int i = 0; i < indent; i++) {
out.write(indentWith);
}
// Write element
out.write("<");
out.write(element.getTagName());
// Write attributes
NamedNodeMap attrs = element.getAttributes();
for (int i = 0; i < attrs.getLength(); i++) {
Attr attr = (Attr) attrs.item(i);
out.write(" ");
out.write(attr.getName());
out.write("=\"");
out.write(encode(attr.getValue()));
out.write("\"");
}
out.write(">");
// Write child elements and text
boolean hasChildren = false;
NodeList children = element.getChildNodes();
for (int i = 0; i < children.getLength(); i++) {
Node child = children.item(i);
switch (child.getNodeType()) {
case Node.ELEMENT_NODE:
if (!hasChildren) {
out.write(lSep);
hasChildren = true;
}
write((Element) child, out, indent + 1, indentWith);
break;
case Node.TEXT_NODE:
//if this is a new line don't print it as we print our own.
if(child.getNodeValue() != null && child.getNodeValue().indexOf(lSep) == -1)
out.write(encode(child.getNodeValue()));
break;
case Node.COMMENT_NODE:
out.write("<!--");
out.write(encode(child.getNodeValue()));
out.write("-->");
break;
case Node.CDATA_SECTION_NODE:
out.write("<![CDATA[");
out.write(encodedata(((Text) child).getData()));
out.write("]]>");
break;
case Node.ENTITY_REFERENCE_NODE:
out.write('&');
out.write(child.getNodeName());
out.write(';');
break;
case Node.PROCESSING_INSTRUCTION_NODE:
out.write("<?");
out.write(child.getNodeName());
String data = child.getNodeValue();
if (data != null && data.length() > 0) {
out.write(' ');
out.write(data);
}
out.write("?>");
break;
}
}
// If we had child elements, we need to indent before we close
// the element, otherwise we're on the same line and don't need
// to indent
if (hasChildren) {
for (int i = 0; i < indent; i++) {
out.write(indentWith);
}
}
// Write element close
out.write("</");
out.write(element.getTagName());
out.write(">");
out.write(lSep);
out.flush();
}
|
diff --git a/discovery/src/main/java/com/proofpoint/discovery/client/CachingServiceSelector.java b/discovery/src/main/java/com/proofpoint/discovery/client/CachingServiceSelector.java
index a702c5c9c..fc8de67bd 100644
--- a/discovery/src/main/java/com/proofpoint/discovery/client/CachingServiceSelector.java
+++ b/discovery/src/main/java/com/proofpoint/discovery/client/CachingServiceSelector.java
@@ -1,139 +1,139 @@
package com.proofpoint.discovery.client;
import com.google.common.base.Preconditions;
import com.google.common.collect.ImmutableList;
import com.google.common.util.concurrent.CheckedFuture;
import com.proofpoint.log.Logger;
import com.proofpoint.units.Duration;
import javax.annotation.PostConstruct;
import java.util.List;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicReference;
import static com.proofpoint.discovery.client.DiscoveryAnnouncementClient.DEFAULT_DELAY;
public class CachingServiceSelector implements ServiceSelector
{
private final static Logger log = Logger.get(CachingServiceSelector.class);
private final String type;
private final String pool;
private final DiscoveryLookupClient lookupClient;
private final AtomicReference<ServiceDescriptors> serviceDescriptors = new AtomicReference<ServiceDescriptors>();
private final ScheduledExecutorService executor;
private final AtomicBoolean serverUp = new AtomicBoolean(true);
private final AtomicBoolean started = new AtomicBoolean(false);
public CachingServiceSelector(String type, ServiceSelectorConfig selectorConfig, DiscoveryLookupClient lookupClient, ScheduledExecutorService executor)
{
Preconditions.checkNotNull(type, "type is null");
Preconditions.checkNotNull(selectorConfig, "selectorConfig is null");
Preconditions.checkNotNull(lookupClient, "client is null");
Preconditions.checkNotNull(executor, "executor is null");
this.type = type;
this.pool = selectorConfig.getPool();
this.lookupClient = lookupClient;
this.executor = executor;
}
@PostConstruct
public void start()
throws TimeoutException
{
if (started.compareAndSet(false, true)) {
Preconditions.checkState(!executor.isShutdown(), "CachingServiceSelector has been destroyed");
// if discovery is available, get the initial set of servers before starting
try {
refresh().checkedGet(30, TimeUnit.SECONDS);
}
catch (Exception ignored) {
}
}
}
@Override
public String getType()
{
return type;
}
@Override
public String getPool()
{
return pool;
}
@Override
public List<ServiceDescriptor> selectAllServices()
{
ServiceDescriptors serviceDescriptors = this.serviceDescriptors.get();
if (serviceDescriptors == null) {
return ImmutableList.of();
}
return serviceDescriptors.getServiceDescriptors();
}
private CheckedFuture<ServiceDescriptors, DiscoveryException> refresh()
{
final ServiceDescriptors oldDescriptors = this.serviceDescriptors.get();
final CheckedFuture<ServiceDescriptors, DiscoveryException> future;
if (oldDescriptors == null) {
future = lookupClient.getServices(type, pool);
}
else {
future = lookupClient.refreshServices(oldDescriptors);
}
future.addListener(new Runnable()
{
@Override
public void run()
{
Duration delay = DEFAULT_DELAY;
try {
ServiceDescriptors newDescriptors = future.checkedGet();
delay = newDescriptors.getMaxAge();
serviceDescriptors.set(newDescriptors);
if (serverUp.compareAndSet(false, true)) {
log.info("Discovery server connect succeeded for refresh (%s/%s)", type, pool);
}
}
catch (DiscoveryException e) {
if (serverUp.compareAndSet(true, false)) {
log.error("Cannot connect to discovery server for refresh (%s/%s): %s", type, pool, e.getMessage());
}
- log.debug(e, "Cannot connect to discovery server for refresh (%s/%s): %s", type, pool);
+ log.debug(e, "Cannot connect to discovery server for refresh (%s/%s)", type, pool);
}
finally {
scheduleRefresh(delay);
}
}
}, executor);
return future;
}
private void scheduleRefresh(Duration delay)
{
// already stopped? avoids rejection exception
if (executor.isShutdown()) {
return;
}
executor.schedule(new Runnable() {
@Override
public void run()
{
refresh();
}
}, (long) delay.toMillis(), TimeUnit.MILLISECONDS);
}
}
| true | true | private CheckedFuture<ServiceDescriptors, DiscoveryException> refresh()
{
final ServiceDescriptors oldDescriptors = this.serviceDescriptors.get();
final CheckedFuture<ServiceDescriptors, DiscoveryException> future;
if (oldDescriptors == null) {
future = lookupClient.getServices(type, pool);
}
else {
future = lookupClient.refreshServices(oldDescriptors);
}
future.addListener(new Runnable()
{
@Override
public void run()
{
Duration delay = DEFAULT_DELAY;
try {
ServiceDescriptors newDescriptors = future.checkedGet();
delay = newDescriptors.getMaxAge();
serviceDescriptors.set(newDescriptors);
if (serverUp.compareAndSet(false, true)) {
log.info("Discovery server connect succeeded for refresh (%s/%s)", type, pool);
}
}
catch (DiscoveryException e) {
if (serverUp.compareAndSet(true, false)) {
log.error("Cannot connect to discovery server for refresh (%s/%s): %s", type, pool, e.getMessage());
}
log.debug(e, "Cannot connect to discovery server for refresh (%s/%s): %s", type, pool);
}
finally {
scheduleRefresh(delay);
}
}
}, executor);
return future;
}
| private CheckedFuture<ServiceDescriptors, DiscoveryException> refresh()
{
final ServiceDescriptors oldDescriptors = this.serviceDescriptors.get();
final CheckedFuture<ServiceDescriptors, DiscoveryException> future;
if (oldDescriptors == null) {
future = lookupClient.getServices(type, pool);
}
else {
future = lookupClient.refreshServices(oldDescriptors);
}
future.addListener(new Runnable()
{
@Override
public void run()
{
Duration delay = DEFAULT_DELAY;
try {
ServiceDescriptors newDescriptors = future.checkedGet();
delay = newDescriptors.getMaxAge();
serviceDescriptors.set(newDescriptors);
if (serverUp.compareAndSet(false, true)) {
log.info("Discovery server connect succeeded for refresh (%s/%s)", type, pool);
}
}
catch (DiscoveryException e) {
if (serverUp.compareAndSet(true, false)) {
log.error("Cannot connect to discovery server for refresh (%s/%s): %s", type, pool, e.getMessage());
}
log.debug(e, "Cannot connect to discovery server for refresh (%s/%s)", type, pool);
}
finally {
scheduleRefresh(delay);
}
}
}, executor);
return future;
}
|
diff --git a/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java b/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
index 84fde91..989d656 100644
--- a/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
+++ b/src/main/java/hudson/plugins/msbuild/MsBuildBuilder.java
@@ -1,178 +1,178 @@
package hudson.plugins.msbuild;
import hudson.*;
import hudson.model.AbstractBuild;
import hudson.model.BuildListener;
import hudson.model.Computer;
import hudson.model.Descriptor;
import hudson.tasks.Builder;
import hudson.tools.ToolInstallation;
import hudson.util.ArgumentListBuilder;
import org.kohsuke.stapler.DataBoundConstructor;
import java.io.IOException;
/**
* @author [email protected]
*/
public class MsBuildBuilder extends Builder {
/**
* GUI fields
*/
private final String msBuildName;
private final String msBuildFile;
private final String cmdLineArgs;
/**
* When this builder is created in the project configuration step,
* the builder object will be created from the strings below.
*
* @param msBuildName The Visual studio logical name
* @param msBuildFile The name/location of the msbuild file
* @param cmdLineArgs Whitespace separated list of command line arguments
*/
@DataBoundConstructor
@SuppressWarnings("unused")
public MsBuildBuilder(String msBuildName, String msBuildFile, String cmdLineArgs) {
this.msBuildName = msBuildName;
this.msBuildFile = msBuildFile;
this.cmdLineArgs = cmdLineArgs;
}
@SuppressWarnings("unused")
public String getCmdLineArgs() {
return cmdLineArgs;
}
@SuppressWarnings("unused")
public String getMsBuildFile() {
return msBuildFile;
}
@SuppressWarnings("unused")
public String getMsBuildName() {
return msBuildName;
}
public MsBuildInstallation getMsBuild() {
for (MsBuildInstallation i : DESCRIPTOR.getInstallations()) {
if (msBuildName != null && i.getName().equals(msBuildName))
return i;
}
return null;
}
@Override
public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
String execName = "msbuild.exe";
MsBuildInstallation ai = getMsBuild();
if (ai == null) {
listener.getLogger().println("Path To MSBuild.exe: " + execName);
args.add(execName);
} else {
EnvVars env = build.getEnvironment(listener);
ai = ai.forNode(Computer.currentComputer().getNode(), listener);
ai = ai.forEnvironment(env);
String pathToMsBuild = ai.getHome();
FilePath exec = new FilePath(launcher.getChannel(), pathToMsBuild);
try {
if (!exec.exists()) {
listener.fatalError(pathToMsBuild + " doesn't exist");
return false;
}
} catch (IOException e) {
listener.fatalError("Failed checking for existence of " + pathToMsBuild);
return false;
}
listener.getLogger().println("Path To MSBuild.exe: " + pathToMsBuild);
args.add(pathToMsBuild);
}
if (ai.getDefaultArgs() != null) {
- args.add(ai.getDefaultArgs());
+ args.addTokenized(ai.getDefaultArgs());
}
EnvVars env = build.getEnvironment(listener);
String normalizedArgs = cmdLineArgs.replaceAll("[\t\r\n]+", " ");
normalizedArgs = Util.replaceMacro(normalizedArgs, env);
normalizedArgs = Util.replaceMacro(normalizedArgs, build.getBuildVariables());
if (normalizedArgs.trim().length() > 0)
args.addTokenized(normalizedArgs);
args.addKeyValuePairs("/P:", build.getBuildVariables());
//If a msbuild file is specified, then add it as an argument, otherwise
//msbuild will search for any file that ends in .proj or .sln
if (msBuildFile != null && msBuildFile.trim().length() > 0) {
String normalizedFile = msBuildFile.replaceAll("[\t\r\n]+", " ");
normalizedFile = Util.replaceMacro(normalizedFile, env);
normalizedFile = Util.replaceMacro(normalizedFile, build.getBuildVariables());
if (normalizedFile.length() > 0)
args.add(normalizedFile);
}
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
listener.getLogger().println("Executing command: " + args.toStringWithQuote());
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(build.getModuleRoot()).join();
return r == 0;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
@Override
public Descriptor<Builder> getDescriptor() {
return DESCRIPTOR;
}
/**
* Descriptor should be singleton.
*/
@Extension
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends Descriptor<Builder> {
@CopyOnWrite
private volatile MsBuildInstallation[] installations = new MsBuildInstallation[0];
DescriptorImpl() {
super(MsBuildBuilder.class);
load();
}
public String getDisplayName() {
return "Build a Visual Studio project or solution using MSBuild.";
}
public MsBuildInstallation[] getInstallations() {
return installations;
}
public void setInstallations(MsBuildInstallation... antInstallations) {
this.installations = antInstallations;
save();
}
/**
* Obtains the {@link MsBuildInstallation.DescriptorImpl} instance.
*/
public MsBuildInstallation.DescriptorImpl getToolDescriptor() {
return ToolInstallation.all().get(MsBuildInstallation.DescriptorImpl.class);
}
}
}
| true | true | public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
String execName = "msbuild.exe";
MsBuildInstallation ai = getMsBuild();
if (ai == null) {
listener.getLogger().println("Path To MSBuild.exe: " + execName);
args.add(execName);
} else {
EnvVars env = build.getEnvironment(listener);
ai = ai.forNode(Computer.currentComputer().getNode(), listener);
ai = ai.forEnvironment(env);
String pathToMsBuild = ai.getHome();
FilePath exec = new FilePath(launcher.getChannel(), pathToMsBuild);
try {
if (!exec.exists()) {
listener.fatalError(pathToMsBuild + " doesn't exist");
return false;
}
} catch (IOException e) {
listener.fatalError("Failed checking for existence of " + pathToMsBuild);
return false;
}
listener.getLogger().println("Path To MSBuild.exe: " + pathToMsBuild);
args.add(pathToMsBuild);
}
if (ai.getDefaultArgs() != null) {
args.add(ai.getDefaultArgs());
}
EnvVars env = build.getEnvironment(listener);
String normalizedArgs = cmdLineArgs.replaceAll("[\t\r\n]+", " ");
normalizedArgs = Util.replaceMacro(normalizedArgs, env);
normalizedArgs = Util.replaceMacro(normalizedArgs, build.getBuildVariables());
if (normalizedArgs.trim().length() > 0)
args.addTokenized(normalizedArgs);
args.addKeyValuePairs("/P:", build.getBuildVariables());
//If a msbuild file is specified, then add it as an argument, otherwise
//msbuild will search for any file that ends in .proj or .sln
if (msBuildFile != null && msBuildFile.trim().length() > 0) {
String normalizedFile = msBuildFile.replaceAll("[\t\r\n]+", " ");
normalizedFile = Util.replaceMacro(normalizedFile, env);
normalizedFile = Util.replaceMacro(normalizedFile, build.getBuildVariables());
if (normalizedFile.length() > 0)
args.add(normalizedFile);
}
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
listener.getLogger().println("Executing command: " + args.toStringWithQuote());
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(build.getModuleRoot()).join();
return r == 0;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
| public boolean perform(AbstractBuild<?, ?> build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
ArgumentListBuilder args = new ArgumentListBuilder();
String execName = "msbuild.exe";
MsBuildInstallation ai = getMsBuild();
if (ai == null) {
listener.getLogger().println("Path To MSBuild.exe: " + execName);
args.add(execName);
} else {
EnvVars env = build.getEnvironment(listener);
ai = ai.forNode(Computer.currentComputer().getNode(), listener);
ai = ai.forEnvironment(env);
String pathToMsBuild = ai.getHome();
FilePath exec = new FilePath(launcher.getChannel(), pathToMsBuild);
try {
if (!exec.exists()) {
listener.fatalError(pathToMsBuild + " doesn't exist");
return false;
}
} catch (IOException e) {
listener.fatalError("Failed checking for existence of " + pathToMsBuild);
return false;
}
listener.getLogger().println("Path To MSBuild.exe: " + pathToMsBuild);
args.add(pathToMsBuild);
}
if (ai.getDefaultArgs() != null) {
args.addTokenized(ai.getDefaultArgs());
}
EnvVars env = build.getEnvironment(listener);
String normalizedArgs = cmdLineArgs.replaceAll("[\t\r\n]+", " ");
normalizedArgs = Util.replaceMacro(normalizedArgs, env);
normalizedArgs = Util.replaceMacro(normalizedArgs, build.getBuildVariables());
if (normalizedArgs.trim().length() > 0)
args.addTokenized(normalizedArgs);
args.addKeyValuePairs("/P:", build.getBuildVariables());
//If a msbuild file is specified, then add it as an argument, otherwise
//msbuild will search for any file that ends in .proj or .sln
if (msBuildFile != null && msBuildFile.trim().length() > 0) {
String normalizedFile = msBuildFile.replaceAll("[\t\r\n]+", " ");
normalizedFile = Util.replaceMacro(normalizedFile, env);
normalizedFile = Util.replaceMacro(normalizedFile, build.getBuildVariables());
if (normalizedFile.length() > 0)
args.add(normalizedFile);
}
if (!launcher.isUnix()) {
args.prepend("cmd.exe", "/C");
args.add("&&", "exit", "%%ERRORLEVEL%%");
}
listener.getLogger().println("Executing command: " + args.toStringWithQuote());
try {
int r = launcher.launch().cmds(args).envs(env).stdout(listener).pwd(build.getModuleRoot()).join();
return r == 0;
} catch (IOException e) {
Util.displayIOException(e, listener);
e.printStackTrace(listener.fatalError("command execution failed"));
return false;
}
}
|
diff --git a/jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/StandardStreamTest.java b/jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/StandardStreamTest.java
index ff73b456c..b920f0949 100644
--- a/jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/StandardStreamTest.java
+++ b/jetty-spdy/spdy-core/src/test/java/org/eclipse/jetty/spdy/StandardStreamTest.java
@@ -1,112 +1,112 @@
// ========================================================================
// Copyright (c) 2009-2009 Mort Bay Consulting Pty. Ltd.
// ------------------------------------------------------------------------
// All rights reserved. This program and the accompanying materials
// are made available under the terms of the Eclipse Public License v1.0
// and Apache License v2.0 which accompanies this distribution.
// The Eclipse Public License is available at
// http://www.eclipse.org/legal/epl-v10.html
// The Apache License v2.0 is available at
// http://www.opensource.org/licenses/apache2.0.php
// You may elect to redistribute this code under either of these licenses.
// ========================================================================
package org.eclipse.jetty.spdy;
import static org.hamcrest.Matchers.equalTo;
import static org.hamcrest.Matchers.is;
import static org.junit.Assert.assertThat;
import static org.mockito.Matchers.any;
import static org.mockito.Matchers.anyLong;
import static org.mockito.Matchers.argThat;
import static org.mockito.Mockito.verify;
import static org.mockito.Mockito.when;
import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import org.eclipse.jetty.spdy.api.Handler;
import org.eclipse.jetty.spdy.api.Stream;
import org.eclipse.jetty.spdy.api.StreamFrameListener;
import org.eclipse.jetty.spdy.api.SynInfo;
import org.eclipse.jetty.spdy.frames.SynStreamFrame;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.ArgumentMatcher;
import org.mockito.Mock;
import org.mockito.runners.MockitoJUnitRunner;
/* ------------------------------------------------------------ */
/**
*/
@RunWith(MockitoJUnitRunner.class)
public class StandardStreamTest
{
@Mock private ISession session;
@Mock private SynStreamFrame synStreamFrame;
/**
* Test method for {@link org.eclipse.jetty.spdy.StandardStream#syn(org.eclipse.jetty.spdy.api.SynInfo)}.
*/
@SuppressWarnings("unchecked")
@Test
public void testSyn()
{
Stream stream = new StandardStream(synStreamFrame,session,0,null);
Map<Integer,Stream> streams = new HashMap<>();
streams.put(stream.getId(),stream);
when(synStreamFrame.isClose()).thenReturn(false);
SynInfo synInfo = new SynInfo(false);
when(session.getStreams()).thenReturn(streams);
stream.syn(synInfo);
verify(session).syn(argThat(new PushSynInfoMatcher(stream.getId(),synInfo)),any(StreamFrameListener.class),anyLong(),any(TimeUnit.class),any(Handler.class));
}
private class PushSynInfoMatcher extends ArgumentMatcher<PushSynInfo>{
int associatedStreamId;
SynInfo synInfo;
public PushSynInfoMatcher(int associatedStreamId, SynInfo synInfo)
{
this.associatedStreamId = associatedStreamId;
this.synInfo = synInfo;
}
@Override
public boolean matches(Object argument)
{
PushSynInfo pushSynInfo = (PushSynInfo)argument;
if(pushSynInfo.getAssociatedStreamId() != associatedStreamId){
System.out.println("streamIds do not match!");
return false;
}
if(pushSynInfo.isClose() != synInfo.isClose()){
System.out.println("isClose doesn't match");
return false;
}
return true;
}
}
@Test
public void testSynOnClosedStream(){
IStream stream = new StandardStream(synStreamFrame,session,0,null);
stream.updateCloseState(true,true);
stream.updateCloseState(true,false);
assertThat("stream expected to be closed",stream.isClosed(),is(true));
final CountDownLatch failedLatch = new CountDownLatch(1);
- stream.syn(new SynInfo(false),0,TimeUnit.SECONDS,new Handler.Adapter<Stream>()
+ stream.syn(new SynInfo(false),1,TimeUnit.SECONDS,new Handler.Adapter<Stream>()
{
@Override
public void failed(Throwable x)
{
failedLatch.countDown();
}
});
assertThat("PushStream creation failed", failedLatch.getCount(), equalTo(0L));
}
}
| true | true | public void testSynOnClosedStream(){
IStream stream = new StandardStream(synStreamFrame,session,0,null);
stream.updateCloseState(true,true);
stream.updateCloseState(true,false);
assertThat("stream expected to be closed",stream.isClosed(),is(true));
final CountDownLatch failedLatch = new CountDownLatch(1);
stream.syn(new SynInfo(false),0,TimeUnit.SECONDS,new Handler.Adapter<Stream>()
{
@Override
public void failed(Throwable x)
{
failedLatch.countDown();
}
});
assertThat("PushStream creation failed", failedLatch.getCount(), equalTo(0L));
}
| public void testSynOnClosedStream(){
IStream stream = new StandardStream(synStreamFrame,session,0,null);
stream.updateCloseState(true,true);
stream.updateCloseState(true,false);
assertThat("stream expected to be closed",stream.isClosed(),is(true));
final CountDownLatch failedLatch = new CountDownLatch(1);
stream.syn(new SynInfo(false),1,TimeUnit.SECONDS,new Handler.Adapter<Stream>()
{
@Override
public void failed(Throwable x)
{
failedLatch.countDown();
}
});
assertThat("PushStream creation failed", failedLatch.getCount(), equalTo(0L));
}
|
diff --git a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.project/src/org/wso2/developerstudio/eclipse/esb/project/utils/ESBProjectUtils.java b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.project/src/org/wso2/developerstudio/eclipse/esb/project/utils/ESBProjectUtils.java
index dea59a26a..449fac278 100644
--- a/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.project/src/org/wso2/developerstudio/eclipse/esb/project/utils/ESBProjectUtils.java
+++ b/ide/eclipse/esb/org.wso2.developerstudio.eclipse.esb.project/src/org/wso2/developerstudio/eclipse/esb/project/utils/ESBProjectUtils.java
@@ -1,278 +1,306 @@
/*
* Copyright (c) 2011, WSO2 Inc. (http://www.wso2.org) All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.wso2.developerstudio.eclipse.esb.project.utils;
import java.io.File;
import java.util.List;
import java.util.Map;
import java.util.regex.Pattern;
import javax.xml.namespace.QName;
import javax.xml.stream.FactoryConfigurationError;
import org.apache.axiom.om.OMElement;
import org.apache.maven.model.Plugin;
import org.apache.maven.model.PluginExecution;
import org.apache.maven.model.Repository;
import org.apache.maven.model.RepositoryPolicy;
import org.apache.maven.project.MavenProject;
import org.codehaus.plexus.util.xml.Xpp3Dom;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.ResourcesPlugin;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.jface.dialogs.Dialog;
import org.eclipse.jface.viewers.IStructuredSelection;
import org.eclipse.jface.wizard.WizardDialog;
import org.eclipse.swt.widgets.Shell;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.wizards.IWizardDescriptor;
import org.wso2.developerstudio.eclipse.capp.maven.utils.MavenConstants;
import org.wso2.developerstudio.eclipse.esb.project.Activator;
import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBArtifact;
import org.wso2.developerstudio.eclipse.esb.project.artifact.ESBProjectArtifact;
import org.wso2.developerstudio.eclipse.esb.project.ui.wizard.ESBProjectWizard;
import org.wso2.developerstudio.eclipse.logging.core.IDeveloperStudioLog;
import org.wso2.developerstudio.eclipse.logging.core.Logger;
import org.wso2.developerstudio.eclipse.maven.util.MavenUtils;
import org.wso2.developerstudio.eclipse.utils.file.FileUtils;
public class ESBProjectUtils {
private static IDeveloperStudioLog log=Logger.getLog(Activator.PLUGIN_ID);
public static IProject createESBProject(Shell shell){
IWizardDescriptor wizardDesc = PlatformUI.getWorkbench().getNewWizardRegistry().findWizard("org.wso2.developerstudio.eclipse.artifact.newesbproject");
if (wizardDesc!=null) {
try {
IProject esbProject = null;
ESBProjectWizard esbProjectWizard = (ESBProjectWizard) wizardDesc.createWizard();
IStructuredSelection selection = (IStructuredSelection) PlatformUI
.getWorkbench().getActiveWorkbenchWindow()
.getSelectionService().getSelection();
esbProjectWizard.init(PlatformUI.getWorkbench(), selection);
WizardDialog dialog = new WizardDialog(shell, esbProjectWizard);
dialog.create();
if(dialog.open() ==Dialog.OK){
String projectName = esbProjectWizard.getModel().getProjectName();
esbProject = ResourcesPlugin.getWorkspace().getRoot()
.getProject(projectName);
}
return esbProject;
} catch (CoreException e) {
log.error("CoreException has occurred",e);
}
}
return null;
}
public static boolean artifactExists(IProject project, String artifactName) throws Exception {
ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact();
esbProjectArtifact.fromFile(project.getFile("artifact.xml").getLocation().toFile());
List<ESBArtifact> allArtifacts = esbProjectArtifact.getAllESBArtifacts();
for (ESBArtifact artifact : allArtifacts) {
if (artifactName.equalsIgnoreCase(artifact.getName()))
return true;
}
return false;
}
public static void createESBArtifacts(List<OMElement> selectedElementsList,IProject project,File pomfile,Map<File,String> fileList,
String groupId) throws FactoryConfigurationError, Exception {
if (selectedElementsList != null) {
for (OMElement element : selectedElementsList) {
String localName = element.getLocalName();
String qName = element.getAttributeValue(new QName("name"));
if (("".equals(qName)) || (qName == null)) {
qName = element.getAttributeValue(new QName("key"));
if (("".equals(qName)) || (qName == null)) {
continue;
}
}
//esbProjectModel.setName(qName);
String commonESBPath = "src" + File.separator + "main"
+ File.separator + "synapse-config" + File.separator;
if (localName.equalsIgnoreCase("sequence")) {
File baseDir = project
.getFolder(commonESBPath + "sequences")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-sequence-plugin",
MavenConstants.WSO2_ESB_SEQUENCE_VERSION,
"sequence");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "sequence");
createArtifactMetaDataEntry(qName, "synapse/sequence",
baseDir, groupId + ".sequence",project);
} else if (localName.equalsIgnoreCase("endpoint")) {
File baseDir = project
.getFolder(commonESBPath + "endpoints")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-endpoint-plugin",
MavenConstants.WSO2_ESB_ENDPOINT_VERSION,
"endpoint");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "endpoint");
createArtifactMetaDataEntry(qName, "synapse/endpoint",
baseDir, groupId + ".endpoint",project);
} else if (localName.equalsIgnoreCase("proxy")) {
File baseDir = project
.getFolder(commonESBPath + "proxy-services")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-proxy-plugin",
MavenConstants.WSO2_ESB_PROXY_VERSION, "proxy");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "proxy");
createArtifactMetaDataEntry(qName, "synapse/proxy-service",
baseDir, groupId + ".proxy-service",project);
} else if (localName.equalsIgnoreCase("localEntry")) {
File baseDir = project
.getFolder(commonESBPath + "local-entries")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-localentry-plugin",
MavenConstants.WSO2_ESB_LOCAL_ENTRY_VERSION,
"localentry");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "localEntry");
createArtifactMetaDataEntry(qName, "synapse/local-entry",
baseDir, groupId + ".local-entry",project);
} else if (localName.equalsIgnoreCase("task")) {
File baseDir = project.getFolder(commonESBPath + "task")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-task-plugin",
MavenConstants.WSO2_ESB_TASK_VERSION, "task");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "task");
createArtifactMetaDataEntry(qName, "synapse/task", baseDir,
groupId + ".task",project);
} else if (localName.equalsIgnoreCase("api")) {
File baseDir = project.getFolder(commonESBPath + "api")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-api-plugin",
MavenConstants.WSO2_ESB_API_VERSION, "api");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "api");
createArtifactMetaDataEntry(qName, "synapse/api", baseDir,
groupId + ".api",project);
+ } else if (localName.equalsIgnoreCase("messageStore")) {
+ File baseDir = project.getFolder(commonESBPath + "message-stores")
+ .getLocation().toFile();
+ File destFile = new File(baseDir, qName + ".xml");
+ FileUtils.createFile(destFile, element.toString());
+ MavenProject mavenProject = MavenUtils
+ .getMavenProject(pomfile);
+ addPluginEntry(mavenProject, "org.wso2.maven",
+ "wso2-esb-messagestore-plugin",
+ MavenConstants.WSO2_ESB_MESSAGE_STORE_PLUGIN_VERSION, "message-store");
+ MavenUtils.saveMavenProject(mavenProject, pomfile);
+ fileList.put(destFile, localName);
+ createArtifactMetaDataEntry(qName, "synapse/message-store", baseDir,
+ groupId + ".message-store",project);
+ } else if (localName.equalsIgnoreCase("messageProcessor")) {
+ File baseDir = project.getFolder(commonESBPath + "message-processors")
+ .getLocation().toFile();
+ File destFile = new File(baseDir, qName + ".xml");
+ FileUtils.createFile(destFile, element.toString());
+ MavenProject mavenProject = MavenUtils
+ .getMavenProject(pomfile);
+ addPluginEntry(mavenProject, "org.wso2.maven",
+ "wso2-esb-messageprocessor-plugin",
+ MavenConstants.WSO2_ESB_MESSAGE_PROCESSOR_PLUGIN_VERSION, "message-processor");
+ MavenUtils.saveMavenProject(mavenProject, pomfile);
+ fileList.put(destFile, localName);
+ createArtifactMetaDataEntry(qName, "synapse/message-processors", baseDir,
+ groupId + ".message-processor",project);
}
}
}
}
public static void addPluginEntry(MavenProject mavenProject, String groupId, String artifactId, String version, String Id) {
List<Plugin> plugins = mavenProject.getBuild().getPlugins();
for (Plugin plg : plugins) {
if (plg.getGroupId().equalsIgnoreCase(groupId) && plg.getArtifactId().equalsIgnoreCase(artifactId) && plg.getVersion().equalsIgnoreCase(version) ) {
return;
}
}
Plugin plugin = MavenUtils.createPluginEntry(mavenProject, groupId, artifactId, version, true);
PluginExecution pluginExecution = new PluginExecution();
pluginExecution.addGoal("pom-gen");
pluginExecution.setPhase("process-resources");
pluginExecution.setId(Id);
Xpp3Dom configurationNode = MavenUtils.createMainConfigurationNode();
Xpp3Dom artifactLocationNode = MavenUtils.createXpp3Node(configurationNode, "artifactLocation");
artifactLocationNode.setValue(".");
Xpp3Dom typeListNode = MavenUtils.createXpp3Node(configurationNode, "typeList");
typeListNode.setValue("${artifact.types}");
pluginExecution.setConfiguration(configurationNode);
plugin.addExecution(pluginExecution);
Repository repo = new Repository();
repo.setUrl("http://maven.wso2.org/nexus/content/groups/wso2-public/");
repo.setId("wso2-nexus");
RepositoryPolicy releasePolicy=new RepositoryPolicy();
releasePolicy.setEnabled(true);
releasePolicy.setUpdatePolicy("daily");
releasePolicy.setChecksumPolicy("ignore");
repo.setReleases(releasePolicy);
if (!mavenProject.getRepositories().contains(repo)) {
mavenProject.getModel().addRepository(repo);
mavenProject.getModel().addPluginRepository(repo);
}
}
public static void createArtifactMetaDataEntry(String name, String type,
File baseDir, String groupId,IProject project) throws FactoryConfigurationError,
Exception {
ESBProjectArtifact esbProjectArtifact = new ESBProjectArtifact();
esbProjectArtifact.fromFile(project.getFile("artifact.xml")
.getLocation().toFile());
ESBArtifact artifact = new ESBArtifact();
artifact.setName(name);
artifact.setVersion("1.0.0");
artifact.setType(type);
artifact.setServerRole("EnterpriseServiceBus");
artifact.setGroupId(groupId);
artifact.setFile(FileUtils.getRelativePath(
project.getLocation().toFile(),
new File(baseDir, name + ".xml")).replaceAll(
Pattern.quote(File.separator), "/"));
esbProjectArtifact.addESBArtifact(artifact);
esbProjectArtifact.toFile();
}
public static void updatePom(IProject project) throws Exception {
File mavenProjectPomLocation = project.getFile("pom.xml").getLocation().toFile();
MavenProject mavenProject = MavenUtils.getMavenProject(mavenProjectPomLocation);
addPluginEntry(mavenProject, "org.wso2.maven","wso2-esb-synapse-plugin", MavenConstants.WSO2_ESB_SYNAPSE_VERSION,"synapse");
MavenUtils.saveMavenProject(mavenProject, mavenProjectPomLocation);
}
}
| true | true | public static void createESBArtifacts(List<OMElement> selectedElementsList,IProject project,File pomfile,Map<File,String> fileList,
String groupId) throws FactoryConfigurationError, Exception {
if (selectedElementsList != null) {
for (OMElement element : selectedElementsList) {
String localName = element.getLocalName();
String qName = element.getAttributeValue(new QName("name"));
if (("".equals(qName)) || (qName == null)) {
qName = element.getAttributeValue(new QName("key"));
if (("".equals(qName)) || (qName == null)) {
continue;
}
}
//esbProjectModel.setName(qName);
String commonESBPath = "src" + File.separator + "main"
+ File.separator + "synapse-config" + File.separator;
if (localName.equalsIgnoreCase("sequence")) {
File baseDir = project
.getFolder(commonESBPath + "sequences")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-sequence-plugin",
MavenConstants.WSO2_ESB_SEQUENCE_VERSION,
"sequence");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "sequence");
createArtifactMetaDataEntry(qName, "synapse/sequence",
baseDir, groupId + ".sequence",project);
} else if (localName.equalsIgnoreCase("endpoint")) {
File baseDir = project
.getFolder(commonESBPath + "endpoints")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-endpoint-plugin",
MavenConstants.WSO2_ESB_ENDPOINT_VERSION,
"endpoint");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "endpoint");
createArtifactMetaDataEntry(qName, "synapse/endpoint",
baseDir, groupId + ".endpoint",project);
} else if (localName.equalsIgnoreCase("proxy")) {
File baseDir = project
.getFolder(commonESBPath + "proxy-services")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-proxy-plugin",
MavenConstants.WSO2_ESB_PROXY_VERSION, "proxy");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "proxy");
createArtifactMetaDataEntry(qName, "synapse/proxy-service",
baseDir, groupId + ".proxy-service",project);
} else if (localName.equalsIgnoreCase("localEntry")) {
File baseDir = project
.getFolder(commonESBPath + "local-entries")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-localentry-plugin",
MavenConstants.WSO2_ESB_LOCAL_ENTRY_VERSION,
"localentry");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "localEntry");
createArtifactMetaDataEntry(qName, "synapse/local-entry",
baseDir, groupId + ".local-entry",project);
} else if (localName.equalsIgnoreCase("task")) {
File baseDir = project.getFolder(commonESBPath + "task")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-task-plugin",
MavenConstants.WSO2_ESB_TASK_VERSION, "task");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "task");
createArtifactMetaDataEntry(qName, "synapse/task", baseDir,
groupId + ".task",project);
} else if (localName.equalsIgnoreCase("api")) {
File baseDir = project.getFolder(commonESBPath + "api")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-api-plugin",
MavenConstants.WSO2_ESB_API_VERSION, "api");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "api");
createArtifactMetaDataEntry(qName, "synapse/api", baseDir,
groupId + ".api",project);
}
}
}
}
| public static void createESBArtifacts(List<OMElement> selectedElementsList,IProject project,File pomfile,Map<File,String> fileList,
String groupId) throws FactoryConfigurationError, Exception {
if (selectedElementsList != null) {
for (OMElement element : selectedElementsList) {
String localName = element.getLocalName();
String qName = element.getAttributeValue(new QName("name"));
if (("".equals(qName)) || (qName == null)) {
qName = element.getAttributeValue(new QName("key"));
if (("".equals(qName)) || (qName == null)) {
continue;
}
}
//esbProjectModel.setName(qName);
String commonESBPath = "src" + File.separator + "main"
+ File.separator + "synapse-config" + File.separator;
if (localName.equalsIgnoreCase("sequence")) {
File baseDir = project
.getFolder(commonESBPath + "sequences")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-sequence-plugin",
MavenConstants.WSO2_ESB_SEQUENCE_VERSION,
"sequence");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "sequence");
createArtifactMetaDataEntry(qName, "synapse/sequence",
baseDir, groupId + ".sequence",project);
} else if (localName.equalsIgnoreCase("endpoint")) {
File baseDir = project
.getFolder(commonESBPath + "endpoints")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-endpoint-plugin",
MavenConstants.WSO2_ESB_ENDPOINT_VERSION,
"endpoint");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "endpoint");
createArtifactMetaDataEntry(qName, "synapse/endpoint",
baseDir, groupId + ".endpoint",project);
} else if (localName.equalsIgnoreCase("proxy")) {
File baseDir = project
.getFolder(commonESBPath + "proxy-services")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-proxy-plugin",
MavenConstants.WSO2_ESB_PROXY_VERSION, "proxy");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "proxy");
createArtifactMetaDataEntry(qName, "synapse/proxy-service",
baseDir, groupId + ".proxy-service",project);
} else if (localName.equalsIgnoreCase("localEntry")) {
File baseDir = project
.getFolder(commonESBPath + "local-entries")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-localentry-plugin",
MavenConstants.WSO2_ESB_LOCAL_ENTRY_VERSION,
"localentry");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "localEntry");
createArtifactMetaDataEntry(qName, "synapse/local-entry",
baseDir, groupId + ".local-entry",project);
} else if (localName.equalsIgnoreCase("task")) {
File baseDir = project.getFolder(commonESBPath + "task")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-task-plugin",
MavenConstants.WSO2_ESB_TASK_VERSION, "task");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "task");
createArtifactMetaDataEntry(qName, "synapse/task", baseDir,
groupId + ".task",project);
} else if (localName.equalsIgnoreCase("api")) {
File baseDir = project.getFolder(commonESBPath + "api")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-api-plugin",
MavenConstants.WSO2_ESB_API_VERSION, "api");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, "api");
createArtifactMetaDataEntry(qName, "synapse/api", baseDir,
groupId + ".api",project);
} else if (localName.equalsIgnoreCase("messageStore")) {
File baseDir = project.getFolder(commonESBPath + "message-stores")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-messagestore-plugin",
MavenConstants.WSO2_ESB_MESSAGE_STORE_PLUGIN_VERSION, "message-store");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, localName);
createArtifactMetaDataEntry(qName, "synapse/message-store", baseDir,
groupId + ".message-store",project);
} else if (localName.equalsIgnoreCase("messageProcessor")) {
File baseDir = project.getFolder(commonESBPath + "message-processors")
.getLocation().toFile();
File destFile = new File(baseDir, qName + ".xml");
FileUtils.createFile(destFile, element.toString());
MavenProject mavenProject = MavenUtils
.getMavenProject(pomfile);
addPluginEntry(mavenProject, "org.wso2.maven",
"wso2-esb-messageprocessor-plugin",
MavenConstants.WSO2_ESB_MESSAGE_PROCESSOR_PLUGIN_VERSION, "message-processor");
MavenUtils.saveMavenProject(mavenProject, pomfile);
fileList.put(destFile, localName);
createArtifactMetaDataEntry(qName, "synapse/message-processors", baseDir,
groupId + ".message-processor",project);
}
}
}
}
|
diff --git a/test/Arrays.java b/test/Arrays.java
index e00bbf56..42e95806 100644
--- a/test/Arrays.java
+++ b/test/Arrays.java
@@ -1,98 +1,98 @@
public class Arrays {
private static void expect(boolean v) {
if (! v) throw new RuntimeException();
}
public static void main(String[] args) {
{ int[] array = new int[0];
Exception exception = null;
try {
int x = array[0];
} catch (ArrayIndexOutOfBoundsException e) {
exception = e;
}
expect(exception != null);
}
{ int[] array = new int[0];
Exception exception = null;
try {
int x = array[-1];
} catch (ArrayIndexOutOfBoundsException e) {
exception = e;
}
expect(exception != null);
}
{ int[] array = new int[3];
int i = 0;
array[i++] = 1;
array[i++] = 2;
array[i++] = 3;
expect(array[--i] == 3);
expect(array[--i] == 2);
expect(array[--i] == 1);
}
{ Object[][] array = new Object[1][1];
expect(array.length == 1);
expect(array[0].length == 1);
}
{ Object[][] array = new Object[2][3];
expect(array.length == 2);
expect(array[0].length == 3);
}
{ int j = 0;
byte[] decodeTable = new byte[256];
for (int i = 'A'; i <= 'Z'; ++i) decodeTable[i] = (byte) j++;
for (int i = 'a'; i <= 'z'; ++i) decodeTable[i] = (byte) j++;
for (int i = '0'; i <= '9'; ++i) decodeTable[i] = (byte) j++;
decodeTable['+'] = (byte) j++;
decodeTable['/'] = (byte) j++;
decodeTable['='] = 0;
expect(decodeTable['a'] != 0);
}
{ boolean p = true;
int[] array = new int[] { 1, 2 };
expect(array[0] == array[p ? 0 : 1]);
p = false;
expect(array[1] == array[p ? 0 : 1]);
}
{ int[] array = new int[1024];
array[1023] = -1;
expect(array[1023] == -1);
expect(array[1022] == 0);
}
{ Integer[] array = (Integer[])
java.lang.reflect.Array.newInstance(Integer.class, 1);
array[0] = Integer.valueOf(42);
expect(array[0].intValue() == 42);
}
{ Object[] a = new Object[3];
Object[] b = new Object[3];
expect(java.util.Arrays.equals(a, b));
a[0] = new Object();
expect(! java.util.Arrays.equals(a, b));
expect(! java.util.Arrays.equals(b, new Object[4]));
expect(! java.util.Arrays.equals(a, null));
expect(! java.util.Arrays.equals(null, b));
- expect(java.util.Arrays.equals(null, null));
+ expect(java.util.Arrays.equals((Object[])null, (Object[])null));
b[0] = a[0];
expect(java.util.Arrays.equals(a, b));
java.util.Arrays.hashCode(a);
- java.util.Arrays.hashCode(null);
+ java.util.Arrays.hashCode((Object[])null);
}
}
}
| false | true | public static void main(String[] args) {
{ int[] array = new int[0];
Exception exception = null;
try {
int x = array[0];
} catch (ArrayIndexOutOfBoundsException e) {
exception = e;
}
expect(exception != null);
}
{ int[] array = new int[0];
Exception exception = null;
try {
int x = array[-1];
} catch (ArrayIndexOutOfBoundsException e) {
exception = e;
}
expect(exception != null);
}
{ int[] array = new int[3];
int i = 0;
array[i++] = 1;
array[i++] = 2;
array[i++] = 3;
expect(array[--i] == 3);
expect(array[--i] == 2);
expect(array[--i] == 1);
}
{ Object[][] array = new Object[1][1];
expect(array.length == 1);
expect(array[0].length == 1);
}
{ Object[][] array = new Object[2][3];
expect(array.length == 2);
expect(array[0].length == 3);
}
{ int j = 0;
byte[] decodeTable = new byte[256];
for (int i = 'A'; i <= 'Z'; ++i) decodeTable[i] = (byte) j++;
for (int i = 'a'; i <= 'z'; ++i) decodeTable[i] = (byte) j++;
for (int i = '0'; i <= '9'; ++i) decodeTable[i] = (byte) j++;
decodeTable['+'] = (byte) j++;
decodeTable['/'] = (byte) j++;
decodeTable['='] = 0;
expect(decodeTable['a'] != 0);
}
{ boolean p = true;
int[] array = new int[] { 1, 2 };
expect(array[0] == array[p ? 0 : 1]);
p = false;
expect(array[1] == array[p ? 0 : 1]);
}
{ int[] array = new int[1024];
array[1023] = -1;
expect(array[1023] == -1);
expect(array[1022] == 0);
}
{ Integer[] array = (Integer[])
java.lang.reflect.Array.newInstance(Integer.class, 1);
array[0] = Integer.valueOf(42);
expect(array[0].intValue() == 42);
}
{ Object[] a = new Object[3];
Object[] b = new Object[3];
expect(java.util.Arrays.equals(a, b));
a[0] = new Object();
expect(! java.util.Arrays.equals(a, b));
expect(! java.util.Arrays.equals(b, new Object[4]));
expect(! java.util.Arrays.equals(a, null));
expect(! java.util.Arrays.equals(null, b));
expect(java.util.Arrays.equals(null, null));
b[0] = a[0];
expect(java.util.Arrays.equals(a, b));
java.util.Arrays.hashCode(a);
java.util.Arrays.hashCode(null);
}
}
| public static void main(String[] args) {
{ int[] array = new int[0];
Exception exception = null;
try {
int x = array[0];
} catch (ArrayIndexOutOfBoundsException e) {
exception = e;
}
expect(exception != null);
}
{ int[] array = new int[0];
Exception exception = null;
try {
int x = array[-1];
} catch (ArrayIndexOutOfBoundsException e) {
exception = e;
}
expect(exception != null);
}
{ int[] array = new int[3];
int i = 0;
array[i++] = 1;
array[i++] = 2;
array[i++] = 3;
expect(array[--i] == 3);
expect(array[--i] == 2);
expect(array[--i] == 1);
}
{ Object[][] array = new Object[1][1];
expect(array.length == 1);
expect(array[0].length == 1);
}
{ Object[][] array = new Object[2][3];
expect(array.length == 2);
expect(array[0].length == 3);
}
{ int j = 0;
byte[] decodeTable = new byte[256];
for (int i = 'A'; i <= 'Z'; ++i) decodeTable[i] = (byte) j++;
for (int i = 'a'; i <= 'z'; ++i) decodeTable[i] = (byte) j++;
for (int i = '0'; i <= '9'; ++i) decodeTable[i] = (byte) j++;
decodeTable['+'] = (byte) j++;
decodeTable['/'] = (byte) j++;
decodeTable['='] = 0;
expect(decodeTable['a'] != 0);
}
{ boolean p = true;
int[] array = new int[] { 1, 2 };
expect(array[0] == array[p ? 0 : 1]);
p = false;
expect(array[1] == array[p ? 0 : 1]);
}
{ int[] array = new int[1024];
array[1023] = -1;
expect(array[1023] == -1);
expect(array[1022] == 0);
}
{ Integer[] array = (Integer[])
java.lang.reflect.Array.newInstance(Integer.class, 1);
array[0] = Integer.valueOf(42);
expect(array[0].intValue() == 42);
}
{ Object[] a = new Object[3];
Object[] b = new Object[3];
expect(java.util.Arrays.equals(a, b));
a[0] = new Object();
expect(! java.util.Arrays.equals(a, b));
expect(! java.util.Arrays.equals(b, new Object[4]));
expect(! java.util.Arrays.equals(a, null));
expect(! java.util.Arrays.equals(null, b));
expect(java.util.Arrays.equals((Object[])null, (Object[])null));
b[0] = a[0];
expect(java.util.Arrays.equals(a, b));
java.util.Arrays.hashCode(a);
java.util.Arrays.hashCode((Object[])null);
}
}
|
diff --git a/src/main/java/hudson/plugins/jira/JiraIssueUpdater.java b/src/main/java/hudson/plugins/jira/JiraIssueUpdater.java
index 038e484..f9d5de3 100644
--- a/src/main/java/hudson/plugins/jira/JiraIssueUpdater.java
+++ b/src/main/java/hudson/plugins/jira/JiraIssueUpdater.java
@@ -1,140 +1,140 @@
package hudson.plugins.jira;
import hudson.Launcher;
import hudson.model.AbstractBuild;
import hudson.model.AbstractBuild.DependencyChange;
import hudson.model.Build;
import hudson.model.BuildListener;
import hudson.model.Descriptor;
import hudson.model.Hudson;
import hudson.model.Result;
import hudson.scm.ChangeLogSet.Entry;
import hudson.tasks.Publisher;
import org.kohsuke.stapler.StaplerRequest;
import javax.xml.rpc.ServiceException;
import java.io.IOException;
import java.io.PrintStream;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Parses build changelog for JIRA issue IDs and then
* updates JIRA issues accordingly.
*
* @author Kohsuke Kawaguchi
*/
public class JiraIssueUpdater extends Publisher {
public JiraIssueUpdater() {
}
/**
* Regexp pattern that identifies JIRA issue token.
*
* <p>
* At least two upper alphabetic (no numbers allowed.)
*/
public static final Pattern ISSUE_PATTERN = Pattern.compile("\\b[A-Z]([A-Z]+)-[1-9][0-9]*\\b");
public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
PrintStream logger = listener.getLogger();
JiraSite site = JiraSite.get(build.getProject());
if(site==null) {
logger.println("No jira site is configured for this project. This must be a project configuration error");
build.setResult(Result.FAILURE);
return true;
}
String rootUrl = Hudson.getInstance().getRootUrl();
if(rootUrl==null) {
logger.println("Hudson URL is not configured yet. Go to system configuration to set this value");
build.setResult(Result.FAILURE);
return true;
}
Set<String> ids = findIssueIdsRecursive(build);
if(ids.isEmpty())
return true; // nothing found here.
List<JiraIssue> issues = new ArrayList<JiraIssue>();
try {
JiraSession session = site.createSession();
if(session==null) {
logger.println("The system configuration does not allow remote JIRA access");
build.setResult(Result.FAILURE);
return true;
}
for (String id : ids) {
logger.println("Updating "+id);
session.addComment(id,
MessageFormat.format(
site.supportsWikiStyleComment?
"Integrated in !{0}nocacheImages/16x16/{3}.gif! [{2}|{0}{1}]":
"Integrated in {2} (See {0}{1})",
- rootUrl, build.getUrl(), build, build.getIconColor().noAnime()));
+ rootUrl, build.getUrl(), build, build.getResult().color));
issues.add(new JiraIssue(session.getIssue(id)));
}
} catch (ServiceException e) {
e.printStackTrace(listener.error("Failed to connect to JIRA"));
}
build.getActions().add(new JiraBuildAction(build,issues));
return true;
}
private Set<String> findIssueIdsRecursive(Build build) {
Set<String> ids = new HashSet<String>();
findIssues(build,ids);
// check for issues fixed in dependencies
for( DependencyChange depc : build.getDependencyChanges(build.getPreviousBuild()).values())
for(AbstractBuild b : depc.getBuilds())
findIssues(b,ids);
return ids;
}
private void findIssues(AbstractBuild<?,?> build, Set<String> ids) {
for (Iterator<? extends Entry> itr = build.getChangeSet().iterator(); itr.hasNext();) {
Entry change = itr.next();
Matcher m = ISSUE_PATTERN.matcher(change.getMsg());
while(m.find())
ids.add(m.group());
}
}
public DescriptorImpl getDescriptor() {
return DESCRIPTOR;
}
public static final DescriptorImpl DESCRIPTOR = new DescriptorImpl();
public static final class DescriptorImpl extends Descriptor<Publisher> {
private DescriptorImpl() {
super(JiraIssueUpdater.class);
}
public String getDisplayName() {
return "Updated relevant JIRA issues";
}
public String getHelpFile() {
return "/plugin/jira/help.html";
}
public Publisher newInstance(StaplerRequest req) {
return new JiraIssueUpdater();
}
}
}
| true | true | public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
PrintStream logger = listener.getLogger();
JiraSite site = JiraSite.get(build.getProject());
if(site==null) {
logger.println("No jira site is configured for this project. This must be a project configuration error");
build.setResult(Result.FAILURE);
return true;
}
String rootUrl = Hudson.getInstance().getRootUrl();
if(rootUrl==null) {
logger.println("Hudson URL is not configured yet. Go to system configuration to set this value");
build.setResult(Result.FAILURE);
return true;
}
Set<String> ids = findIssueIdsRecursive(build);
if(ids.isEmpty())
return true; // nothing found here.
List<JiraIssue> issues = new ArrayList<JiraIssue>();
try {
JiraSession session = site.createSession();
if(session==null) {
logger.println("The system configuration does not allow remote JIRA access");
build.setResult(Result.FAILURE);
return true;
}
for (String id : ids) {
logger.println("Updating "+id);
session.addComment(id,
MessageFormat.format(
site.supportsWikiStyleComment?
"Integrated in !{0}nocacheImages/16x16/{3}.gif! [{2}|{0}{1}]":
"Integrated in {2} (See {0}{1})",
rootUrl, build.getUrl(), build, build.getIconColor().noAnime()));
issues.add(new JiraIssue(session.getIssue(id)));
}
} catch (ServiceException e) {
e.printStackTrace(listener.error("Failed to connect to JIRA"));
}
build.getActions().add(new JiraBuildAction(build,issues));
return true;
}
| public boolean perform(Build build, Launcher launcher, BuildListener listener) throws InterruptedException, IOException {
PrintStream logger = listener.getLogger();
JiraSite site = JiraSite.get(build.getProject());
if(site==null) {
logger.println("No jira site is configured for this project. This must be a project configuration error");
build.setResult(Result.FAILURE);
return true;
}
String rootUrl = Hudson.getInstance().getRootUrl();
if(rootUrl==null) {
logger.println("Hudson URL is not configured yet. Go to system configuration to set this value");
build.setResult(Result.FAILURE);
return true;
}
Set<String> ids = findIssueIdsRecursive(build);
if(ids.isEmpty())
return true; // nothing found here.
List<JiraIssue> issues = new ArrayList<JiraIssue>();
try {
JiraSession session = site.createSession();
if(session==null) {
logger.println("The system configuration does not allow remote JIRA access");
build.setResult(Result.FAILURE);
return true;
}
for (String id : ids) {
logger.println("Updating "+id);
session.addComment(id,
MessageFormat.format(
site.supportsWikiStyleComment?
"Integrated in !{0}nocacheImages/16x16/{3}.gif! [{2}|{0}{1}]":
"Integrated in {2} (See {0}{1})",
rootUrl, build.getUrl(), build, build.getResult().color));
issues.add(new JiraIssue(session.getIssue(id)));
}
} catch (ServiceException e) {
e.printStackTrace(listener.error("Failed to connect to JIRA"));
}
build.getActions().add(new JiraBuildAction(build,issues));
return true;
}
|
diff --git a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/perf/AllTests.java b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/perf/AllTests.java
index 83371f839..6d914f8bb 100644
--- a/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/perf/AllTests.java
+++ b/tests/org.eclipse.core.tests.resources/src/org/eclipse/core/tests/resources/perf/AllTests.java
@@ -1,32 +1,33 @@
/*******************************************************************************
* Copyright (c) 2004, 2005 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* Contributors:
* IBM Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.core.tests.resources.perf;
import junit.framework.Test;
import junit.framework.TestSuite;
/**
* @since 3.1
*/
public class AllTests extends TestSuite {
public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(BenchWorkspace.suite());
suite.addTest(BenchMiscWorkspace.suite());
suite.addTest(MarkerPerformanceTest.suite());
suite.addTest(LocalHistoryPerformanceTest.suite());
suite.addTest(WorkspacePerformanceTest.suite());
suite.addTest(PropertyManagerPerformanceTest.suite());
- suite.addTest(ContentDescriptionPerformanceTest.suite());
+ // these tests are flawed - see bug 57137
+ // suite.addTest(ContentDescriptionPerformanceTest.suite());
return suite;
}
}
| true | true | public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(BenchWorkspace.suite());
suite.addTest(BenchMiscWorkspace.suite());
suite.addTest(MarkerPerformanceTest.suite());
suite.addTest(LocalHistoryPerformanceTest.suite());
suite.addTest(WorkspacePerformanceTest.suite());
suite.addTest(PropertyManagerPerformanceTest.suite());
suite.addTest(ContentDescriptionPerformanceTest.suite());
return suite;
}
| public static Test suite() {
TestSuite suite = new TestSuite(AllTests.class.getName());
suite.addTest(BenchWorkspace.suite());
suite.addTest(BenchMiscWorkspace.suite());
suite.addTest(MarkerPerformanceTest.suite());
suite.addTest(LocalHistoryPerformanceTest.suite());
suite.addTest(WorkspacePerformanceTest.suite());
suite.addTest(PropertyManagerPerformanceTest.suite());
// these tests are flawed - see bug 57137
// suite.addTest(ContentDescriptionPerformanceTest.suite());
return suite;
}
|
diff --git a/src/com/danielmessias/particleplayground/GoffParticle.java b/src/com/danielmessias/particleplayground/GoffParticle.java
index e081b20..de82112 100644
--- a/src/com/danielmessias/particleplayground/GoffParticle.java
+++ b/src/com/danielmessias/particleplayground/GoffParticle.java
@@ -1,64 +1,64 @@
package com.danielmessias.particleplayground;
import org.lwjgl.input.Mouse;
import org.newdawn.slick.Color;
public class GoffParticle extends Particle {
int velocityX;
double velocityY;
float dx = 0;
int bounces = 0;
final int maxBounces = 10;
public GoffParticle(int xPos, int yPos) {
super(xPos, yPos);
dx += (Mouse.getDX()/2);
}
public void update() {
super.update();
prevx = x;
prevy = y;
y+=velocityY;
if(y < ParticleWorld.winHeight && velocityY <= 60) {
velocityY++;
}
if(y >= ParticleWorld.winHeight) {
velocityY = -0.8 * velocityY;
- dx = (float) (-0.9*dx);
+ dx = (float) (0.9*dx);
bounces++;
}
dx = (float) (dx * 0.95);
x+=dx;
if(x <= 0 || x >= ParticleWorld.winWidth) {
dx = (float) (-0.9*dx);
velocityY = -0.98 * velocityY;
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/2) {
setColor(new Color(0,255,0));
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/4 && ParticleWorld.winHeight - y < ParticleWorld.winHeight/2) {
setColor(new Color(255,0,0));
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/8 && ParticleWorld.winHeight - y < ParticleWorld.winHeight/4) {
setColor(new Color(0,0,255));
}
if(bounces > maxBounces) {
killParticle();
}
}
}
| true | true | public void update() {
super.update();
prevx = x;
prevy = y;
y+=velocityY;
if(y < ParticleWorld.winHeight && velocityY <= 60) {
velocityY++;
}
if(y >= ParticleWorld.winHeight) {
velocityY = -0.8 * velocityY;
dx = (float) (-0.9*dx);
bounces++;
}
dx = (float) (dx * 0.95);
x+=dx;
if(x <= 0 || x >= ParticleWorld.winWidth) {
dx = (float) (-0.9*dx);
velocityY = -0.98 * velocityY;
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/2) {
setColor(new Color(0,255,0));
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/4 && ParticleWorld.winHeight - y < ParticleWorld.winHeight/2) {
setColor(new Color(255,0,0));
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/8 && ParticleWorld.winHeight - y < ParticleWorld.winHeight/4) {
setColor(new Color(0,0,255));
}
if(bounces > maxBounces) {
killParticle();
}
}
| public void update() {
super.update();
prevx = x;
prevy = y;
y+=velocityY;
if(y < ParticleWorld.winHeight && velocityY <= 60) {
velocityY++;
}
if(y >= ParticleWorld.winHeight) {
velocityY = -0.8 * velocityY;
dx = (float) (0.9*dx);
bounces++;
}
dx = (float) (dx * 0.95);
x+=dx;
if(x <= 0 || x >= ParticleWorld.winWidth) {
dx = (float) (-0.9*dx);
velocityY = -0.98 * velocityY;
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/2) {
setColor(new Color(0,255,0));
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/4 && ParticleWorld.winHeight - y < ParticleWorld.winHeight/2) {
setColor(new Color(255,0,0));
}
if(ParticleWorld.winHeight - y >= ParticleWorld.winHeight/8 && ParticleWorld.winHeight - y < ParticleWorld.winHeight/4) {
setColor(new Color(0,0,255));
}
if(bounces > maxBounces) {
killParticle();
}
}
|
diff --git a/src/com/infomancers/collections/yield/asm/delayed/DelayedMethodVisitor.java b/src/com/infomancers/collections/yield/asm/delayed/DelayedMethodVisitor.java
index 877b8da..71be71c 100644
--- a/src/com/infomancers/collections/yield/asm/delayed/DelayedMethodVisitor.java
+++ b/src/com/infomancers/collections/yield/asm/delayed/DelayedMethodVisitor.java
@@ -1,121 +1,121 @@
package com.infomancers.collections.yield.asm.delayed;
import org.objectweb.asm.MethodAdapter;
import org.objectweb.asm.MethodVisitor;
import java.util.HashSet;
import java.util.LinkedList;
import java.util.Queue;
import java.util.Stack;
/**
* Copyright (c) 2007, Aviad Ben Dov
* <p/>
* All rights reserved.
* <p/>
* Redistribution and use in source and binary forms, with or without modification,
* are permitted provided that the following conditions are met:
* <p/>
* 1. Redistributions of source code must retain the above copyright notice, this list
* of conditions and the following disclaimer.
* 2. Redistributions in binary form must reproduce the above copyright notice, this
* list of conditions and the following disclaimer in the documentation and/or other
* materials provided with the distribution.
* 3. Neither the name of Infomancers, Ltd. nor the names of its contributors may be
* used to endorse or promote products derived from this software without specific
* prior written permission.
* <p/>
* THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
* "AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
* LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
* A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR
* CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
* EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO,
* PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR
* PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
* LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING
* NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
* SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
public class DelayedMethodVisitor extends MethodAdapter {
private static class MiniFrame {
public Queue<DelayedInstructionEmitter> workQueue = new LinkedList<DelayedInstructionEmitter>();
int stackSize = 0;
}
private static HashSet<Integer> poppingCodes = new HashSet<Integer>();
private static HashSet<Integer> pushingCodes = new HashSet<Integer>();
private Stack<MiniFrame> miniFrames = new Stack<MiniFrame>();
private MiniFrame currentMiniFrame = null;
/**
* Constructs a new {@link org.objectweb.asm.MethodAdapter} object.
*
* @param mv the code visitor to which this adapter must delegate calls.
*/
public DelayedMethodVisitor(MethodVisitor mv) {
super(mv);
}
@Override
public void visitMethodInsn(final int opcode, final String owner, final String name, final String desc) {
super.visitMethodInsn(opcode, owner, name, desc);
delayInsn(opcode, DelayedInstruction.METHOD.createEmitter(opcode, owner, name, desc));
}
@Override
public void visitFieldInsn(final int opcode, final String owner, final String name, final String desc) {
super.visitFieldInsn(opcode, owner, name, desc);
delayInsn(opcode, DelayedInstruction.FIELD.createEmitter(opcode, owner, name, desc));
}
protected final void startMiniFrame() {
if (currentMiniFrame != null) {
miniFrames.push(currentMiniFrame);
}
currentMiniFrame = new MiniFrame();
}
private void delayInsn(int opcode, DelayedInstructionEmitter emitter) {
currentMiniFrame.workQueue.offer(emitter);
if (poppingCodes.contains(opcode)) {
if (currentMiniFrame.stackSize == 0) {
throw new IllegalStateException("Popping from stack when the stack is empty? " +
"Probably missing popping/pushing instruction");
}
currentMiniFrame.stackSize--;
- } else {
+ } else if (pushingCodes.contains(opcode)) {
currentMiniFrame.stackSize++;
}
}
protected final void emit(MethodVisitor mv, int count) {
if (count <= 0) {
throw new IllegalArgumentException("count <= 0");
}
while (count-- > 0) {
currentMiniFrame.workQueue.poll().emit(mv);
}
}
protected final void emitAll(MethodVisitor mv) {
emit(mv, currentMiniFrame.workQueue.size());
}
protected final void endMiniFrame() {
if (currentMiniFrame.stackSize > 0) {
throw new IllegalStateException("Ending mini-frame when stack still has values!");
}
currentMiniFrame = miniFrames.isEmpty() ? null : miniFrames.pop();
}
}
| true | true | private void delayInsn(int opcode, DelayedInstructionEmitter emitter) {
currentMiniFrame.workQueue.offer(emitter);
if (poppingCodes.contains(opcode)) {
if (currentMiniFrame.stackSize == 0) {
throw new IllegalStateException("Popping from stack when the stack is empty? " +
"Probably missing popping/pushing instruction");
}
currentMiniFrame.stackSize--;
} else {
currentMiniFrame.stackSize++;
}
}
| private void delayInsn(int opcode, DelayedInstructionEmitter emitter) {
currentMiniFrame.workQueue.offer(emitter);
if (poppingCodes.contains(opcode)) {
if (currentMiniFrame.stackSize == 0) {
throw new IllegalStateException("Popping from stack when the stack is empty? " +
"Probably missing popping/pushing instruction");
}
currentMiniFrame.stackSize--;
} else if (pushingCodes.contains(opcode)) {
currentMiniFrame.stackSize++;
}
}
|
diff --git a/src/main/java/com/in6k/twitter/LoginPageServlet.java b/src/main/java/com/in6k/twitter/LoginPageServlet.java
index 31627ad..f754754 100644
--- a/src/main/java/com/in6k/twitter/LoginPageServlet.java
+++ b/src/main/java/com/in6k/twitter/LoginPageServlet.java
@@ -1,31 +1,31 @@
package com.in6k.twitter;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.sql.SQLException;
public class LoginPageServlet extends HttpServlet {
@Override
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("password");
if (AccountManager.isValid(login, password)) {
request.getSession().setAttribute("authorized", true);
request.getSession().setAttribute("login", login);
request.getRequestDispatcher("home-page.jsp").include(request, response);
return;
}
try {
ConsoleMessagePrinter.print(MessageManager.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
- request.getRequestDispatcher("/login.jsp").include(request, response);
+ request.getRequestDispatcher("WEB-INF/pages/login-form-error.jsp").include(request, response);
}
}
| true | true | protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("password");
if (AccountManager.isValid(login, password)) {
request.getSession().setAttribute("authorized", true);
request.getSession().setAttribute("login", login);
request.getRequestDispatcher("home-page.jsp").include(request, response);
return;
}
try {
ConsoleMessagePrinter.print(MessageManager.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("/login.jsp").include(request, response);
}
| protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
String login = request.getParameter("login");
String password = request.getParameter("password");
if (AccountManager.isValid(login, password)) {
request.getSession().setAttribute("authorized", true);
request.getSession().setAttribute("login", login);
request.getRequestDispatcher("home-page.jsp").include(request, response);
return;
}
try {
ConsoleMessagePrinter.print(MessageManager.getMessage());
} catch (Exception e) {
e.printStackTrace();
}
request.getRequestDispatcher("WEB-INF/pages/login-form-error.jsp").include(request, response);
}
|
diff --git a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
index 1d6a2ce4..086eace3 100644
--- a/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
+++ b/src/main/java/com/jayway/maven/plugins/android/phase04processclasses/ProguardMojo.java
@@ -1,743 +1,743 @@
package com.jayway.maven.plugins.android.phase04processclasses;
import com.jayway.maven.plugins.android.AbstractAndroidMojo;
import com.jayway.maven.plugins.android.CommandExecutor;
import com.jayway.maven.plugins.android.ExecutionException;
import com.jayway.maven.plugins.android.config.ConfigHandler;
import com.jayway.maven.plugins.android.config.ConfigPojo;
import com.jayway.maven.plugins.android.config.PullParameter;
import com.jayway.maven.plugins.android.configuration.Proguard;
import org.apache.commons.lang.StringUtils;
import org.apache.maven.RepositoryUtils;
import org.apache.maven.artifact.Artifact;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.plugin.MojoFailureException;
import org.eclipse.aether.artifact.DefaultArtifact;
import org.eclipse.aether.util.artifact.JavaScopes;
import java.io.File;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.HashSet;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
/**
* Processes both application and dependency classes using the ProGuard byte code obfuscator,
* minimzer, and optimizer. For more information, see https://proguard.sourceforge.net.
*
* @author Jonson
* @author Matthias Kaeppler
* @author Manfred Moser
* @author Michal Harakal
* @goal proguard
* @phase process-classes
* @requiresDependencyResolution compile
*/
public class ProguardMojo extends AbstractAndroidMojo
{
/**
* <p>
* ProGuard configuration. ProGuard is disabled by default. Set the skip parameter to false to activate proguard.
* A complete configuartion can include any of the following:
* </p>
* <p/>
* <pre>
* <proguard>
* <skip>true|false</skip>
* <config>proguard.cfg</config>
* <configs>
* <config>${env.ANDROID_HOME}/tools/proguard/proguard-android.txt</config>
* </configs>
* <proguardJarPath>someAbsolutePathToProguardJar</proguardJarPath>
* <filterMavenDescriptor>true|false</filterMavenDescriptor>
* <filterManifest>true|false</filterManifest>
* <jvmArguments>
* <jvmArgument>-Xms256m</jvmArgument>
* <jvmArgument>-Xmx512m</jvmArgument>
* </jvmArguments>
* </proguard>
* </pre>
* <p>
* A good practice is to create a release profile in your POM, in which you enable ProGuard.
* ProGuard should be disabled for development builds, since it obfuscates class and field
* names, and it may interfere with test projects that rely on your application classes.
* All parameters can be overridden in profiles or the the proguard* properties. Default values apply and are
* documented with these properties.
* </p>
*
* @parameter
*/
@ConfigPojo
protected Proguard proguard;
/**
* Whether ProGuard is enabled or not. Defaults to true.
*
* @parameter expression="${android.proguard.skip}"
* @optional
*/
private Boolean proguardSkip;
@PullParameter( defaultValue = "true" )
private Boolean parsedSkip;
/**
* Path to the ProGuard configuration file (relative to project root). Defaults to "proguard.cfg"
*
* @parameter expression="${android.proguard.config}"
* @optional
*/
private String proguardConfig;
@PullParameter( defaultValue = "proguard.cfg" )
private String parsedConfig;
/**
* Additional ProGuard configuration files (relative to project root).
*
* @parameter expression="${android.proguard.configs}"
* @optional
*/
private String[] proguardConfigs;
@PullParameter( defaultValueGetterMethod = "getDefaultProguardConfigs" )
private String[] parsedConfigs;
/**
* Additional ProGuard options
*
* @parameter expression="${android.proguard.options}"
* @optional
*/
private String[] proguardOptions;
@PullParameter( defaultValueGetterMethod = "getDefaultProguardOptions" )
private String[] parsedOptions;
/**
* Path to the proguard jar and therefore version of proguard to be used. By default this will load the jar from
* the Android SDK install. Overriding it with an absolute path allows you to use a newer or custom proguard
* version..
* <p/>
* You can also reference an external Proguard version as a plugin dependency like this:
* <pre>
* <plugin>
* <groupId>com.jayway.maven.plugins.android.generation2</groupId>
* <artifactId>android-maven-plugin</artifactId>
* <dependencies>
* <dependency>
* <groupId>net.sf.proguard</groupId>
* <artifactId>proguard-base</artifactId>
* <version>4.7</version>
* </dependency>
* </dependencies>
* </pre>
* <p/>
* which will download and use Proguard 4.7 as deployed to the Central Repository.
*
* @parameter expression="${android.proguard.proguardJarPath}
* @optional
*/
private String proguardProguardJarPath;
@PullParameter( defaultValueGetterMethod = "getProguardJarPath" )
private String parsedProguardJarPath;
/**
* Path relative to the project's build directory (target) where proguard puts folowing files:
* <p/>
* <ul>
* <li>dump.txt</li>
* <li>seeds.txt</li>
* <li>usage.txt</li>
* <li>mapping.txt</li>
* </ul>
* <p/>
* You can define the directory like this:
* <pre>
* <proguard>
* <skip>false</skip>
* <config>proguard.cfg</config>
* <outputDirectory>my_proguard</outputDirectory>
* </proguard>
* </pre>
* <p/>
* Output directory is defined relatively so it could be also outside of the target directory.
* <p/>
*
* @parameter expression="${android.proguard.outputDirectory}" default-value="proguard"
* @optional
*/
private String outputDirectory;
/**
* @parameter expression="${android.proguard.obfuscatedJar}"
* default-value="${project.build.directory}/${project.build.finalName}_obfuscated.jar"
*/
private String obfuscatedJar;
@PullParameter( defaultValue = "proguard" )
private String parsedOutputDirectory;
@PullParameter
private String parsedObfuscatedJar;
/**
* Extra JVM Arguments. Using these you can e.g. increase memory for the jvm running the build.
* Defaults to "-Xmx512M".
*
* @parameter expression="${android.proguard.jvmArguments}"
* @optional
*/
private String[] proguardJvmArguments;
@PullParameter( defaultValueGetterMethod = "getDefaultJvmArguments" )
private String[] parsedJvmArguments;
/**
* If set to true will add a filter to remove META-INF/maven/* files. Defaults to false.
*
* @parameter expression="${android.proguard.filterMavenDescriptor}"
* @optional
*/
private Boolean proguardFilterMavenDescriptor;
@PullParameter( defaultValue = "true" )
private Boolean parsedFilterMavenDescriptor;
/**
* If set to true will add a filter to remove META-INF/MANIFEST.MF files. Defaults to false.
*
* @parameter expression="${android.proguard.filterManifest}"
* @optional
*/
private Boolean proguardFilterManifest;
@PullParameter( defaultValue = "true" )
private Boolean parsedFilterManifest;
/**
* If set to true JDK jars will be included as library jars and corresponding filters
* will be applied to android.jar. Defaults to true.
* @parameter expression="${android.proguard.includeJdkLibs}"
*/
private Boolean includeJdkLibs;
@PullParameter( defaultValue = "true" )
private Boolean parsedIncludeJdkLibs;
/**
* If set to true the mapping.txt file will be attached as artifact of type <code>map</code>
* @parameter expression="${android.proguard.attachMap}"
*/
private Boolean attachMap;
@PullParameter( defaultValue = "false" )
private Boolean parsedAttachMap;
/**
* The plugin dependencies.
*
* @parameter expression="${plugin.artifacts}"
* @required
* @readonly
*/
protected List<Artifact> pluginDependencies;
private static final Collection<String> ANDROID_LIBRARY_EXCLUDED_FILTER = Arrays
.asList( "org/xml/**", "org/w3c/**", "java/**", "javax/**" );
private static final Collection<String> MAVEN_DESCRIPTOR = Arrays.asList( "META-INF/maven/**" );
private static final Collection<String> META_INF_MANIFEST = Arrays.asList( "META-INF/MANIFEST.MF" );
/**
* For Proguard is required only jar type dependencies, all other like .so or .apklib can be skipped.
*/
private static final String USED_DEPENDENCY_TYPE = "jar";
private Collection<String> globalInJarExcludes = new HashSet<String>();
private List<Artifact> artifactBlacklist = new LinkedList<Artifact>();
private List<Artifact> artifactsToShift = new LinkedList<Artifact>();
private List<ProGuardInput> inJars = new LinkedList<ProguardMojo.ProGuardInput>();
private List<ProGuardInput> libraryJars = new LinkedList<ProguardMojo.ProGuardInput>();
private File javaHomeDir;
private File javaLibDir;
private File altJavaLibDir;
private static class ProGuardInput
{
private String path;
private Collection<String> excludedFilter;
public ProGuardInput( String path, Collection<String> excludedFilter )
{
this.path = path;
this.excludedFilter = excludedFilter;
}
public String toCommandLine()
{
if ( excludedFilter != null && ! excludedFilter.isEmpty() )
{
StringBuilder sb = new StringBuilder( path );
sb.append( '(' );
for ( Iterator<String> it = excludedFilter.iterator(); it.hasNext(); )
{
sb.append( '!' ).append( it.next() );
if ( it.hasNext() )
{
sb.append( ',' );
}
}
sb.append( ')' );
return sb.toString();
}
else
{
return "\'" + path + "\'";
}
}
}
@Override
public void execute() throws MojoExecutionException, MojoFailureException
{
ConfigHandler configHandler = new ConfigHandler( this );
configHandler.parseConfiguration();
if ( ! parsedSkip )
{
// TODO: make the property name a constant sometime after switching to @Mojo
project.getProperties().setProperty( "android.proguard.obfuscatedJar", obfuscatedJar );
executeProguard();
}
}
private void executeProguard() throws MojoExecutionException
{
final File proguardDir = new File( project.getBuild().getDirectory(), parsedOutputDirectory );
if ( ! proguardDir.exists() && ! proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && ! proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
commands.add( "@" + parsedConfig );
for ( String config : parsedConfigs )
{
commands.add( "@" + config );
}
if ( proguardFile != null )
{
commands.add( "@" + proguardFile.getAbsolutePath() );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'" + obfuscatedJar + "'" );
commands.add( "-dump" );
commands.add( "'" + proguardDir + File.separator + "dump.txt'" );
commands.add( "-printseeds" );
commands.add( "'" + proguardDir + File.separator + "seeds.txt'" );
commands.add( "-printusage" );
commands.add( "'" + proguardDir + File.separator + "usage.txt'" );
- File mapFile = new File(proguardDir, "mapping.txt");
+ File mapFile = new File( proguardDir, "mapping.txt" );
commands.add( "-printmapping" );
commands.add( "'" + mapFile + "mapping.txt'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
- if( parsedAttachMap )
+ if ( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
/**
* Convert the jvm arguments in parsedJvmArguments as populated by the config in format as needed by the java
* command. Also preserve backwards compatibility in terms of dashes required or not..
*
* @param commands
*/
private void collectJvmArguments( List<String> commands )
{
if ( parsedJvmArguments != null )
{
for ( String jvmArgument : parsedJvmArguments )
{
// preserve backward compatibility allowing argument with or without dash (e.g.
// Xmx512m as well as -Xmx512m should work) (see
// http://code.google.com/p/maven-android-plugin/issues/detail?id=153)
if ( ! jvmArgument.startsWith( "-" ) )
{
jvmArgument = "-" + jvmArgument;
}
commands.add( jvmArgument );
}
}
}
private void collectInputFiles( List<String> commands )
{
// commons-logging breaks everything horribly, so we skip it from the program
// dependencies and declare it to be a library dependency instead
skipArtifact( "commons-logging", "commons-logging", true );
collectProgramInputFiles();
for ( ProGuardInput injar : inJars )
{
commands.add( "-injars" );
commands.add( injar.toCommandLine() );
}
collectLibraryInputFiles();
for ( ProGuardInput libraryjar : libraryJars )
{
commands.add( "-libraryjars" );
commands.add( libraryjar.toCommandLine() );
}
}
/**
* Figure out the full path to the current java executable.
*
* @return the full path to the current java executable.
*/
private static File getJavaExecutable()
{
final String javaHome = System.getProperty( "java.home" );
final String slash = File.separator;
return new File( javaHome + slash + "bin" + slash + "java" );
}
private void skipArtifact( String groupId, String artifactId, boolean shiftToLibraries )
{
artifactBlacklist.add( RepositoryUtils.toArtifact( new DefaultArtifact( groupId, artifactId, null, null ) ) );
if ( shiftToLibraries )
{
artifactsToShift
.add( RepositoryUtils.toArtifact( new DefaultArtifact( groupId, artifactId, null, null ) ) );
}
}
private boolean isBlacklistedArtifact( Artifact artifact )
{
for ( Artifact artifactToSkip : artifactBlacklist )
{
if ( artifactToSkip.getGroupId().equals( artifact.getGroupId() ) && artifactToSkip.getArtifactId()
.equals( artifact.getArtifactId() ) )
{
return true;
}
}
return false;
}
private boolean isShiftedArtifact( Artifact artifact )
{
for ( Artifact artifactToShift : artifactsToShift )
{
if ( artifactToShift.getGroupId().equals( artifact.getGroupId() ) && artifactToShift.getArtifactId()
.equals( artifact.getArtifactId() ) )
{
return true;
}
}
return false;
}
private void collectProgramInputFiles()
{
if ( parsedFilterManifest )
{
globalInJarExcludes.addAll( META_INF_MANIFEST );
}
if ( parsedFilterMavenDescriptor )
{
globalInJarExcludes.addAll( MAVEN_DESCRIPTOR );
}
// we first add the application's own class files
addInJar( project.getBuild().getOutputDirectory() );
// we then add all its dependencies (incl. transitive ones), unless they're blacklisted
for ( Artifact artifact : getAllRelevantDependencyArtifacts() )
{
if ( isBlacklistedArtifact( artifact ) || !USED_DEPENDENCY_TYPE.equals( artifact.getType() ) )
{
continue;
}
addInJar( artifact.getFile().getAbsolutePath(), globalInJarExcludes );
}
}
private void addInJar( String path, Collection<String> filterExpression )
{
inJars.add( new ProGuardInput( path, filterExpression ) );
}
private void addInJar( String path )
{
addInJar( path, null );
}
private void addLibraryJar( String path, Collection<String> filterExpression )
{
libraryJars.add( new ProGuardInput( path, filterExpression ) );
}
private void addLibraryJar( String path )
{
addLibraryJar( path, null );
}
private void collectLibraryInputFiles()
{
if ( parsedIncludeJdkLibs )
{
// we have to add the Java framework classes to the library JARs, since they are not
// distributed with the JAR on Central, and since we'll strip them out of the android.jar
// that is shipped with the SDK (since that is not a complete Java distribution)
File rtJar = getJVMLibrary( "rt.jar" );
if ( rtJar == null )
{
rtJar = getJVMLibrary( "classes.jar" );
}
if ( rtJar != null )
{
addLibraryJar( rtJar.getPath() );
}
// we also need to add the JAR containing e.g. javax.servlet
File jsseJar = getJVMLibrary( "jsse.jar" );
if ( jsseJar != null )
{
addLibraryJar( jsseJar.getPath() );
}
// and the javax.crypto stuff
File jceJar = getJVMLibrary( "jce.jar" );
if ( jceJar != null )
{
addLibraryJar( jceJar.getPath() );
}
}
// we treat any dependencies with provided scope as library JARs
for ( Artifact artifact : project.getArtifacts() )
{
if ( artifact.getScope().equals( JavaScopes.PROVIDED ) )
{
if ( artifact.getArtifactId().equals( "android" ) && parsedIncludeJdkLibs )
{
addLibraryJar( artifact.getFile().getAbsolutePath(), ANDROID_LIBRARY_EXCLUDED_FILTER );
}
else
{
addLibraryJar( artifact.getFile().getAbsolutePath() );
}
}
else
{
if ( isShiftedArtifact( artifact ) )
{
// this is a blacklisted artifact that should be processed as a library instead
addLibraryJar( artifact.getFile().getAbsolutePath() );
}
}
}
}
/**
* Get the path to the proguard jar.
*
* @return
* @throws MojoExecutionException
*/
private String getProguardJarPath() throws MojoExecutionException
{
String proguardJarPath = getProguardJarPathFromDependencies();
if ( StringUtils.isEmpty( proguardJarPath ) )
{
File proguardJarPathFile = new File( getAndroidSdk().getToolsPath(), "proguard/lib/proguard.jar" );
return proguardJarPathFile.getAbsolutePath();
}
return proguardJarPath;
}
private String getProguardJarPathFromDependencies() throws MojoExecutionException
{
Artifact proguardArtifact = null;
int proguardArtifactDistance = - 1;
for ( Artifact artifact : pluginDependencies )
{
getLog().debug( "pluginArtifact: " + artifact.getFile() );
if ( ( "proguard".equals( artifact.getArtifactId() ) ) || ( "proguard-base"
.equals( artifact.getArtifactId() ) ) )
{
int distance = artifact.getDependencyTrail().size();
getLog().debug( "proguard DependencyTrail: " + distance );
if ( proguardArtifactDistance == - 1 )
{
proguardArtifact = artifact;
proguardArtifactDistance = distance;
}
else
{
if ( distance < proguardArtifactDistance )
{
proguardArtifact = artifact;
proguardArtifactDistance = distance;
}
}
}
}
if ( proguardArtifact != null )
{
getLog().debug( "proguardArtifact: " + proguardArtifact.getFile() );
return proguardArtifact.getFile().getAbsoluteFile().toString();
}
else
{
return null;
}
}
/**
* Get the default JVM arguments for the proguard invocation.
*
* @return
* @see #parsedJvmArguments
*/
private String[] getDefaultJvmArguments()
{
return new String[]{ "-Xmx512M" };
}
/**
* Get the default ProGuard config files.
*
* @return
* @see #parsedConfigs
*/
private String[] getDefaultProguardConfigs()
{
return new String[0];
}
/**
* Get the default ProGuard options.
*
* @return
* @see #parsedOptions
*/
private String[] getDefaultProguardOptions()
{
return new String[0];
}
/**
* Finds a library file in either the primary or alternate lib directory.
* @param fileName The base name of the file.
* @return Either a canonical filename, or {@code null} if not found.
*/
private File getJVMLibrary( String fileName )
{
File libFile = new File( getJavaLibDir(), fileName );
if ( !libFile.exists() )
{
libFile = new File( getAltJavaLibDir(), fileName );
if ( !libFile.exists() )
{
libFile = null;
}
}
return libFile;
}
/**
* Determines the java.home directory.
* @return The java.home directory, as a File.
*/
private File getJavaHomeDir()
{
if ( javaHomeDir == null )
{
javaHomeDir = new File( System.getProperty( "java.home" ) );
}
return javaHomeDir;
}
/**
* Determines the primary JVM library location.
* @return The primary library directory, as a File.
*/
private File getJavaLibDir()
{
if ( javaLibDir == null )
{
javaLibDir = new File( getJavaHomeDir(), "lib" );
}
return javaLibDir;
}
/**
* Determines the alternate JVM library location (applies with older
* MacOSX JVMs).
* @return The alternate JVM library location, as a File.
*/
private File getAltJavaLibDir()
{
if ( altJavaLibDir == null )
{
altJavaLibDir = new File( getJavaHomeDir().getParent(), "Classes" );
}
return altJavaLibDir;
}
}
| false | true | private void executeProguard() throws MojoExecutionException
{
final File proguardDir = new File( project.getBuild().getDirectory(), parsedOutputDirectory );
if ( ! proguardDir.exists() && ! proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && ! proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
commands.add( "@" + parsedConfig );
for ( String config : parsedConfigs )
{
commands.add( "@" + config );
}
if ( proguardFile != null )
{
commands.add( "@" + proguardFile.getAbsolutePath() );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'" + obfuscatedJar + "'" );
commands.add( "-dump" );
commands.add( "'" + proguardDir + File.separator + "dump.txt'" );
commands.add( "-printseeds" );
commands.add( "'" + proguardDir + File.separator + "seeds.txt'" );
commands.add( "-printusage" );
commands.add( "'" + proguardDir + File.separator + "usage.txt'" );
File mapFile = new File(proguardDir, "mapping.txt");
commands.add( "-printmapping" );
commands.add( "'" + mapFile + "mapping.txt'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
if( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
| private void executeProguard() throws MojoExecutionException
{
final File proguardDir = new File( project.getBuild().getDirectory(), parsedOutputDirectory );
if ( ! proguardDir.exists() && ! proguardDir.mkdir() )
{
throw new MojoExecutionException( "Cannot create proguard output directory" );
}
else
{
if ( proguardDir.exists() && ! proguardDir.isDirectory() )
{
throw new MojoExecutionException( "Non-directory exists at " + proguardDir.getAbsolutePath() );
}
}
CommandExecutor executor = CommandExecutor.Factory.createDefaultCommmandExecutor();
executor.setLogger( this.getLog() );
List<String> commands = new ArrayList<String>();
collectJvmArguments( commands );
commands.add( "-jar" );
commands.add( parsedProguardJarPath );
commands.add( "@" + parsedConfig );
for ( String config : parsedConfigs )
{
commands.add( "@" + config );
}
if ( proguardFile != null )
{
commands.add( "@" + proguardFile.getAbsolutePath() );
}
collectInputFiles( commands );
commands.add( "-outjars" );
commands.add( "'" + obfuscatedJar + "'" );
commands.add( "-dump" );
commands.add( "'" + proguardDir + File.separator + "dump.txt'" );
commands.add( "-printseeds" );
commands.add( "'" + proguardDir + File.separator + "seeds.txt'" );
commands.add( "-printusage" );
commands.add( "'" + proguardDir + File.separator + "usage.txt'" );
File mapFile = new File( proguardDir, "mapping.txt" );
commands.add( "-printmapping" );
commands.add( "'" + mapFile + "mapping.txt'" );
commands.addAll( Arrays.asList( parsedOptions ) );
final String javaExecutable = getJavaExecutable().getAbsolutePath();
getLog().info( javaExecutable + " " + commands.toString() );
try
{
executor.executeCommand( javaExecutable, commands, project.getBasedir(), false );
}
catch ( ExecutionException e )
{
throw new MojoExecutionException( "", e );
}
if ( parsedAttachMap )
{
projectHelper.attachArtifact( project, "map", mapFile );
}
}
|
diff --git a/src/com/android/launcher2/AllAppsView.java b/src/com/android/launcher2/AllAppsView.java
index 999844d1..44b18ffe 100644
--- a/src/com/android/launcher2/AllAppsView.java
+++ b/src/com/android/launcher2/AllAppsView.java
@@ -1,1478 +1,1482 @@
/*
* Copyright (C) 2008 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.android.launcher2;
import android.content.ComponentName;
import android.content.Context;
import android.content.res.Resources;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.PixelFormat;
import android.graphics.Rect;
import android.os.SystemClock;
import android.renderscript.Allocation;
import android.renderscript.Dimension;
import android.renderscript.Element;
import android.renderscript.ProgramFragment;
import android.renderscript.ProgramStore;
import android.renderscript.ProgramVertex;
import android.renderscript.RSSurfaceView;
import android.renderscript.RenderScript;
import android.renderscript.Sampler;
import android.renderscript.Script;
import android.renderscript.ScriptC;
import android.renderscript.SimpleMesh;
import android.renderscript.Type;
import android.util.AttributeSet;
import android.util.Log;
import android.view.KeyEvent;
import android.view.MotionEvent;
import android.view.SoundEffectConstants;
import android.view.SurfaceHolder;
import android.view.VelocityTracker;
import android.view.View;
import android.view.ViewConfiguration;
import android.view.accessibility.AccessibilityEvent;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Comparator;
public class AllAppsView extends RSSurfaceView
implements View.OnClickListener, View.OnLongClickListener, DragSource {
private static final String TAG = "Launcher.AllAppsView";
/** Bit for mLocks for when there are icons being loaded. */
private static final int LOCK_ICONS_PENDING = 1;
private static final int TRACKING_NONE = 0;
private static final int TRACKING_FLING = 1;
private static final int TRACKING_HOME = 2;
private static final int SELECTED_NONE = 0;
private static final int SELECTED_FOCUSED = 1;
private static final int SELECTED_PRESSED = 2;
private static final int SELECTION_NONE = 0;
private static final int SELECTION_ICONS = 1;
private static final int SELECTION_HOME = 2;
private Launcher mLauncher;
private DragController mDragController;
/** When this is 0, modifications are allowed, when it's not, they're not.
* TODO: What about scrolling? */
private int mLocks = LOCK_ICONS_PENDING;
private int mSlop;
private int mMaxFlingVelocity;
private Defines mDefines = new Defines();
private RenderScript mRS;
private RolloRS mRollo;
private ArrayList<ApplicationInfo> mAllAppsList;
/**
* True when we are using arrow keys or trackball to drive navigation
*/
private boolean mArrowNavigation = false;
private boolean mStartedScrolling;
/**
* Used to keep track of the selection when AllAppsView loses window focus.
* One of the SELECTION_ constants.
*/
private int mLastSelection;
/**
* Used to keep track of the selection when AllAppsView loses window focus
*/
private int mLastSelectedIcon;
private VelocityTracker mVelocityTracker;
private int mTouchTracking;
private int mMotionDownRawX;
private int mMotionDownRawY;
private int mDownIconIndex = -1;
private int mCurrentIconIndex = -1;
private boolean mShouldGainFocus;
private boolean mHaveSurface = false;
private boolean mZoomDirty = false;
private boolean mAnimateNextZoom;
private float mNextZoom;
private float mZoom;
private float mPosX;
private float mVelocity;
private AAMessage mMessageProc;
static class Defines {
public static final int ALLOC_PARAMS = 0;
public static final int ALLOC_STATE = 1;
public static final int ALLOC_ICON_IDS = 3;
public static final int ALLOC_LABEL_IDS = 4;
public static final int ALLOC_VP_CONSTANTS = 5;
public static final int COLUMNS_PER_PAGE = 4;
public static final int ROWS_PER_PAGE = 4;
public static final int ICON_WIDTH_PX = 64;
public static final int ICON_TEXTURE_WIDTH_PX = 74;
public static final int SELECTION_TEXTURE_WIDTH_PX = 74 + 20;
public static final int ICON_HEIGHT_PX = 64;
public static final int ICON_TEXTURE_HEIGHT_PX = 74;
public static final int SELECTION_TEXTURE_HEIGHT_PX = 74 + 20;
public int SCREEN_WIDTH_PX;
public int SCREEN_HEIGHT_PX;
public void recompute(int w, int h) {
SCREEN_WIDTH_PX = 480;
SCREEN_HEIGHT_PX = 800;
}
}
public AllAppsView(Context context, AttributeSet attrs) {
super(context, attrs);
setFocusable(true);
setSoundEffectsEnabled(false);
getHolder().setFormat(PixelFormat.TRANSLUCENT);
final ViewConfiguration config = ViewConfiguration.get(context);
mSlop = config.getScaledTouchSlop();
mMaxFlingVelocity = config.getScaledMaximumFlingVelocity();
setOnClickListener(this);
setOnLongClickListener(this);
setZOrderOnTop(true);
getHolder().setFormat(PixelFormat.TRANSLUCENT);
mRS = createRenderScript(true);
}
@Override
protected void onDetachedFromWindow() {
destroyRenderScript();
}
/**
* If you have an attached click listener, View always plays the click sound!?!?
* Deal with sound effects by hand.
*/
public void reallyPlaySoundEffect(int sound) {
boolean old = isSoundEffectsEnabled();
setSoundEffectsEnabled(true);
playSoundEffect(sound);
setSoundEffectsEnabled(old);
}
public AllAppsView(Context context, AttributeSet attrs, int defStyle) {
this(context, attrs);
}
public void setLauncher(Launcher launcher) {
mLauncher = launcher;
}
@Override
public void surfaceDestroyed(SurfaceHolder holder) {
super.surfaceDestroyed(holder);
// Without this, we leak mMessageCallback which leaks the context.
mRS.mMessageCallback = null;
// We may lose any callbacks that are pending, so make sure that we re-sync that
// on the next surfaceChanged.
mZoomDirty = true;
mHaveSurface = false;
}
@Override
public void surfaceChanged(SurfaceHolder holder, int format, int w, int h) {
//long startTime = SystemClock.uptimeMillis();
super.surfaceChanged(holder, format, w, h);
mHaveSurface = true;
if (mRollo == null) {
mRollo = new RolloRS();
mRollo.init(getResources(), w, h);
if (mAllAppsList != null) {
mRollo.setApps(mAllAppsList);
}
if (mShouldGainFocus) {
gainFocus();
mShouldGainFocus = false;
}
}
mRollo.dirtyCheck();
mRollo.resize(w, h);
mRS.mMessageCallback = mMessageProc = new AAMessage();
Resources res = getContext().getResources();
int barHeight = (int)res.getDimension(R.dimen.button_bar_height);
//long endTime = SystemClock.uptimeMillis();
//Log.d(TAG, "surfaceChanged took " + (endTime-startTime) + "ms");
}
@Override
public void onWindowFocusChanged(boolean hasWindowFocus) {
super.onWindowFocusChanged(hasWindowFocus);
if (mArrowNavigation) {
if (!hasWindowFocus) {
// Clear selection when we lose window focus
mLastSelectedIcon = mRollo.mState.selectedIconIndex;
mRollo.setHomeSelected(SELECTED_NONE);
mRollo.clearSelectedIcon();
mRollo.mState.save();
} else if (hasWindowFocus) {
if (mRollo.mState.iconCount > 0) {
if (mLastSelection == SELECTION_ICONS) {
int selection = mLastSelectedIcon;
final int firstIcon = Math.round(mPosX) *
Defines.COLUMNS_PER_PAGE;
if (selection < 0 || // No selection
selection < firstIcon || // off the top of the screen
selection >= mRollo.mState.iconCount || // past last icon
selection >= firstIcon + // past last icon on screen
(Defines.COLUMNS_PER_PAGE * Defines.ROWS_PER_PAGE)) {
selection = firstIcon;
}
// Select the first icon when we gain window focus
mRollo.selectIcon(selection, SELECTED_FOCUSED);
mRollo.mState.save();
} else if (mLastSelection == SELECTION_HOME) {
mRollo.setHomeSelected(SELECTED_FOCUSED);
mRollo.mState.save();
}
}
}
}
}
@Override
protected void onFocusChanged(boolean gainFocus, int direction, Rect previouslyFocusedRect) {
super.onFocusChanged(gainFocus, direction, previouslyFocusedRect);
if (!isVisible()) {
return;
}
if (gainFocus) {
if (mRollo != null) {
gainFocus();
} else {
mShouldGainFocus = true;
}
} else {
if (mRollo != null) {
if (mArrowNavigation) {
// Clear selection when we lose focus
mRollo.clearSelectedIcon();
mRollo.setHomeSelected(SELECTED_NONE);
mRollo.mState.save();
mArrowNavigation = false;
}
} else {
mShouldGainFocus = false;
}
}
}
private void gainFocus() {
if (!mArrowNavigation && mRollo.mState.iconCount > 0) {
// Select the first icon when we gain keyboard focus
mArrowNavigation = true;
mRollo.selectIcon(Math.round(mPosX) * Defines.COLUMNS_PER_PAGE,
SELECTED_FOCUSED);
mRollo.mState.save();
}
}
@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean handled = false;
if (!isVisible()) {
return false;
}
final int iconCount = mRollo.mState.iconCount;
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
if (mArrowNavigation) {
if (mLastSelection == SELECTION_HOME) {
reallyPlaySoundEffect(SoundEffectConstants.CLICK);
mLauncher.closeAllApps(true);
} else {
int whichApp = mRollo.mState.selectedIconIndex;
if (whichApp >= 0) {
ApplicationInfo app = mAllAppsList.get(whichApp);
mLauncher.startActivitySafely(app.intent);
handled = true;
}
}
}
}
if (iconCount > 0) {
mArrowNavigation = true;
int currentSelection = mRollo.mState.selectedIconIndex;
int currentTopRow = Math.round(mPosX);
// The column of the current selection, in the range 0..COLUMNS_PER_PAGE-1
final int currentPageCol = currentSelection % Defines.COLUMNS_PER_PAGE;
// The row of the current selection, in the range 0..ROWS_PER_PAGE-1
final int currentPageRow = (currentSelection - (currentTopRow*Defines.COLUMNS_PER_PAGE))
/ Defines.ROWS_PER_PAGE;
int newSelection = currentSelection;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
if (mLastSelection == SELECTION_HOME) {
mRollo.setHomeSelected(SELECTED_NONE);
int lastRowCount = iconCount % Defines.COLUMNS_PER_PAGE;
if (lastRowCount == 0) {
lastRowCount = Defines.COLUMNS_PER_PAGE;
}
newSelection = iconCount - lastRowCount + (Defines.COLUMNS_PER_PAGE / 2);
if (newSelection >= iconCount) {
newSelection = iconCount-1;
}
int target = (newSelection / Defines.COLUMNS_PER_PAGE)
- (Defines.ROWS_PER_PAGE - 1);
if (target < 0) {
target = 0;
}
if (currentTopRow != target) {
mRollo.moveTo(target);
}
} else {
if (currentPageRow > 0) {
newSelection = currentSelection - Defines.COLUMNS_PER_PAGE;
} else if (currentTopRow > 0) {
newSelection = currentSelection - Defines.COLUMNS_PER_PAGE;
mRollo.moveTo(newSelection / Defines.COLUMNS_PER_PAGE);
} else if (currentPageRow != 0) {
newSelection = currentTopRow * Defines.ROWS_PER_PAGE;
}
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN: {
final int rowCount = iconCount / Defines.COLUMNS_PER_PAGE
+ (iconCount % Defines.COLUMNS_PER_PAGE == 0 ? 0 : 1);
final int currentRow = currentSelection / Defines.COLUMNS_PER_PAGE;
if (mLastSelection != SELECTION_HOME) {
if (currentRow < rowCount-1) {
mRollo.setHomeSelected(SELECTED_NONE);
if (currentSelection < 0) {
newSelection = 0;
} else {
newSelection = currentSelection + Defines.COLUMNS_PER_PAGE;
}
if (newSelection >= iconCount) {
// Go from D to G in this arrangement:
// A B C D
// E F G
newSelection = iconCount - 1;
}
if (currentPageRow >= Defines.ROWS_PER_PAGE - 1) {
mRollo.moveTo((newSelection / Defines.COLUMNS_PER_PAGE) -
Defines.ROWS_PER_PAGE + 1);
}
} else {
newSelection = -1;
mRollo.setHomeSelected(SELECTED_FOCUSED);
}
}
handled = true;
break;
}
case KeyEvent.KEYCODE_DPAD_LEFT:
- if (currentPageCol > 0) {
- newSelection = currentSelection - 1;
+ if (mLastSelection != SELECTION_HOME) {
+ if (currentPageCol > 0) {
+ newSelection = currentSelection - 1;
+ }
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
- if ((currentPageCol < Defines.COLUMNS_PER_PAGE - 1) &&
- (currentSelection < iconCount - 1)) {
- newSelection = currentSelection + 1;
+ if (mLastSelection != SELECTION_HOME) {
+ if ((currentPageCol < Defines.COLUMNS_PER_PAGE - 1) &&
+ (currentSelection < iconCount - 1)) {
+ newSelection = currentSelection + 1;
+ }
}
handled = true;
break;
}
if (newSelection != currentSelection) {
mRollo.selectIcon(newSelection, SELECTED_FOCUSED);
mRollo.mState.save();
}
}
return handled;
}
@Override
public boolean onTouchEvent(MotionEvent ev)
{
mArrowNavigation = false;
if (!isVisible()) {
return true;
}
if (mLocks != 0) {
return true;
}
super.onTouchEvent(ev);
int x = (int)ev.getX();
int y = (int)ev.getY();
int action = ev.getAction();
switch (action) {
case MotionEvent.ACTION_DOWN:
if (y > mRollo.mTouchYBorders[mRollo.mTouchYBorders.length-1]) {
mTouchTracking = TRACKING_HOME;
mRollo.setHomeSelected(SELECTED_PRESSED);
mRollo.mState.save();
mCurrentIconIndex = -1;
} else {
mTouchTracking = TRACKING_FLING;
mMotionDownRawX = (int)ev.getRawX();
mMotionDownRawY = (int)ev.getRawY();
mRollo.mState.newPositionX = ev.getRawY() / getHeight();
mRollo.mState.newTouchDown = 1;
if (!mRollo.checkClickOK()) {
mRollo.clearSelectedIcon();
} else {
mDownIconIndex = mCurrentIconIndex
= mRollo.selectIcon(x, y, mPosX, SELECTED_PRESSED);
if (mDownIconIndex < 0) {
// if nothing was selected, no long press.
cancelLongPress();
}
}
mRollo.mState.save();
mRollo.move();
mVelocityTracker = VelocityTracker.obtain();
mVelocityTracker.addMovement(ev);
mStartedScrolling = false;
}
break;
case MotionEvent.ACTION_MOVE:
case MotionEvent.ACTION_OUTSIDE:
if (mTouchTracking == TRACKING_HOME) {
mRollo.setHomeSelected(y > mRollo.mTouchYBorders[mRollo.mTouchYBorders.length-1]
? SELECTED_PRESSED : SELECTED_NONE);
mRollo.mState.save();
} else if (mTouchTracking == TRACKING_FLING) {
int rawX = (int)ev.getRawX();
int rawY = (int)ev.getRawY();
int slop;
slop = Math.abs(rawY - mMotionDownRawY);
if (!mStartedScrolling && slop < mSlop) {
// don't update anything so when we do start scrolling
// below, we get the right delta.
mCurrentIconIndex = mRollo.chooseTappedIcon(x, y, mPosX);
if (mDownIconIndex != mCurrentIconIndex) {
// If a different icon is selected, don't allow it to be picked up.
// This handles off-axis dragging.
cancelLongPress();
mCurrentIconIndex = -1;
}
} else {
if (!mStartedScrolling) {
cancelLongPress();
mCurrentIconIndex = -1;
}
mRollo.mState.newPositionX = ev.getRawY() / getHeight();
mRollo.mState.newTouchDown = 1;
mRollo.move();
mStartedScrolling = true;
mRollo.clearSelectedIcon();
mVelocityTracker.addMovement(ev);
mRollo.mState.save();
}
}
break;
case MotionEvent.ACTION_UP:
case MotionEvent.ACTION_CANCEL:
if (mTouchTracking == TRACKING_HOME) {
if (action == MotionEvent.ACTION_UP) {
if (y > mRollo.mTouchYBorders[mRollo.mTouchYBorders.length-1]) {
reallyPlaySoundEffect(SoundEffectConstants.CLICK);
mLauncher.closeAllApps(true);
}
mRollo.setHomeSelected(SELECTED_NONE);
mRollo.mState.save();
}
mCurrentIconIndex = -1;
} else if (mTouchTracking == TRACKING_FLING) {
mRollo.mState.newTouchDown = 0;
mRollo.mState.newPositionX = ev.getRawY() / getHeight();
mVelocityTracker.computeCurrentVelocity(1000 /* px/sec */, mMaxFlingVelocity);
mRollo.mState.flingVelocity = mVelocityTracker.getYVelocity() / getHeight();
mRollo.clearSelectedIcon();
mRollo.mState.save();
mRollo.fling();
if (mVelocityTracker != null) {
mVelocityTracker.recycle();
mVelocityTracker = null;
}
}
mTouchTracking = TRACKING_NONE;
break;
}
return true;
}
public void onClick(View v) {
if (mLocks != 0 || !isVisible()) {
return;
}
if (mRollo.checkClickOK() && mCurrentIconIndex == mDownIconIndex
&& mCurrentIconIndex >= 0 && mCurrentIconIndex < mAllAppsList.size()) {
reallyPlaySoundEffect(SoundEffectConstants.CLICK);
ApplicationInfo app = mAllAppsList.get(mCurrentIconIndex);
mLauncher.startActivitySafely(app.intent);
}
}
public boolean onLongClick(View v) {
if (mLocks != 0 || !isVisible()) {
return true;
}
if (mRollo.checkClickOK() && mCurrentIconIndex == mDownIconIndex
&& mCurrentIconIndex >= 0 && mCurrentIconIndex < mAllAppsList.size()) {
ApplicationInfo app = mAllAppsList.get(mCurrentIconIndex);
Bitmap bmp = app.iconBitmap;
final int w = bmp.getWidth();
final int h = bmp.getHeight();
// We don't really have an accurate location to use. This will do.
int screenX = mMotionDownRawX - (w / 2);
int screenY = mMotionDownRawY - h;
int left = (mDefines.ICON_TEXTURE_WIDTH_PX - mDefines.ICON_WIDTH_PX) / 2;
int top = (mDefines.ICON_TEXTURE_HEIGHT_PX - mDefines.ICON_HEIGHT_PX) / 2;
mDragController.startDrag(bmp, screenX, screenY,
0, 0, w, h, this, app, DragController.DRAG_ACTION_COPY);
mLauncher.closeAllApps(true);
}
return true;
}
@Override
public boolean dispatchPopulateAccessibilityEvent(AccessibilityEvent event) {
if (event.getEventType() == AccessibilityEvent.TYPE_VIEW_SELECTED) {
if (!isVisible()) {
return false;
}
String text = null;
int index;
int count = mAllAppsList.size() + 1; // +1 is home
int pos = -1;
switch (mLastSelection) {
case SELECTION_ICONS:
index = mRollo.mState.selectedIconIndex;
if (index >= 0) {
ApplicationInfo info = mAllAppsList.get(index);
if (info.title != null) {
text = info.title.toString();
pos = index;
}
}
break;
case SELECTION_HOME:
text = getContext().getString(R.string.all_apps_home_button_label);
pos = count;
break;
}
if (text != null) {
event.setEnabled(true);
event.getText().add(text);
//event.setContentDescription(text);
event.setItemCount(count);
event.setCurrentItemIndex(pos);
}
}
return false;
}
public void setDragController(DragController dragger) {
mDragController = dragger;
}
public void onDropCompleted(View target, boolean success) {
}
/**
* Zoom to the specifed level.
*
* @param zoom [0..1] 0 is hidden, 1 is open
*/
public void zoom(float zoom, boolean animate) {
cancelLongPress();
mNextZoom = zoom;
mAnimateNextZoom = animate;
// if we do setZoom while we don't have a surface, we won't
// get the callbacks that actually set mZoom.
if (mRollo == null || !mHaveSurface) {
mZoomDirty = true;
mZoom = zoom;
return;
} else {
mRollo.setZoom(zoom, animate);
}
}
public boolean isVisible() {
return mZoom > 0.001f;
}
public boolean isOpaque() {
return mZoom > 0.999f;
}
public void setApps(ArrayList<ApplicationInfo> list) {
mAllAppsList = list;
if (mRollo != null) {
mRollo.setApps(list);
}
mLocks &= ~LOCK_ICONS_PENDING;
}
public void addApps(ArrayList<ApplicationInfo> list) {
if (mAllAppsList == null) {
// Not done loading yet. We'll find out about it later.
return;
}
final int N = list.size();
if (mRollo != null) {
mRollo.reallocAppsList(mRollo.mState.iconCount + N);
}
for (int i=0; i<N; i++) {
final ApplicationInfo item = list.get(i);
int index = Collections.binarySearch(mAllAppsList, item,
LauncherModel.APP_NAME_COMPARATOR);
if (index < 0) {
index = -(index+1);
}
mAllAppsList.add(index, item);
if (mRollo != null) {
mRollo.addApp(index, item);
}
}
if (mRollo != null) {
mRollo.saveAppsList();
}
}
public void removeApps(ArrayList<ApplicationInfo> list) {
if (mAllAppsList == null) {
// Not done loading yet. We'll find out about it later.
return;
}
final int N = list.size();
for (int i=0; i<N; i++) {
final ApplicationInfo item = list.get(i);
int index = findAppByComponent(mAllAppsList, item);
if (index >= 0) {
int ic = mRollo != null ? mRollo.mState.iconCount : 666;
mAllAppsList.remove(index);
if (mRollo != null) {
mRollo.removeApp(index);
}
} else {
Log.w(TAG, "couldn't find a match for item \"" + item + "\"");
// Try to recover. This should keep us from crashing for now.
}
}
if (mRollo != null) {
mRollo.saveAppsList();
}
}
public void updateApps(String packageName, ArrayList<ApplicationInfo> list) {
// Just remove and add, because they may need to be re-sorted.
removeApps(list);
addApps(list);
}
private static int findAppByComponent(ArrayList<ApplicationInfo> list, ApplicationInfo item) {
ComponentName component = item.intent.getComponent();
final int N = list.size();
for (int i=0; i<N; i++) {
ApplicationInfo x = list.get(i);
if (x.intent.getComponent().equals(component)) {
return i;
}
}
return -1;
}
private static int countPages(int iconCount) {
int iconsPerPage = Defines.COLUMNS_PER_PAGE * Defines.ROWS_PER_PAGE;
int pages = iconCount / iconsPerPage;
if (pages*iconsPerPage != iconCount) {
pages++;
}
return pages;
}
class AAMessage extends RenderScript.RSMessage {
public void run() {
mPosX = ((float)mData[0]) / (1 << 16);
mVelocity = ((float)mData[1]) / (1 << 16);
mZoom = ((float)mData[2]) / (1 << 16);
mZoomDirty = false;
}
}
public class RolloRS {
// Allocations ======
private int mWidth;
private int mHeight;
private Resources mRes;
private Script mScript;
private Script.Invokable mInvokeMove;
private Script.Invokable mInvokeMoveTo;
private Script.Invokable mInvokeFling;
private Script.Invokable mInvokeResetWAR;
private Script.Invokable mInvokeSetZoom;
private ProgramStore mPSIcons;
private ProgramStore mPSText;
private ProgramFragment mPFColor;
private ProgramFragment mPFTexMip;
private ProgramFragment mPFTexMipAlpha;
private ProgramFragment mPFTexNearest;
private ProgramVertex mPV;
private ProgramVertex mPVOrtho;
private ProgramVertex mPVCurve;
private SimpleMesh mMesh;
private ProgramVertex.MatrixAllocation mPVA;
private Allocation mUniformAlloc;
private Allocation mHomeButtonNormal;
private Allocation mHomeButtonFocused;
private Allocation mHomeButtonPressed;
private Allocation[] mIcons;
private int[] mIconIds;
private Allocation mAllocIconIds;
private Allocation[] mLabels;
private int[] mLabelIds;
private Allocation mAllocLabelIds;
private Allocation mSelectedIcon;
private int[] mTouchYBorders;
private int[] mTouchXBorders;
private Bitmap mSelectionBitmap;
private Canvas mSelectionCanvas;
Params mParams;
State mState;
class BaseAlloc {
Allocation mAlloc;
Type mType;
void save() {
mAlloc.data(this);
}
}
private boolean checkClickOK() {
return (Math.abs(mVelocity) < 0.4f) &&
(Math.abs(mPosX - Math.round(mPosX)) < 0.4f);
}
class Params extends BaseAlloc {
Params() {
mType = Type.createFromClass(mRS, Params.class, 1, "ParamsClass");
mAlloc = Allocation.createTyped(mRS, mType);
save();
}
public int bubbleWidth;
public int bubbleHeight;
public int bubbleBitmapWidth;
public int bubbleBitmapHeight;
public int homeButtonWidth;
public int homeButtonHeight;
public int homeButtonTextureWidth;
public int homeButtonTextureHeight;
}
class State extends BaseAlloc {
public float newPositionX;
public int newTouchDown;
public float flingVelocity;
public int iconCount;
public int selectedIconIndex = -1;
public int selectedIconTexture;
public float zoomTarget;
public int homeButtonId;
public float targetPos;
State() {
mType = Type.createFromClass(mRS, State.class, 1, "StateClass");
mAlloc = Allocation.createTyped(mRS, mType);
save();
}
}
public RolloRS() {
}
public void init(Resources res, int width, int height) {
mRes = res;
mWidth = width;
mHeight = height;
mDefines.recompute(width, height);
initProgramVertex();
initProgramFragment();
initProgramStore();
//initMesh();
initGl();
initData();
initTouchState();
initRs();
}
public void initMesh2() {
SimpleMesh.TriangleMeshBuilder tm = new SimpleMesh.TriangleMeshBuilder(mRS, 2, 0);
for (int ct=0; ct < 16; ct++) {
float pos = (1.f / 16.f) * ct;
tm.addVertex(0.0f, pos);
tm.addVertex(1.0f, pos);
}
for (int ct=0; ct < (16 * 2 - 2); ct+= 2) {
tm.addTriangle(ct, ct+1, ct+2);
tm.addTriangle(ct+1, ct+3, ct+2);
}
mMesh = tm.create();
mMesh.setName("SMCell");
}
void resize(int w, int h) {
mPVA.setupProjectionNormalized(w, h);
mWidth = w;
mHeight = h;
}
private void initProgramVertex() {
mPVA = new ProgramVertex.MatrixAllocation(mRS);
resize(mWidth, mHeight);
ProgramVertex.Builder pvb = new ProgramVertex.Builder(mRS, null, null);
pvb.setTextureMatrixEnable(true);
mPV = pvb.create();
mPV.setName("PV");
mPV.bindAllocation(mPVA);
Element.Builder eb = new Element.Builder(mRS);
eb.add(Element.createVector(mRS, Element.DataType.FLOAT_32, 2), "ImgSize");
eb.add(Element.createVector(mRS, Element.DataType.FLOAT_32, 4), "Position");
Element e = eb.create();
mUniformAlloc = Allocation.createSized(mRS, e, 1);
initMesh2();
ProgramVertex.ShaderBuilder sb = new ProgramVertex.ShaderBuilder(mRS);
String t = new String("void main() {\n" +
// Animation
" float ani = UNI_Position.z;\n" +
" float scale = (2.0 / 480.0);\n" +
" float x = UNI_Position.x + UNI_ImgSize.x * (1.0 - ani) * (ATTRIB_position.x - 0.5);\n" +
" float ys= UNI_Position.y + UNI_ImgSize.y * (1.0 - ani) * ATTRIB_position.y;\n" +
" float y = 0.0;\n" +
" float z = 0.0;\n" +
" float lum = 1.0;\n" +
" float cv = min(ys, 50.0) - 50.0;\n" +
" y += cv * 0.681;\n" + // Roughy 47 degrees
" z += -cv * 0.731;\n" +
" cv = clamp(ys, 50.0, 120.0) - 120.0;\n" + // curve range
" y += cv * cos(cv * 0.4 / (180.0 / 3.14));\n" +
" z += cv * sin(cv * 0.4 / (180.0 / 3.14));\n" +
" cv = max(ys, 750.0) - 750.0;\n" +
" y += cv * 0.681;\n" +
" z += cv * 0.731;\n" +
" cv = clamp(ys, 680.0, 750.0) - 680.0;\n" +
" y += cv * cos(cv * 0.4 / (180.0 / 3.14));\n" +
" z += cv * sin(cv * 0.4 / (180.0 / 3.14));\n" +
" y += clamp(ys, 120.0, 680.0);\n" +
" lum += (clamp(ys, 60.0, 115.0) - 115.0) / 100.0;\n" +
" lum -= (clamp(ys, 685.0, 740.0) - 685.0) / 100.0;\n" +
" vec4 pos;\n" +
" pos.x = x * scale - 1.0;\n" +
" pos.y = y * scale - 1.66;\n" +
" pos.z = z * scale;\n" +
" pos.w = 1.0;\n" +
" pos.x *= 1.0 + ani * 4.0;\n" +
" pos.y *= 1.0 + ani * 4.0;\n" +
" pos.z -= ani * 1.5;\n" +
" lum *= 1.0 - ani;\n" +
" gl_Position = UNI_MVP * pos;\n" +
" varColor.rgba = vec4(lum, lum, lum, 1.0);\n" +
" varTex0.xy = ATTRIB_position;\n" +
" varTex0.y = 1.0 - varTex0.y;\n" +
" varTex0.zw = vec2(0.0, 0.0);\n" +
"}\n");
sb.setShader(t);
sb.addConstant(mUniformAlloc.getType());
sb.addInput(mMesh.getVertexType(0).getElement());
mPVCurve = sb.create();
mPVCurve.setName("PVCurve");
mPVCurve.bindAllocation(mPVA);
mPVCurve.bindConstants(mUniformAlloc, 1);
float tf[] = new float[] {72.f, 72.f, 0.f, 0.f, 120.f, 120.f, 0.f, 0.f};
mUniformAlloc.data(tf);
//pva = new ProgramVertex.MatrixAllocation(mRS);
//pva.setupOrthoWindow(mWidth, mHeight);
//pvb.setTextureMatrixEnable(true);
//mPVOrtho = pvb.create();
//mPVOrtho.setName("PVOrtho");
//mPVOrtho.bindAllocation(pva);
mRS.contextBindProgramVertex(mPV);
}
private void initProgramFragment() {
Sampler.Builder sb = new Sampler.Builder(mRS);
sb.setMin(Sampler.Value.LINEAR_MIP_LINEAR);
sb.setMag(Sampler.Value.NEAREST);
sb.setWrapS(Sampler.Value.CLAMP);
sb.setWrapT(Sampler.Value.CLAMP);
Sampler linear = sb.create();
sb.setMin(Sampler.Value.NEAREST);
sb.setMag(Sampler.Value.NEAREST);
Sampler nearest = sb.create();
ProgramFragment.Builder bf = new ProgramFragment.Builder(mRS);
//mPFColor = bf.create();
//mPFColor.setName("PFColor");
bf.setTexture(ProgramFragment.Builder.EnvMode.MODULATE,
ProgramFragment.Builder.Format.RGBA, 0);
mPFTexMip = bf.create();
mPFTexMip.setName("PFTexMip");
mPFTexMip.bindSampler(linear, 0);
mPFTexNearest = bf.create();
mPFTexNearest.setName("PFTexNearest");
mPFTexNearest.bindSampler(nearest, 0);
bf.setTexture(ProgramFragment.Builder.EnvMode.MODULATE,
ProgramFragment.Builder.Format.ALPHA, 0);
mPFTexMipAlpha = bf.create();
mPFTexMipAlpha.setName("PFTexMipAlpha");
mPFTexMipAlpha.bindSampler(linear, 0);
}
private void initProgramStore() {
ProgramStore.Builder bs = new ProgramStore.Builder(mRS, null, null);
bs.setDepthFunc(ProgramStore.DepthFunc.ALWAYS);
bs.setColorMask(true,true,true,false);
bs.setDitherEnable(true);
bs.setBlendFunc(ProgramStore.BlendSrcFunc.SRC_ALPHA,
ProgramStore.BlendDstFunc.ONE_MINUS_SRC_ALPHA);
mPSIcons = bs.create();
mPSIcons.setName("PSIcons");
//bs.setDitherEnable(false);
//mPSText = bs.create();
//mPSText.setName("PSText");
}
private void initGl() {
mTouchXBorders = new int[Defines.COLUMNS_PER_PAGE+1];
mTouchYBorders = new int[Defines.ROWS_PER_PAGE+1];
}
private void initData() {
mParams = new Params();
mState = new State();
final Utilities.BubbleText bubble = new Utilities.BubbleText(getContext());
mParams.bubbleWidth = bubble.getBubbleWidth();
mParams.bubbleHeight = bubble.getMaxBubbleHeight();
mParams.bubbleBitmapWidth = bubble.getBitmapWidth();
mParams.bubbleBitmapHeight = bubble.getBitmapHeight();
mHomeButtonNormal = Allocation.createFromBitmapResource(mRS, mRes,
R.drawable.home_button_normal, Element.RGBA_8888(mRS), false);
mHomeButtonNormal.uploadToTexture(0);
mHomeButtonFocused = Allocation.createFromBitmapResource(mRS, mRes,
R.drawable.home_button_focused, Element.RGBA_8888(mRS), false);
mHomeButtonFocused.uploadToTexture(0);
mHomeButtonPressed = Allocation.createFromBitmapResource(mRS, mRes,
R.drawable.home_button_pressed, Element.RGBA_8888(mRS), false);
mHomeButtonPressed.uploadToTexture(0);
mParams.homeButtonWidth = 76;
mParams.homeButtonHeight = 68;
mParams.homeButtonTextureWidth = 128;
mParams.homeButtonTextureHeight = 128;
mState.homeButtonId = mHomeButtonNormal.getID();
mParams.save();
mState.save();
mSelectionBitmap = Bitmap.createBitmap(Defines.SELECTION_TEXTURE_WIDTH_PX,
Defines.SELECTION_TEXTURE_HEIGHT_PX, Bitmap.Config.ARGB_8888);
mSelectionCanvas = new Canvas(mSelectionBitmap);
setApps(null);
}
private void initScript(int id) {
}
private void initRs() {
ScriptC.Builder sb = new ScriptC.Builder(mRS);
sb.setScript(mRes, R.raw.allapps);
sb.setRoot(true);
sb.addDefines(mDefines);
sb.setType(mParams.mType, "params", Defines.ALLOC_PARAMS);
sb.setType(mState.mType, "state", Defines.ALLOC_STATE);
sb.setType(mUniformAlloc.getType(), "vpConstants", Defines.ALLOC_VP_CONSTANTS);
mInvokeMove = sb.addInvokable("move");
mInvokeFling = sb.addInvokable("fling");
mInvokeMoveTo = sb.addInvokable("moveTo");
mInvokeResetWAR = sb.addInvokable("resetHWWar");
mInvokeSetZoom = sb.addInvokable("setZoom");
mScript = sb.create();
mScript.setClearColor(0.0f, 0.0f, 0.0f, 0.0f);
mScript.bindAllocation(mParams.mAlloc, Defines.ALLOC_PARAMS);
mScript.bindAllocation(mState.mAlloc, Defines.ALLOC_STATE);
mScript.bindAllocation(mAllocIconIds, Defines.ALLOC_ICON_IDS);
mScript.bindAllocation(mAllocLabelIds, Defines.ALLOC_LABEL_IDS);
mScript.bindAllocation(mUniformAlloc, Defines.ALLOC_VP_CONSTANTS);
mRS.contextBindRootScript(mScript);
}
void dirtyCheck() {
if (mZoomDirty) {
setZoom(mNextZoom, mAnimateNextZoom);
}
}
private void setApps(ArrayList<ApplicationInfo> list) {
final int count = list != null ? list.size() : 0;
int allocCount = count;
if (allocCount < 1) {
allocCount = 1;
}
mIcons = new Allocation[count];
mIconIds = new int[allocCount];
mAllocIconIds = Allocation.createSized(mRS, Element.USER_I32(mRS), allocCount);
mLabels = new Allocation[count];
mLabelIds = new int[allocCount];
mAllocLabelIds = Allocation.createSized(mRS, Element.USER_I32(mRS), allocCount);
Element ie8888 = Element.RGBA_8888(mRS);
mState.iconCount = count;
for (int i=0; i < mState.iconCount; i++) {
createAppIconAllocations(i, list.get(i));
}
for (int i=0; i < mState.iconCount; i++) {
uploadAppIcon(i, list.get(i));
}
saveAppsList();
}
private void setZoom(float zoom, boolean animate) {
mRollo.clearSelectedIcon();
mRollo.setHomeSelected(SELECTED_NONE);
if (zoom > 0.001f) {
mRollo.mState.zoomTarget = zoom;
} else {
mRollo.mState.zoomTarget = 0;
}
mRollo.mState.save();
if (!animate) {
mRollo.mInvokeSetZoom.execute();
}
}
private void createAppIconAllocations(int index, ApplicationInfo item) {
mIcons[index] = Allocation.createFromBitmap(mRS, item.iconBitmap,
Element.RGBA_8888(mRS), true);
mLabels[index] = Allocation.createFromBitmap(mRS, item.titleBitmap,
Element.A_8(mRS), true);
mIconIds[index] = mIcons[index].getID();
mLabelIds[index] = mLabels[index].getID();
}
private void uploadAppIcon(int index, ApplicationInfo item) {
if (mIconIds[index] != mIcons[index].getID()) {
throw new IllegalStateException("uploadAppIcon index=" + index
+ " mIcons[index].getID=" + mIcons[index].getID()
+ " mIconsIds[index]=" + mIconIds[index]
+ " item=" + item);
}
mIcons[index].uploadToTexture(0);
mLabels[index].uploadToTexture(0);
}
/**
* Puts the empty spaces at the end. Updates mState.iconCount. You must
* fill in the values and call saveAppsList().
*/
private void reallocAppsList(int count) {
Allocation[] icons = new Allocation[count];
int[] iconIds = new int[count];
mAllocIconIds = Allocation.createSized(mRS, Element.USER_I32(mRS), count);
Allocation[] labels = new Allocation[count];
int[] labelIds = new int[count];
mAllocLabelIds = Allocation.createSized(mRS, Element.USER_I32(mRS), count);
final int oldCount = mRollo.mState.iconCount;
System.arraycopy(mIcons, 0, icons, 0, oldCount);
System.arraycopy(mIconIds, 0, iconIds, 0, oldCount);
System.arraycopy(mLabels, 0, labels, 0, oldCount);
System.arraycopy(mLabelIds, 0, labelIds, 0, oldCount);
mIcons = icons;
mIconIds = iconIds;
mLabels = labels;
mLabelIds = labelIds;
}
/**
* Handle the allocations for the new app. Make sure you call saveAppsList when done.
*/
private void addApp(int index, ApplicationInfo item) {
final int count = mState.iconCount - index;
final int dest = index + 1;
System.arraycopy(mIcons, index, mIcons, dest, count);
System.arraycopy(mIconIds, index, mIconIds, dest, count);
System.arraycopy(mLabels, index, mLabels, dest, count);
System.arraycopy(mLabelIds, index, mLabelIds, dest, count);
createAppIconAllocations(index, item);
uploadAppIcon(index, item);
mRollo.mState.iconCount++;
}
/**
* Handle the allocations for the removed app. Make sure you call saveAppsList when done.
*/
private void removeApp(int index) {
final int count = mState.iconCount - index - 1;
final int src = index + 1;
System.arraycopy(mIcons, src, mIcons, index, count);
System.arraycopy(mIconIds, src, mIconIds, index, count);
System.arraycopy(mLabels, src, mLabels, index, count);
System.arraycopy(mLabelIds, src, mLabelIds, index, count);
mRollo.mState.iconCount--;
final int last = mState.iconCount;
mIcons[last] = null;
mIconIds[last] = 0;
mLabels[last] = null;
mLabelIds[last] = 0;
}
/**
* Send the apps list structures to RS.
*/
private void saveAppsList() {
mRS.contextBindRootScript(null);
mAllocIconIds.data(mIconIds);
mAllocLabelIds.data(mLabelIds);
if (mScript != null) { // this happens when we init it
mScript.bindAllocation(mAllocIconIds, Defines.ALLOC_ICON_IDS);
mScript.bindAllocation(mAllocLabelIds, Defines.ALLOC_LABEL_IDS);
}
mState.save();
// Note: mScript may be null if we haven't initialized it yet.
// In that case, this is a no-op.
if (mInvokeResetWAR != null) {
mInvokeResetWAR.execute();
}
mRS.contextBindRootScript(mScript);
}
void initTouchState() {
int width = getWidth();
int height = getHeight();
int cellHeight = 145;//iconsSize / Defines.ROWS_PER_PAGE;
int cellWidth = width / Defines.COLUMNS_PER_PAGE;
int centerY = (height / 2);
mTouchYBorders[0] = centerY - (cellHeight * 2);
mTouchYBorders[1] = centerY - cellHeight;
mTouchYBorders[2] = centerY;
mTouchYBorders[3] = centerY + cellHeight;
mTouchYBorders[4] = centerY + (cellHeight * 2);
int centerX = (width / 2);
mTouchXBorders[0] = 0;
mTouchXBorders[1] = centerX - (width / 4);
mTouchXBorders[2] = centerX;
mTouchXBorders[3] = centerX + (width / 4);
mTouchXBorders[4] = width;
}
void fling() {
mInvokeFling.execute();
}
void move() {
mInvokeMove.execute();
}
void moveTo(float row) {
mState.targetPos = row;
mState.save();
mInvokeMoveTo.execute();
}
int chooseTappedIcon(int x, int y, float pos) {
// Adjust for scroll position if not zero.
y += (pos - ((int)pos)) * (mTouchYBorders[1] - mTouchYBorders[0]);
int col = -1;
int row = -1;
for (int i=0; i<Defines.COLUMNS_PER_PAGE; i++) {
if (x >= mTouchXBorders[i] && x < mTouchXBorders[i+1]) {
col = i;
break;
}
}
for (int i=0; i<Defines.ROWS_PER_PAGE; i++) {
if (y >= mTouchYBorders[i] && y < mTouchYBorders[i+1]) {
row = i;
break;
}
}
if (row < 0 || col < 0) {
return -1;
}
int index = (((int)pos) * Defines.COLUMNS_PER_PAGE)
+ (row * Defines.ROWS_PER_PAGE) + col;
if (index >= mState.iconCount) {
return -1;
} else {
return index;
}
}
/**
* You need to call save() on mState on your own after calling this.
*
* @return the index of the icon that was selected.
*/
int selectIcon(int x, int y, float pos, int pressed) {
final int index = chooseTappedIcon(x, y, pos);
selectIcon(index, pressed);
return index;
}
/**
* Select the icon at the given index.
*
* @param index The index.
* @param pressed one of SELECTED_PRESSED or SELECTED_FOCUSED
*/
void selectIcon(int index, int pressed) {
if (mAllAppsList == null || index < 0 || index >= mAllAppsList.size()) {
mState.selectedIconIndex = -1;
if (mLastSelection == SELECTION_ICONS) {
mLastSelection = SELECTION_NONE;
}
} else {
if (pressed == SELECTED_FOCUSED) {
mLastSelection = SELECTION_ICONS;
}
int prev = mState.selectedIconIndex;
mState.selectedIconIndex = index;
ApplicationInfo info = mAllAppsList.get(index);
Bitmap selectionBitmap = mSelectionBitmap;
Utilities.drawSelectedAllAppsBitmap(mSelectionCanvas,
selectionBitmap.getWidth(), selectionBitmap.getHeight(),
pressed == SELECTED_PRESSED, info.iconBitmap);
mSelectedIcon = Allocation.createFromBitmap(mRS, selectionBitmap,
Element.RGBA_8888(mRS), false);
mSelectedIcon.uploadToTexture(0);
mState.selectedIconTexture = mSelectedIcon.getID();
if (prev != index) {
if (info.title != null && info.title.length() > 0) {
//setContentDescription(info.title);
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
}
}
}
/**
* You need to call save() on mState on your own after calling this.
*/
void clearSelectedIcon() {
mState.selectedIconIndex = -1;
}
void setHomeSelected(int mode) {
final int prev = mLastSelection;
switch (mode) {
case SELECTED_NONE:
mState.homeButtonId = mHomeButtonNormal.getID();
break;
case SELECTED_FOCUSED:
mLastSelection = SELECTION_HOME;
mState.homeButtonId = mHomeButtonFocused.getID();
if (prev != SELECTION_HOME) {
sendAccessibilityEvent(AccessibilityEvent.TYPE_VIEW_SELECTED);
}
break;
case SELECTED_PRESSED:
mState.homeButtonId = mHomeButtonPressed.getID();
break;
}
}
public void dumpState() {
Log.d(TAG, "mRollo.mWidth=" + mWidth);
Log.d(TAG, "mRollo.mHeight=" + mHeight);
Log.d(TAG, "mRollo.mIcons=" + mIcons);
if (mIcons != null) {
Log.d(TAG, "mRollo.mIcons.length=" + mIcons.length);
}
if (mIconIds != null) {
Log.d(TAG, "mRollo.mIconIds.length=" + mIconIds.length);
}
Log.d(TAG, "mRollo.mIconIds=" + Arrays.toString(mIconIds));
if (mLabelIds != null) {
Log.d(TAG, "mRollo.mLabelIds.length=" + mLabelIds.length);
}
Log.d(TAG, "mRollo.mLabelIds=" + Arrays.toString(mLabelIds));
Log.d(TAG, "mRollo.mTouchXBorders=" + Arrays.toString(mTouchXBorders));
Log.d(TAG, "mRollo.mTouchYBorders=" + Arrays.toString(mTouchYBorders));
Log.d(TAG, "mRollo.mState.newPositionX=" + mState.newPositionX);
Log.d(TAG, "mRollo.mState.newTouchDown=" + mState.newTouchDown);
Log.d(TAG, "mRollo.mState.flingVelocity=" + mState.flingVelocity);
Log.d(TAG, "mRollo.mState.iconCount=" + mState.iconCount);
Log.d(TAG, "mRollo.mState.selectedIconIndex=" + mState.selectedIconIndex);
Log.d(TAG, "mRollo.mState.selectedIconTexture=" + mState.selectedIconTexture);
Log.d(TAG, "mRollo.mState.zoomTarget=" + mState.zoomTarget);
Log.d(TAG, "mRollo.mState.homeButtonId=" + mState.homeButtonId);
Log.d(TAG, "mRollo.mState.targetPos=" + mState.targetPos);
Log.d(TAG, "mRollo.mParams.bubbleWidth=" + mParams.bubbleWidth);
Log.d(TAG, "mRollo.mParams.bubbleHeight=" + mParams.bubbleHeight);
Log.d(TAG, "mRollo.mParams.bubbleBitmapWidth=" + mParams.bubbleBitmapWidth);
Log.d(TAG, "mRollo.mParams.bubbleBitmapHeight=" + mParams.bubbleBitmapHeight);
Log.d(TAG, "mRollo.mParams.homeButtonWidth=" + mParams.homeButtonWidth);
Log.d(TAG, "mRollo.mParams.homeButtonHeight=" + mParams.homeButtonHeight);
Log.d(TAG, "mRollo.mParams.homeButtonTextureWidth=" + mParams.homeButtonTextureWidth);
Log.d(TAG, "mRollo.mParams.homeButtonTextureHeight=" + mParams.homeButtonTextureHeight);
}
}
public void dumpState() {
Log.d(TAG, "mRS=" + mRS);
Log.d(TAG, "mRollo=" + mRollo);
ApplicationInfo.dumpApplicationInfoList(TAG, "mAllAppsList", mAllAppsList);
Log.d(TAG, "mArrowNavigation=" + mArrowNavigation);
Log.d(TAG, "mStartedScrolling=" + mStartedScrolling);
Log.d(TAG, "mLastSelection=" + mLastSelection);
Log.d(TAG, "mLastSelectedIcon=" + mLastSelectedIcon);
Log.d(TAG, "mVelocityTracker=" + mVelocityTracker);
Log.d(TAG, "mTouchTracking=" + mTouchTracking);
Log.d(TAG, "mShouldGainFocus=" + mShouldGainFocus);
Log.d(TAG, "mZoomDirty=" + mZoomDirty);
Log.d(TAG, "mAnimateNextZoom=" + mAnimateNextZoom);
Log.d(TAG, "mZoom=" + mZoom);
Log.d(TAG, "mPosX=" + mPosX);
Log.d(TAG, "mVelocity=" + mVelocity);
Log.d(TAG, "mMessageProc=" + mMessageProc);
if (mRollo != null) {
mRollo.dumpState();
}
if (mRS != null) {
mRS.contextDump(0);
}
}
}
| false | true | public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean handled = false;
if (!isVisible()) {
return false;
}
final int iconCount = mRollo.mState.iconCount;
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
if (mArrowNavigation) {
if (mLastSelection == SELECTION_HOME) {
reallyPlaySoundEffect(SoundEffectConstants.CLICK);
mLauncher.closeAllApps(true);
} else {
int whichApp = mRollo.mState.selectedIconIndex;
if (whichApp >= 0) {
ApplicationInfo app = mAllAppsList.get(whichApp);
mLauncher.startActivitySafely(app.intent);
handled = true;
}
}
}
}
if (iconCount > 0) {
mArrowNavigation = true;
int currentSelection = mRollo.mState.selectedIconIndex;
int currentTopRow = Math.round(mPosX);
// The column of the current selection, in the range 0..COLUMNS_PER_PAGE-1
final int currentPageCol = currentSelection % Defines.COLUMNS_PER_PAGE;
// The row of the current selection, in the range 0..ROWS_PER_PAGE-1
final int currentPageRow = (currentSelection - (currentTopRow*Defines.COLUMNS_PER_PAGE))
/ Defines.ROWS_PER_PAGE;
int newSelection = currentSelection;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
if (mLastSelection == SELECTION_HOME) {
mRollo.setHomeSelected(SELECTED_NONE);
int lastRowCount = iconCount % Defines.COLUMNS_PER_PAGE;
if (lastRowCount == 0) {
lastRowCount = Defines.COLUMNS_PER_PAGE;
}
newSelection = iconCount - lastRowCount + (Defines.COLUMNS_PER_PAGE / 2);
if (newSelection >= iconCount) {
newSelection = iconCount-1;
}
int target = (newSelection / Defines.COLUMNS_PER_PAGE)
- (Defines.ROWS_PER_PAGE - 1);
if (target < 0) {
target = 0;
}
if (currentTopRow != target) {
mRollo.moveTo(target);
}
} else {
if (currentPageRow > 0) {
newSelection = currentSelection - Defines.COLUMNS_PER_PAGE;
} else if (currentTopRow > 0) {
newSelection = currentSelection - Defines.COLUMNS_PER_PAGE;
mRollo.moveTo(newSelection / Defines.COLUMNS_PER_PAGE);
} else if (currentPageRow != 0) {
newSelection = currentTopRow * Defines.ROWS_PER_PAGE;
}
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN: {
final int rowCount = iconCount / Defines.COLUMNS_PER_PAGE
+ (iconCount % Defines.COLUMNS_PER_PAGE == 0 ? 0 : 1);
final int currentRow = currentSelection / Defines.COLUMNS_PER_PAGE;
if (mLastSelection != SELECTION_HOME) {
if (currentRow < rowCount-1) {
mRollo.setHomeSelected(SELECTED_NONE);
if (currentSelection < 0) {
newSelection = 0;
} else {
newSelection = currentSelection + Defines.COLUMNS_PER_PAGE;
}
if (newSelection >= iconCount) {
// Go from D to G in this arrangement:
// A B C D
// E F G
newSelection = iconCount - 1;
}
if (currentPageRow >= Defines.ROWS_PER_PAGE - 1) {
mRollo.moveTo((newSelection / Defines.COLUMNS_PER_PAGE) -
Defines.ROWS_PER_PAGE + 1);
}
} else {
newSelection = -1;
mRollo.setHomeSelected(SELECTED_FOCUSED);
}
}
handled = true;
break;
}
case KeyEvent.KEYCODE_DPAD_LEFT:
if (currentPageCol > 0) {
newSelection = currentSelection - 1;
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if ((currentPageCol < Defines.COLUMNS_PER_PAGE - 1) &&
(currentSelection < iconCount - 1)) {
newSelection = currentSelection + 1;
}
handled = true;
break;
}
if (newSelection != currentSelection) {
mRollo.selectIcon(newSelection, SELECTED_FOCUSED);
mRollo.mState.save();
}
}
return handled;
}
| public boolean onKeyDown(int keyCode, KeyEvent event) {
boolean handled = false;
if (!isVisible()) {
return false;
}
final int iconCount = mRollo.mState.iconCount;
if (keyCode == KeyEvent.KEYCODE_DPAD_CENTER || keyCode == KeyEvent.KEYCODE_ENTER) {
if (mArrowNavigation) {
if (mLastSelection == SELECTION_HOME) {
reallyPlaySoundEffect(SoundEffectConstants.CLICK);
mLauncher.closeAllApps(true);
} else {
int whichApp = mRollo.mState.selectedIconIndex;
if (whichApp >= 0) {
ApplicationInfo app = mAllAppsList.get(whichApp);
mLauncher.startActivitySafely(app.intent);
handled = true;
}
}
}
}
if (iconCount > 0) {
mArrowNavigation = true;
int currentSelection = mRollo.mState.selectedIconIndex;
int currentTopRow = Math.round(mPosX);
// The column of the current selection, in the range 0..COLUMNS_PER_PAGE-1
final int currentPageCol = currentSelection % Defines.COLUMNS_PER_PAGE;
// The row of the current selection, in the range 0..ROWS_PER_PAGE-1
final int currentPageRow = (currentSelection - (currentTopRow*Defines.COLUMNS_PER_PAGE))
/ Defines.ROWS_PER_PAGE;
int newSelection = currentSelection;
switch (keyCode) {
case KeyEvent.KEYCODE_DPAD_UP:
if (mLastSelection == SELECTION_HOME) {
mRollo.setHomeSelected(SELECTED_NONE);
int lastRowCount = iconCount % Defines.COLUMNS_PER_PAGE;
if (lastRowCount == 0) {
lastRowCount = Defines.COLUMNS_PER_PAGE;
}
newSelection = iconCount - lastRowCount + (Defines.COLUMNS_PER_PAGE / 2);
if (newSelection >= iconCount) {
newSelection = iconCount-1;
}
int target = (newSelection / Defines.COLUMNS_PER_PAGE)
- (Defines.ROWS_PER_PAGE - 1);
if (target < 0) {
target = 0;
}
if (currentTopRow != target) {
mRollo.moveTo(target);
}
} else {
if (currentPageRow > 0) {
newSelection = currentSelection - Defines.COLUMNS_PER_PAGE;
} else if (currentTopRow > 0) {
newSelection = currentSelection - Defines.COLUMNS_PER_PAGE;
mRollo.moveTo(newSelection / Defines.COLUMNS_PER_PAGE);
} else if (currentPageRow != 0) {
newSelection = currentTopRow * Defines.ROWS_PER_PAGE;
}
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_DOWN: {
final int rowCount = iconCount / Defines.COLUMNS_PER_PAGE
+ (iconCount % Defines.COLUMNS_PER_PAGE == 0 ? 0 : 1);
final int currentRow = currentSelection / Defines.COLUMNS_PER_PAGE;
if (mLastSelection != SELECTION_HOME) {
if (currentRow < rowCount-1) {
mRollo.setHomeSelected(SELECTED_NONE);
if (currentSelection < 0) {
newSelection = 0;
} else {
newSelection = currentSelection + Defines.COLUMNS_PER_PAGE;
}
if (newSelection >= iconCount) {
// Go from D to G in this arrangement:
// A B C D
// E F G
newSelection = iconCount - 1;
}
if (currentPageRow >= Defines.ROWS_PER_PAGE - 1) {
mRollo.moveTo((newSelection / Defines.COLUMNS_PER_PAGE) -
Defines.ROWS_PER_PAGE + 1);
}
} else {
newSelection = -1;
mRollo.setHomeSelected(SELECTED_FOCUSED);
}
}
handled = true;
break;
}
case KeyEvent.KEYCODE_DPAD_LEFT:
if (mLastSelection != SELECTION_HOME) {
if (currentPageCol > 0) {
newSelection = currentSelection - 1;
}
}
handled = true;
break;
case KeyEvent.KEYCODE_DPAD_RIGHT:
if (mLastSelection != SELECTION_HOME) {
if ((currentPageCol < Defines.COLUMNS_PER_PAGE - 1) &&
(currentSelection < iconCount - 1)) {
newSelection = currentSelection + 1;
}
}
handled = true;
break;
}
if (newSelection != currentSelection) {
mRollo.selectIcon(newSelection, SELECTED_FOCUSED);
mRollo.mState.save();
}
}
return handled;
}
|
diff --git a/src/xmlvm/org/xmlvm/proc/out/CppOutputProcess.java b/src/xmlvm/org/xmlvm/proc/out/CppOutputProcess.java
index b97993ed..c57b9bfb 100755
--- a/src/xmlvm/org/xmlvm/proc/out/CppOutputProcess.java
+++ b/src/xmlvm/org/xmlvm/proc/out/CppOutputProcess.java
@@ -1,180 +1,180 @@
/*
* Copyright (c) 2004-2009 XMLVM --- An XML-based Programming Language
*
* 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., 675 Mass
* Ave, Cambridge, MA 02139, USA.
*
* For more information, visit the XMLVM Home Page at http://www.xmlvm.org
*/
package org.xmlvm.proc.out;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.Iterator;
import java.util.List;
import org.jdom.Attribute;
import org.jdom.Document;
import org.jdom.Element;
import org.xmlvm.main.Arguments;
import org.xmlvm.proc.XmlvmProcessImpl;
import org.xmlvm.proc.XmlvmResource;
import org.xmlvm.proc.XmlvmResourceProvider;
import org.xmlvm.proc.XsltRunner;
public class CppOutputProcess extends XmlvmProcessImpl<XmlvmResourceProvider> {
private static final String CPP_EXTENSION = ".cpp";
private static final String H_EXTENSION = ".h";
private List<OutputFile> result = new ArrayList<OutputFile>();
public CppOutputProcess(Arguments arguments) {
super(arguments);
// addAllXmlvmEmittingProcessesAsInput();
// We need the special Vtable information in order to be able to produce
// C code.
addSupportedInput(XmlvmJavaRuntimeAnnotationProcess.class);
}
@Override
public List<OutputFile> getOutputFiles() {
return result;
}
@Override
public boolean process() {
List<XmlvmResourceProvider> preprocesses = preprocess();
for (XmlvmResourceProvider process : preprocesses) {
List<XmlvmResource> xmlvmResources = process.getXmlvmResources();
for (XmlvmResource xmlvm : xmlvmResources) {
if (xmlvm != null) {
OutputFile[] files = genCpp(xmlvm);
for (OutputFile file : files) {
file.setLocation(arguments.option_out());
result.add(file);
}
}
}
}
return true;
}
/**
* From the given XmlvmResource creates a header as well as cpp-file.
*/
public OutputFile[] genCpp(XmlvmResource xmlvm) {
Document doc = xmlvm.getXmlvmDocument();
// The filename will be the name of the first class
String namespaceName = xmlvm.getPackageName();
String inheritsFrom = xmlvm.getSuperTypeName().replace('.', '_').replace('$', '_');
String className = xmlvm.getName().replace('$', '_');
String fileNameStem = (namespaceName + "." + className).replace('.', '_');
String headerFileName = fileNameStem + H_EXTENSION;
String mFileName = fileNameStem + CPP_EXTENSION;
StringBuffer headerBuffer = new StringBuffer();
headerBuffer.append("#import \"xmlvm.h\"\n");
for (String i : getTypesForHeader(doc)) {
if (i.equals(inheritsFrom)) {
headerBuffer.append("#import \"" + i + ".h\"\n");
}
}
String interfaces = xmlvm.getInterfaces();
if (interfaces != null) {
for (String i : interfaces.split(",")) {
headerBuffer
.append("#import \"" + i.replace('.', '_').replace('$', '_') + ".h\"\n");
}
}
headerBuffer.append("\n// For circular include:\n");
for (String i : getTypesForHeader(doc)) {
headerBuffer.append("class " + i + ";\n");
}
OutputFile headerFile = XsltRunner.runXSLT("xmlvm2cpp.xsl", doc, new String[][] {
{ "pass", "emitHeader" }, { "header", headerFileName } });
headerFile.setData(headerBuffer.toString() + headerFile.getData());
headerFile.setFileName(headerFileName);
StringBuffer mBuffer = new StringBuffer();
for (String i : getTypesForHeader(doc)) {
String toIgnore = (namespaceName + "_" + className).replace('.', '_');
if (!i.equals(inheritsFrom) && !i.equals(toIgnore)) {
mBuffer.append("#import \"" + i + ".h\"\n");
}
}
OutputFile mFile = XsltRunner.runXSLT("xmlvm2cpp.xsl", doc, new String[][] {
{ "pass", "emitImplementation" }, { "header", headerFileName } });
mFile.setData(mBuffer.toString() + mFile.getData());
mFile.setFileName(mFileName);
return new OutputFile[] { headerFile, mFile };
}
private List<String> getTypesForHeader(Document doc) {
HashSet<String> seen = new HashSet<String>();
@SuppressWarnings("unchecked")
Iterator<Object> i = doc.getDescendants();
while (i.hasNext()) {
Object cur = i.next();
if (cur instanceof Element) {
Attribute a = ((Element) cur).getAttribute("type");
if (a != null) {
seen.add(a.getValue());
}
a = ((Element) cur).getAttribute("extends");
- if (a != null) {
+ if (a != null && !a.getValue().equals("")) {
seen.add(a.getValue());
}
a = ((Element) cur).getAttribute("interfaces");
if (a != null) {
for (String iface : a.getValue().split(",")) {
seen.add(iface);
}
}
a = ((Element) cur).getAttribute("class-type");
if (a != null) {
seen.add(a.getValue());
}
if (((Element) cur).getName().equals("const-class")) {
a = ((Element) cur).getAttribute("value");
if (a != null) {
seen.add(a.getValue());
}
}
a = ((Element) cur).getAttribute("kind");
if (a != null && a.getValue().equals("type")) {
a = ((Element) cur).getAttribute("value");
if (a != null) {
seen.add(a.getValue());
}
}
} else {
System.out.println(cur);
}
}
HashSet<String> bad = new HashSet<String>();
for (String t : new String[] { "char", "float", "double", "int", "void", "boolean",
"short", "byte", "float", "long" }) {
bad.add(t);
}
List<String> toRet = new ArrayList<String>();
for (String t : seen) {
if (!bad.contains(t) && t.indexOf("[]") == -1) {
toRet.add(t.replace('.', '_').replace('$', '_'));
}
}
return toRet;
}
}
| true | true | private List<String> getTypesForHeader(Document doc) {
HashSet<String> seen = new HashSet<String>();
@SuppressWarnings("unchecked")
Iterator<Object> i = doc.getDescendants();
while (i.hasNext()) {
Object cur = i.next();
if (cur instanceof Element) {
Attribute a = ((Element) cur).getAttribute("type");
if (a != null) {
seen.add(a.getValue());
}
a = ((Element) cur).getAttribute("extends");
if (a != null) {
seen.add(a.getValue());
}
a = ((Element) cur).getAttribute("interfaces");
if (a != null) {
for (String iface : a.getValue().split(",")) {
seen.add(iface);
}
}
a = ((Element) cur).getAttribute("class-type");
if (a != null) {
seen.add(a.getValue());
}
if (((Element) cur).getName().equals("const-class")) {
a = ((Element) cur).getAttribute("value");
if (a != null) {
seen.add(a.getValue());
}
}
a = ((Element) cur).getAttribute("kind");
if (a != null && a.getValue().equals("type")) {
a = ((Element) cur).getAttribute("value");
if (a != null) {
seen.add(a.getValue());
}
}
} else {
System.out.println(cur);
}
}
HashSet<String> bad = new HashSet<String>();
for (String t : new String[] { "char", "float", "double", "int", "void", "boolean",
"short", "byte", "float", "long" }) {
bad.add(t);
}
List<String> toRet = new ArrayList<String>();
for (String t : seen) {
if (!bad.contains(t) && t.indexOf("[]") == -1) {
toRet.add(t.replace('.', '_').replace('$', '_'));
}
}
return toRet;
}
| private List<String> getTypesForHeader(Document doc) {
HashSet<String> seen = new HashSet<String>();
@SuppressWarnings("unchecked")
Iterator<Object> i = doc.getDescendants();
while (i.hasNext()) {
Object cur = i.next();
if (cur instanceof Element) {
Attribute a = ((Element) cur).getAttribute("type");
if (a != null) {
seen.add(a.getValue());
}
a = ((Element) cur).getAttribute("extends");
if (a != null && !a.getValue().equals("")) {
seen.add(a.getValue());
}
a = ((Element) cur).getAttribute("interfaces");
if (a != null) {
for (String iface : a.getValue().split(",")) {
seen.add(iface);
}
}
a = ((Element) cur).getAttribute("class-type");
if (a != null) {
seen.add(a.getValue());
}
if (((Element) cur).getName().equals("const-class")) {
a = ((Element) cur).getAttribute("value");
if (a != null) {
seen.add(a.getValue());
}
}
a = ((Element) cur).getAttribute("kind");
if (a != null && a.getValue().equals("type")) {
a = ((Element) cur).getAttribute("value");
if (a != null) {
seen.add(a.getValue());
}
}
} else {
System.out.println(cur);
}
}
HashSet<String> bad = new HashSet<String>();
for (String t : new String[] { "char", "float", "double", "int", "void", "boolean",
"short", "byte", "float", "long" }) {
bad.add(t);
}
List<String> toRet = new ArrayList<String>();
for (String t : seen) {
if (!bad.contains(t) && t.indexOf("[]") == -1) {
toRet.add(t.replace('.', '_').replace('$', '_'));
}
}
return toRet;
}
|
diff --git a/src/main/java/org/diyefi/openlogviewer/graphing/InfoPanel.java b/src/main/java/org/diyefi/openlogviewer/graphing/InfoPanel.java
index 2cae41b..74e272d 100644
--- a/src/main/java/org/diyefi/openlogviewer/graphing/InfoPanel.java
+++ b/src/main/java/org/diyefi/openlogviewer/graphing/InfoPanel.java
@@ -1,155 +1,157 @@
/* OpenLogViewer
*
* Copyright 2011
*
* This file is part of the OpenLogViewer project.
*
* OpenLogViewer software 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.
*
* OpenLogViewer 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 General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with any OpenLogViewer software. If not, see http://www.gnu.org/licenses/
*
* I ask that if you make any changes to this file you fork the code on github.com!
*
*/
package org.diyefi.openlogviewer.graphing;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.event.MouseEvent;
import java.awt.event.MouseListener;
import java.awt.event.MouseMotionListener;
import javax.swing.JPanel;
import org.diyefi.openlogviewer.OpenLogViewerApp;
import org.diyefi.openlogviewer.genericlog.GenericLog;
/**
* @author Bryan Harris and Ben Fenner
*/
public class InfoPanel extends JPanel implements MouseMotionListener, MouseListener {
public InfoPanel() {
genLog = new GenericLog();
xMouseCoord = -100;
yMouseCoord = -100;
mouseOver = false;
this.setOpaque(false);
}
@Override
public void paint(Graphics g) { // override paint because there will be no components in this pane
builtTime += System.currentTimeMillis() - currentTime;
currentTime = System.currentTimeMillis();
if (builtTime <= 1000) {
FPScounter++;
} else {
FPS = FPScounter;
if (FPScounter != 0) {
FPS += (1000 % FPScounter) * 0.001;
}
FPScounter = 0;
builtTime = 0;
}
if (!this.getSize().equals(this.getParent().getSize())) {
this.setSize(this.getParent().getSize());
}
if (genLog.getLogStatus() == GenericLog.LOG_NOT_LOADED) {
g.setColor(Color.RED);
g.drawString("No log loaded, please select a log from the file menu.", 20, 20);
} else if (genLog.getLogStatus() == GenericLog.LOG_LOADING) {
g.setColor(Color.red);
g.drawString("Loading log, please wait...", 20, 20);
} else if (genLog.getLogStatus() == GenericLog.LOG_LOADED) {
Dimension d = this.getSize();
MultiGraphLayeredPane lg = OpenLogViewerApp.getInstance().getMultiGraphLayeredPane();
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("FPS: " + Double.toString(FPS), 30, 60);
if (mouseOver) {
int zoom = OpenLogViewerApp.getInstance().getEntireGraphingPanel().getZoom();
+ double graphPosition = OpenLogViewerApp.getInstance().getEntireGraphingPanel().getGraphPosition();
int center = this.getWidth() / 2;
- // Divide by zoom then multiply by zoom effectively drops the remainder from the mouse coords then the remainder is added back as an offset
- int lineDraw = (((xMouseCoord ) / zoom) * zoom) + (center % zoom);
+ double offset = (graphPosition % 1) * zoom;
+ // Divide by zoom then multiply by zoom effectively drops the remainders from the mouse coords then the remainder is added back as an offset
+ int lineDraw = (((xMouseCoord ) / zoom) * zoom) + (center % zoom) - (int)offset;
g2d.setColor(vertBar);
g2d.drawLine(d.width / 2, 0, d.width / 2, d.height); //center position line
g2d.drawLine(lineDraw, 0, lineDraw, d.height); //mouse cursor line
for (int i = 0; i < lg.getComponentCount(); i++) {
if (lg.getComponent(i) instanceof SingleGraphPanel) {
SingleGraphPanel gl = (SingleGraphPanel) lg.getComponent(i);
g2d.setColor(textBackground);
g2d.fillRect(lineDraw, yMouseCoord + 2 + (15 * i), gl.getMouseInfo(xMouseCoord).toString().length() * 8, 15);
g2d.setColor(gl.getColor());
g2d.drawString(gl.getMouseInfo(xMouseCoord).toString(), lineDraw + 2, yMouseCoord + 15 + (15 * i));
}
}
}
}
}
public void setLog(GenericLog log) {
genLog = log;
repaint();
}
@Override
public void mouseEntered(MouseEvent e) {
mouseOver = true;
}
@Override
public void mouseExited(MouseEvent e) {
mouseOver = false;
repaint();
}
@Override
public void mouseMoved(MouseEvent e) {
xMouseCoord = e.getX();
yMouseCoord = e.getY();
repaint();
}
@Override
public void mouseClicked(MouseEvent arg0) {
}
@Override
public void mousePressed(MouseEvent e) {
}
@Override
public void mouseReleased(MouseEvent e) {
}
@Override
public void mouseDragged(MouseEvent e) {
}
int FPScounter = 0;
int FPS = 0;
private long currentTime;
private long builtTime;
private GenericLog genLog;
private Color vertBar = new Color(255, 255, 255, 100);
private Color textBackground = new Color(0, 0, 0, 170);
private int xMouseCoord;
private int yMouseCoord;
boolean mouseOver;
private static final long serialVersionUID = -6657156551430700622L;
}
| false | true | public void paint(Graphics g) { // override paint because there will be no components in this pane
builtTime += System.currentTimeMillis() - currentTime;
currentTime = System.currentTimeMillis();
if (builtTime <= 1000) {
FPScounter++;
} else {
FPS = FPScounter;
if (FPScounter != 0) {
FPS += (1000 % FPScounter) * 0.001;
}
FPScounter = 0;
builtTime = 0;
}
if (!this.getSize().equals(this.getParent().getSize())) {
this.setSize(this.getParent().getSize());
}
if (genLog.getLogStatus() == GenericLog.LOG_NOT_LOADED) {
g.setColor(Color.RED);
g.drawString("No log loaded, please select a log from the file menu.", 20, 20);
} else if (genLog.getLogStatus() == GenericLog.LOG_LOADING) {
g.setColor(Color.red);
g.drawString("Loading log, please wait...", 20, 20);
} else if (genLog.getLogStatus() == GenericLog.LOG_LOADED) {
Dimension d = this.getSize();
MultiGraphLayeredPane lg = OpenLogViewerApp.getInstance().getMultiGraphLayeredPane();
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("FPS: " + Double.toString(FPS), 30, 60);
if (mouseOver) {
int zoom = OpenLogViewerApp.getInstance().getEntireGraphingPanel().getZoom();
int center = this.getWidth() / 2;
// Divide by zoom then multiply by zoom effectively drops the remainder from the mouse coords then the remainder is added back as an offset
int lineDraw = (((xMouseCoord ) / zoom) * zoom) + (center % zoom);
g2d.setColor(vertBar);
g2d.drawLine(d.width / 2, 0, d.width / 2, d.height); //center position line
g2d.drawLine(lineDraw, 0, lineDraw, d.height); //mouse cursor line
for (int i = 0; i < lg.getComponentCount(); i++) {
if (lg.getComponent(i) instanceof SingleGraphPanel) {
SingleGraphPanel gl = (SingleGraphPanel) lg.getComponent(i);
g2d.setColor(textBackground);
g2d.fillRect(lineDraw, yMouseCoord + 2 + (15 * i), gl.getMouseInfo(xMouseCoord).toString().length() * 8, 15);
g2d.setColor(gl.getColor());
g2d.drawString(gl.getMouseInfo(xMouseCoord).toString(), lineDraw + 2, yMouseCoord + 15 + (15 * i));
}
}
}
}
}
| public void paint(Graphics g) { // override paint because there will be no components in this pane
builtTime += System.currentTimeMillis() - currentTime;
currentTime = System.currentTimeMillis();
if (builtTime <= 1000) {
FPScounter++;
} else {
FPS = FPScounter;
if (FPScounter != 0) {
FPS += (1000 % FPScounter) * 0.001;
}
FPScounter = 0;
builtTime = 0;
}
if (!this.getSize().equals(this.getParent().getSize())) {
this.setSize(this.getParent().getSize());
}
if (genLog.getLogStatus() == GenericLog.LOG_NOT_LOADED) {
g.setColor(Color.RED);
g.drawString("No log loaded, please select a log from the file menu.", 20, 20);
} else if (genLog.getLogStatus() == GenericLog.LOG_LOADING) {
g.setColor(Color.red);
g.drawString("Loading log, please wait...", 20, 20);
} else if (genLog.getLogStatus() == GenericLog.LOG_LOADED) {
Dimension d = this.getSize();
MultiGraphLayeredPane lg = OpenLogViewerApp.getInstance().getMultiGraphLayeredPane();
Graphics2D g2d = (Graphics2D) g;
g2d.drawString("FPS: " + Double.toString(FPS), 30, 60);
if (mouseOver) {
int zoom = OpenLogViewerApp.getInstance().getEntireGraphingPanel().getZoom();
double graphPosition = OpenLogViewerApp.getInstance().getEntireGraphingPanel().getGraphPosition();
int center = this.getWidth() / 2;
double offset = (graphPosition % 1) * zoom;
// Divide by zoom then multiply by zoom effectively drops the remainders from the mouse coords then the remainder is added back as an offset
int lineDraw = (((xMouseCoord ) / zoom) * zoom) + (center % zoom) - (int)offset;
g2d.setColor(vertBar);
g2d.drawLine(d.width / 2, 0, d.width / 2, d.height); //center position line
g2d.drawLine(lineDraw, 0, lineDraw, d.height); //mouse cursor line
for (int i = 0; i < lg.getComponentCount(); i++) {
if (lg.getComponent(i) instanceof SingleGraphPanel) {
SingleGraphPanel gl = (SingleGraphPanel) lg.getComponent(i);
g2d.setColor(textBackground);
g2d.fillRect(lineDraw, yMouseCoord + 2 + (15 * i), gl.getMouseInfo(xMouseCoord).toString().length() * 8, 15);
g2d.setColor(gl.getColor());
g2d.drawString(gl.getMouseInfo(xMouseCoord).toString(), lineDraw + 2, yMouseCoord + 15 + (15 * i));
}
}
}
}
}
|
diff --git a/exact-binding/src/main/java/com/thoratou/exact/bom/XmlExtensionReader.java b/exact-binding/src/main/java/com/thoratou/exact/bom/XmlExtensionReader.java
index fd76239..2a6d424 100644
--- a/exact-binding/src/main/java/com/thoratou/exact/bom/XmlExtensionReader.java
+++ b/exact-binding/src/main/java/com/thoratou/exact/bom/XmlExtensionReader.java
@@ -1,81 +1,81 @@
/*****************************************************************************
* This source file is part of SBS (Screen Build System), *
* which is a component of Screen Framework *
* *
* Copyright (c) 2008-2013 Ratouit Thomas *
* *
* 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., 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA, or go to *
* http://www.gnu.org/copyleft/lesser.txt. *
*****************************************************************************/
package com.thoratou.exact.bom;
import com.thoratou.exact.Entry;
import com.thoratou.exact.exception.ExactReadException;
import com.thoratou.exact.fields.FieldBase;
import com.thoratou.exact.fields.FieldExtensionList;
import org.jdom.Element;
import java.util.HashMap;
public abstract class XmlExtensionReader<T extends FieldBase<String> & Entry<T>> {
private final HashMap<T, InnerExtension<T>> extensionMap;
private final HashMap<T,XmlReader> extensionReaderMap;
private T filterField;
protected XmlExtensionReader(T filterField){
this.filterField = filterField;
extensionMap = new HashMap<T, InnerExtension<T>>();
extensionReaderMap = new HashMap<T, XmlReader>();
}
public void registerExtension(InnerExtension<T> prototype, XmlReader reader){
T filter = prototype.getExtensionFilter();
extensionMap.put(filter, prototype);
extensionReaderMap.put(filter, reader);
}
public InnerExtension<T> allocateFromFilter(FieldExtensionList<T> extensionList, T filter){
if(extensionMap.containsKey(filter))
{
InnerExtension<T> extension = extensionMap.get(filter);
return extensionList.allocate(extension);
}
return null;
}
protected void setFilterField(String value){
filterField.set(value);
}
protected abstract void readFilter(final org.jdom.Element rootElement)
throws com.thoratou.exact.exception.ExactReadException;
- public void read(Element rootElement, FieldExtensionList<T> extensionList) throws ExactReadException {
+ public void read(FieldExtensionList<T> extensionList, Element rootElement) throws ExactReadException {
readFilter(rootElement);
if(!filterField.isEmpty()){
InnerExtension<T> extension = allocateFromFilter(extensionList, filterField);
if(extension != null)
{
if(extensionReaderMap.containsKey(filterField))
{
XmlReader<InnerExtension<T>> reader = extensionReaderMap.get(filterField);
reader.read(extension, rootElement);
}
}
filterField.set(null);
}
}
}
| true | true | public void read(Element rootElement, FieldExtensionList<T> extensionList) throws ExactReadException {
readFilter(rootElement);
if(!filterField.isEmpty()){
InnerExtension<T> extension = allocateFromFilter(extensionList, filterField);
if(extension != null)
{
if(extensionReaderMap.containsKey(filterField))
{
XmlReader<InnerExtension<T>> reader = extensionReaderMap.get(filterField);
reader.read(extension, rootElement);
}
}
filterField.set(null);
}
}
| public void read(FieldExtensionList<T> extensionList, Element rootElement) throws ExactReadException {
readFilter(rootElement);
if(!filterField.isEmpty()){
InnerExtension<T> extension = allocateFromFilter(extensionList, filterField);
if(extension != null)
{
if(extensionReaderMap.containsKey(filterField))
{
XmlReader<InnerExtension<T>> reader = extensionReaderMap.get(filterField);
reader.read(extension, rootElement);
}
}
filterField.set(null);
}
}
|
diff --git a/work-swing-api/src/main/java/org/cytoscape/work/swing/AbstractGUITunableHandler.java b/work-swing-api/src/main/java/org/cytoscape/work/swing/AbstractGUITunableHandler.java
index 9ec966ae..b01f7d4f 100644
--- a/work-swing-api/src/main/java/org/cytoscape/work/swing/AbstractGUITunableHandler.java
+++ b/work-swing-api/src/main/java/org/cytoscape/work/swing/AbstractGUITunableHandler.java
@@ -1,256 +1,256 @@
package org.cytoscape.work.swing;
import java.awt.Component;
import java.awt.Container;
import java.lang.reflect.Field;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.LinkedList;
import java.util.List;
import javax.swing.JPanel;
import org.cytoscape.work.AbstractTunableHandler;
import org.cytoscape.work.Tunable;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/** Base class for the various Swing implementations of <code>TunableHandler</code>.
* @CyAPI.Abstract.Class
*/
public abstract class AbstractGUITunableHandler
extends AbstractTunableHandler implements GUITunableHandler
{
private static final Logger logger = LoggerFactory.getLogger(AbstractGUITunableHandler.class);
/**
* If true, the associated GUI element should be laid out next to others in the same group,
* if false, it should be vertically stacked relative to the others.
*/
protected boolean horizontal;
/** <code>JPanel</code> that will contain the GUI representation of the <code>TunableHandler</code>. */
protected JPanel panel;
/**
* <pre>
* If this <code>Tunable</code> has a dependency on another <code>Tunable</code>,
* it represents the name of this dependency (i.e name of the other <code>Tunable</code>
* </pre>
*/
private String dependencyName;
/**
* <pre>
* Represents the value of the dependency.
* Could be : "true, false, an item of a <code>ListSelection</code>, a value ..."
* </pre>
* Either mustMatch is non-empty and mustNotMatch, or vice versa, or both are null if there is no dependency.
*/
private String mustMatch;
private String mustNotMatch;
/**
* The list of GUITunableHandlers that depend on THIS GUITunableHandler.
*/
private List<GUITunableHandler> dependents;
/**
* The list of GUITunableHandlers that are listening for changes on THIS GUITunableHandler.
*/
private List<GUITunableHandler> listeners;
/** Standard base class constructor for <code>TunableHandler</code>s that deal with
* <code>Tunable</code>s that annotate a field.
*
* @param field An instance of <code>Field</code> that represents a field annotated with <code>@Tunable</code>
* @param instance An object instance that contains a field corresponding to the <i>field</i> parameter
* @param tunable The <code>Tunable</code> that annotates <i>field</i>
*/
protected AbstractGUITunableHandler(final Field field, final Object instance, final Tunable tunable) {
super(field, instance, tunable);
init();
}
/** Standard base class constructor for <code>TunableHandler</code>s that deal with
* <code>Tunable</code>s that use getter and setter methods.
*
* @param getter The getter method of the tunable object represented by the <i>instance</i> parameter.
* @param setter The setter method complimentary to the getter.
* @param instance An instance of an object with a getter method that has been determined to be annotated with <code>@Tunable</code>.
* @param tunable The <code>Tunable</code> that annotates the <i>getter</i>.
*/
protected AbstractGUITunableHandler(final Method getter, final Method setter, final Object instance, final Tunable tunable) {
super(getter, setter, instance, tunable);
init();
}
private void init() {
final String alignment = getParams().getProperty("alignments", "vertical");
horizontal = false;
if (alignment.equalsIgnoreCase("horizontal"))
horizontal = true;
else if (!alignment.equalsIgnoreCase("vertical"))
logger.warn("\"alignments\" was specified but is neither \"horizontal\" nor \"vertical\".");
String s = dependsOn();
if (!s.isEmpty()) {
if (!s.contains("!=")) {
dependencyName = s.substring(0, s.indexOf("="));
mustMatch = s.substring(s.indexOf("=") + 1);
mustNotMatch = "";
} else {
- dependencyName = s.substring(0, s.indexOf("."));
+ dependencyName = s.substring(0, s.indexOf("!"));
mustNotMatch = s.substring(s.indexOf("=") + 1);
mustMatch = "";
}
}
dependents = new LinkedList<GUITunableHandler>();
listeners = new LinkedList<GUITunableHandler>();
panel = new JPanel();
}
public void setValue(final Object newValue) throws IllegalAccessException, InvocationTargetException{
super.setValue(newValue);
notifyDependents();
notifyChangeListeners();
}
/**
* Notifies all dependents that this object has changed.
*/
public void notifyDependents() {
String state = getState();
String name = getName();
for (GUITunableHandler gh : dependents)
gh.checkDependency(name, state);
}
/**
* Notifies all dependents that this object has changed.
*/
public void notifyChangeListeners() {
String state = getState();
String name = getName();
for (GUITunableHandler gh : listeners)
gh.changeOccurred(name, state);
}
/**
* Adds the argument as a new dependency to this <code>GUITunableHandler</code>.
* @param gh <code>Handler</code> on which this one will depend on
*/
public void addChangeListener(GUITunableHandler gh) {
if (!listeners.contains(gh))
listeners.add(gh);
}
/**
* Adds the argument as a new dependency to this <code>GUITunableHandler</code>.
* @param gh <code>Handler</code> on which this one will depend on
*/
public void addDependent(GUITunableHandler gh) {
if (!dependents.contains(gh))
dependents.add(gh);
}
/** {@inheritDoc} */
public String getDependency() {
return dependencyName;
}
/** {@inheritDoc} */
public String[] getChangeSources() {
return listenForChange();
}
/** {@inheritDoc} */
public final void changeOccurred(final String name, final String state) {
update();
}
/** {@inheritDoc} */
public final void checkDependency(final String depName, final String depState) {
// if we don't depend on anything, then we should be enabled
if (dependencyName == null || mustMatch == null) {
setEnabledContainer(true, panel);
return;
}
// if the dependency name matches ...
if (dependencyName.equals(depName)) {
// ... and the state matches, then enable
if (!mustMatch.isEmpty()) {
if (mustMatch.equals(depState))
setEnabledContainer(true, panel);
else // ... and the state doesn't match, then disable
setEnabledContainer(false, panel);
} else {
if (!mustNotMatch.equals(depState))
setEnabledContainer(true, panel);
else // ... and the state doesn't match, then disable
setEnabledContainer(false, panel);
}
}
return;
}
/**
* Enables or disables a container and all its children.
*
* @param enable whether to enable the container or not
* @param container the container that will be enabled or not
*/
private void setEnabledContainer(final boolean enable, final Container container) {
container.setEnabled(enable);
for (final Component child : container.getComponents()) {
if (child instanceof Container)
setEnabledContainer(enable, (Container)child);
else
child.setEnabled(enable);
}
}
/**
* Returns the panel associated with this <code>GUITunableHandler</code>.
* @return the <code>JPanel</code> container of this <code>GUITunableHandler</code>
*/
public JPanel getJPanel() {
return panel;
}
/** {@inheritDoc} */
public abstract void handle();
/**
* The default implementation is a no-op. You should override this method if
* you want your tunable to update.
*/
public void update() { }
/** Returns a string representation of the value of the <code>Tunable</code> associated with
* this <code>GUITunableHandler</code>.
*
* @return the current value of the associated <code>Tunable</code> represented as a string
*/
public String getState() {
try {
final Object value = getValue();
return value == null ? "" : value.toString();
} catch (final Exception e) {
logger.warn("Could not get state.", e);
return "";
}
}
}
| true | true | private void init() {
final String alignment = getParams().getProperty("alignments", "vertical");
horizontal = false;
if (alignment.equalsIgnoreCase("horizontal"))
horizontal = true;
else if (!alignment.equalsIgnoreCase("vertical"))
logger.warn("\"alignments\" was specified but is neither \"horizontal\" nor \"vertical\".");
String s = dependsOn();
if (!s.isEmpty()) {
if (!s.contains("!=")) {
dependencyName = s.substring(0, s.indexOf("="));
mustMatch = s.substring(s.indexOf("=") + 1);
mustNotMatch = "";
} else {
dependencyName = s.substring(0, s.indexOf("."));
mustNotMatch = s.substring(s.indexOf("=") + 1);
mustMatch = "";
}
}
dependents = new LinkedList<GUITunableHandler>();
listeners = new LinkedList<GUITunableHandler>();
panel = new JPanel();
}
| private void init() {
final String alignment = getParams().getProperty("alignments", "vertical");
horizontal = false;
if (alignment.equalsIgnoreCase("horizontal"))
horizontal = true;
else if (!alignment.equalsIgnoreCase("vertical"))
logger.warn("\"alignments\" was specified but is neither \"horizontal\" nor \"vertical\".");
String s = dependsOn();
if (!s.isEmpty()) {
if (!s.contains("!=")) {
dependencyName = s.substring(0, s.indexOf("="));
mustMatch = s.substring(s.indexOf("=") + 1);
mustNotMatch = "";
} else {
dependencyName = s.substring(0, s.indexOf("!"));
mustNotMatch = s.substring(s.indexOf("=") + 1);
mustMatch = "";
}
}
dependents = new LinkedList<GUITunableHandler>();
listeners = new LinkedList<GUITunableHandler>();
panel = new JPanel();
}
|
diff --git a/src/org/apache/xerces/validators/dtd/DTDValidator.java b/src/org/apache/xerces/validators/dtd/DTDValidator.java
index 6fcb2585..9eff6027 100644
--- a/src/org/apache/xerces/validators/dtd/DTDValidator.java
+++ b/src/org/apache/xerces/validators/dtd/DTDValidator.java
@@ -1,2988 +1,2992 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 1999 The Apache Software Foundation. All rights
* reserved.
*
* Redistribution and use in source and binary forms, with or without
* modification, are permitted provided that the following conditions
* are met:
*
* 1. Redistributions of source code must retain the above copyright
* notice, this list of conditions and the following disclaimer.
*
* 2. Redistributions in binary form must reproduce the above copyright
* notice, this list of conditions and the following disclaimer in
* the documentation and/or other materials provided with the
* distribution.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact [email protected].
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.apache.org. For more
* information on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
package org.apache.xerces.validators.dtd;
import org.apache.xerces.framework.XMLAttrList;
import org.apache.xerces.framework.XMLContentSpecNode;
import org.apache.xerces.framework.XMLErrorReporter;
import org.apache.xerces.framework.XMLValidator;
import org.apache.xerces.readers.XMLEntityHandler;
import org.apache.xerces.utils.ChunkyCharArray;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.utils.StringPool;
import org.apache.xerces.utils.XMLCharacterProperties;
import org.apache.xerces.utils.XMLMessages;
import org.apache.xerces.utils.ImplementationMessages;
import org.xml.sax.Locator;
import org.xml.sax.InputSource;
import org.xml.sax.SAXParseException;
import java.util.StringTokenizer;
import java.util.Stack;
import java.util.Enumeration;
import java.util.Hashtable;
// for scanning DTD
import org.apache.xerces.framework.XMLDTDScanner;
public final class DTDValidator
implements XMLValidator,
XMLDTDScanner.EventHandler,
NamespacesScope.NamespacesHandler
{
//
// Debugging options
//
private static final boolean PRINT_EXCEPTION_STACK_TRACE = false;
private static final boolean DEBUG_PRINT_ATTRIBUTES = false;
private static final boolean DEBUG_PRINT_CONTENT = false;
//
//
//
private XMLDTDScanner fDTDScanner = null;
protected StringPool fStringPool = null; // protected for use by AttributeValidator classes.
private XMLErrorReporter fErrorReporter = null;
private XMLEntityHandler fEntityHandler = null;
//
//
//
protected boolean fValidating = false; // protected for use by AttributeValidator classes.
private boolean fValidationEnabled = false;
private boolean fDynamicValidation = false;
private boolean fValidationEnabledByDynamic = false;
private boolean fDynamicDisabledByValidation = false;
private boolean fWarningOnDuplicateAttDef = false;
private boolean fWarningOnUndeclaredElements = false;
private EntityPool fEntityPool = null;
private int fStandaloneReader = -1;
private int[] fElementTypeStack = new int[8];
private int[] fElementIndexStack = new int[8];
private int[] fContentSpecTypeStack = new int[8];
private int[] fElementChildCount = new int[8];
private int[][] fElementChildren = new int[8][];
private int fElementDepth = -1;
private boolean fNamespacesEnabled = false;
private NamespacesScope fNamespacesScope = null;
private int fNamespacesPrefix = -1;
private int fRootElementType = -1;
private int fAttrIndex = -1;
private int fElementDeclCount = 0;
private int fAttlistDeclCount = 0;
private int fCurrentElementType = -1;
private int fCurrentElementIndex = -1;
private int fCurrentContentSpecType = -1;
//
private boolean fSeenDoctypeDecl = false;
private EventHandler fEventHandler = null;
private EntityPool fParameterEntityPool = null;
private int fEMPTYSymbol = -1;
private int fANYSymbol = -1;
private int fMIXEDSymbol = -1;
private int fCHILDRENSymbol = -1;
private int fCDATASymbol = -1;
private int fIDSymbol = -1;
private int fIDREFSymbol = -1;
private int fIDREFSSymbol = -1;
private int fENTITYSymbol = -1;
private int fENTITIESSymbol = -1;
private int fNMTOKENSymbol = -1;
private int fNMTOKENSSymbol = -1;
private int fNOTATIONSymbol = -1;
private int fENUMERATIONSymbol = -1;
private int fREQUIREDSymbol = -1;
private int fFIXEDSymbol = -1;
private int fEpsilonIndex = -1;
//
//
//
public interface EventHandler {
/**
* Tell the handler that validation is happening
*
* @param flag true if validation is occuring
*/
public void setValidating(boolean flag) throws Exception;
/**
* callback for the start of the DTD
* This function will be called when a <!DOCTYPE...> declaration is
* encountered.
*
* @param rootElementType element handle for the root element of the document
* @param publicId string pool index of the DTD's public ID
* @param systemId string pool index of the DTD's system ID
* @exception java.lang.Exception
*/
public void startDTD(int rootElementType, int publicId, int systemId) throws Exception;
/**
* callback for the end of the DTD
* This function will be called at the end of the DTD.
*/
public void endDTD() throws Exception;
/**
* callback for an element declaration.
*
* @param elementType element handle of the element being declared
* @param contentSpec contentSpec for the element being declared
* @see org.apache.xerces.framework.XMLValidator.ContentSpec
* @exception java.lang.Exception
*/
public void elementDecl(int elementType, XMLValidator.ContentSpec contentSpec) throws Exception;
/**
* callback for an attribute list declaration.
*
* @param elementType element handle for the attribute's element
* @param attrName string pool index of the attribute name
* @param attType type of attribute
* @param enumString String representing the values of the enumeration,
* if the attribute is of enumerated type, or null if it is not.
* @param attDefaultType an integer value denoting the DefaultDecl value
* @param attDefaultValue string pool index of this attribute's default value
* or -1 if there is no defaultvalue
* @exception java.lang.Exception
*/
public void attlistDecl(int elementType,
int attrName,
int attType,
String enumString,
int attDefaultType,
int attDefaultValue) throws Exception;
/**
* callback for an internal parameter entity declaration.
*
* @param entityName string pool index of the entity name
* @param entityValue string pool index of the entity replacement text
* @exception java.lang.Exception
*/
public void internalPEDecl(int entityName, int entityValue) throws Exception;
/**
* callback for an external parameter entity declaration.
*
* @param entityName string pool index of the entity name
* @param publicId string pool index of the entity's public id.
* @param systemId string pool index of the entity's system id.
* @exception java.lang.Exception
*/
public void externalPEDecl(int entityName, int publicId, int systemId) throws Exception;
/**
* callback for internal general entity declaration.
*
* @param entityName string pool index of the entity name
* @param entityValue string pool index of the entity replacement text
* @exception java.lang.Exception
*/
public void internalEntityDecl(int entityName, int entityValue) throws Exception;
/**
* callback for external general entity declaration.
*
* @param entityName string pool index of the entity name
* @param publicId string pool index of the entity's public id.
* @param systemId string pool index of the entity's system id.
* @exception java.lang.Exception
*/
public void externalEntityDecl(int entityName, int publicId, int systemId) throws Exception;
/**
* callback for an unparsed entity declaration.
*
* @param entityName string pool index of the entity name
* @param publicId string pool index of the entity's public id.
* @param systemId string pool index of the entity's system id.
* @param notationName string pool index of the notation name.
* @exception java.lang.Exception
*/
public void unparsedEntityDecl(int entityName, int publicId, int systemId, int notationName) throws Exception;
/**
* callback for a notation declaration.
*
* @param notationName string pool index of the notation name
* @param publicId string pool index of the notation's public id.
* @param systemId string pool index of the notation's system id.
* @exception java.lang.Exception
*/
public void notationDecl(int notationName, int publicId, int systemId) throws Exception;
/**
* Callback for comment in DTD.
*
* @param comment the string pool index of the comment text
* @exception java.lang.Exception
*/
public void commentInDTD(int dataIndex) throws Exception;
/**
* Callback for processing instruction in DTD.
*
* @param target the string pool index of the PI's target
* @param data the string pool index of the PI's data
* @exception java.lang.Exception
*/
public void processingInstructionInDTD(int targetIndex, int dataIndex) throws Exception;
/**
* callback for the start of a namespace declaration scope.
*
* @param prefix string pool index of the namespace prefix being declared
* @param uri string pool index of the namespace uri begin bound
* @param java.lang.Exception
*/
public void startNamespaceDeclScope(int prefix, int uri) throws Exception;
/**
* callback for the end a namespace declaration scope.
*
* @param prefix string pool index of the namespace prefix being declared
* @exception java.lang.Exception
*/
public void endNamespaceDeclScope(int prefix) throws Exception;
/**
* Supports DOM Level 2 internalSubset addition.
* Called when the internal subset is completely scanned.
*/
public void internalSubset(int internalSubset);
}
//
//
//
public DTDValidator(EventHandler eventHandler,
StringPool stringPool,
XMLErrorReporter errorReporter,
XMLEntityHandler entityHandler)
{
fEventHandler = eventHandler;
fStringPool = stringPool;
fErrorReporter = errorReporter;
fEntityHandler = entityHandler;
fDTDScanner = new XMLDTDScanner(this, fStringPool, fErrorReporter, fEntityHandler, new ChunkyCharArray(fStringPool));
fEntityPool = new EntityPool(fStringPool, fErrorReporter, true);
init();
}
//
//
//
public void reset(StringPool stringPool) throws Exception
{
fStringPool = stringPool;
fDTDScanner.reset(stringPool, new ChunkyCharArray(fStringPool));
setValidating(fValidationEnabled);
fValidationEnabledByDynamic = false;
fDynamicDisabledByValidation = false;
fEntityPool.reset(fStringPool);
poolReset();
fStandaloneReader = -1;
fElementDepth = -1;
fSeenDoctypeDecl = false;
fParameterEntityPool = null;
fNamespacesScope = null;
fNamespacesPrefix = -1;
fRootElementType = -1;
fAttrIndex = -1;
fElementDeclCount = 0;
fAttlistDeclCount = 0;
init();
}
//
//
//
private void init() {
fEMPTYSymbol = fStringPool.addSymbol("EMPTY");
fANYSymbol = fStringPool.addSymbol("ANY");
fMIXEDSymbol = fStringPool.addSymbol("MIXED");
fCHILDRENSymbol = fStringPool.addSymbol("CHILDREN");
fCDATASymbol = fStringPool.addSymbol("CDATA");
fIDSymbol = fStringPool.addSymbol("ID");
fIDREFSymbol = fStringPool.addSymbol("IDREF");
fIDREFSSymbol = fStringPool.addSymbol("IDREFS");
fENTITYSymbol = fStringPool.addSymbol("ENTITY");
fENTITIESSymbol = fStringPool.addSymbol("ENTITIES");
fNMTOKENSymbol = fStringPool.addSymbol("NMTOKEN");
fNMTOKENSSymbol = fStringPool.addSymbol("NMTOKENS");
fNOTATIONSymbol = fStringPool.addSymbol("NOTATION");
fENUMERATIONSymbol = fStringPool.addSymbol("ENUMERATION");
fREQUIREDSymbol = fStringPool.addSymbol("#REQUIRED");
fFIXEDSymbol = fStringPool.addSymbol("#FIXED");
fEpsilonIndex = fStringPool.addSymbol("<<CMNODE_EPSILON>>");
}
//
// Turning on validation/dynamic turns on validation if it is off, and this
// is remembered. Turning off validation DISABLES validation/dynamic if it
// is on. Turning off validation/dynamic DOES NOT turn off validation if it
// was explicitly turned on, only if it was turned on BECAUSE OF the call to
// turn validation/dynamic on. Turning on validation will REENABLE and turn
// validation/dynamic back on if it was disabled by a call that turned off
// validation while validation/dynamic was enabled.
//
public void setValidationEnabled(boolean flag) throws Exception {
fValidationEnabled = flag;
fValidationEnabledByDynamic = false;
if (fValidationEnabled) {
if (fDynamicDisabledByValidation) {
fDynamicValidation = true;
fDynamicDisabledByValidation = false;
}
} else if (fDynamicValidation) {
fDynamicValidation = false;
fDynamicDisabledByValidation = true;
}
setValidating(fValidationEnabled);
}
public boolean getValidationEnabled() {
return fValidationEnabled;
}
public void setDynamicValidationEnabled(boolean flag) throws Exception {
fDynamicValidation = flag;
fDynamicDisabledByValidation = false;
if (!fDynamicValidation) {
if (fValidationEnabledByDynamic) {
fValidationEnabled = false;
fValidationEnabledByDynamic = false;
}
} else if (!fValidationEnabled) {
fValidationEnabled = true;
fValidationEnabledByDynamic = true;
}
setValidating(fValidationEnabled);
}
public boolean getDynamicValidationEnabled() {
return fDynamicValidation;
}
private void setValidating(boolean flag) throws Exception {
fValidating = flag;
fEventHandler.setValidating(flag);
}
public void setNamespacesEnabled(boolean flag) {
fNamespacesEnabled = flag;
}
public boolean getNamespacesEnabled() {
return fNamespacesEnabled;
}
public void startNamespaceDeclScope(int prefix, int uri) throws Exception {
fEventHandler.startNamespaceDeclScope(prefix, uri);
}
public void endNamespaceDeclScope(int prefix) throws Exception {
fEventHandler.endNamespaceDeclScope(prefix);
}
public void internalSubset(int internalSubset) {
fEventHandler.internalSubset(internalSubset);
}
public void setWarningOnDuplicateAttDef(boolean flag) {
fWarningOnDuplicateAttDef = flag;
}
public boolean getWarningOnDuplicateAttDef() {
return fWarningOnDuplicateAttDef;
}
public void setWarningOnUndeclaredElements(boolean flag) {
fWarningOnUndeclaredElements = flag;
}
public boolean getWarningOnUndeclaredElements() {
return fWarningOnUndeclaredElements;
}
private boolean usingStandaloneReader() {
return fStandaloneReader == -1 || fEntityHandler.getReaderId() == fStandaloneReader;
}
protected boolean invalidStandaloneAttDef(int elementType, int attrName) {
if (fStandaloneReader == -1)
return false;
if (elementType == -1) // we are normalizing a default att value... this ok?
return false;
int attDefIndex = getAttDef(elementType, attrName);
return getAttDefIsExternal(attDefIndex);
}
//
// Validator interface
//
public boolean scanDoctypeDecl(boolean standalone) throws Exception {
fSeenDoctypeDecl = true;
fStandaloneReader = standalone ? fEntityHandler.getReaderId() : -1;
if (!fDTDScanner.scanDoctypeDecl()) {
return false;
}
if (fDTDScanner.getReadingExternalEntity()) {
fDTDScanner.scanDecls(true);
}
if (fValidating) {
// check declared elements
if (fWarningOnUndeclaredElements)
checkDeclaredElements();
// check required notations
fEntityPool.checkRequiredNotations();
}
fEventHandler.endDTD();
return true;
}
public void characters(char[] chars, int offset, int length) throws Exception {
if (fValidating) {
charDataInContent();
}
}
public void characters(int stringIndex) throws Exception {
if (fValidating) {
charDataInContent();
}
}
public void ignorableWhitespace(char[] chars, int offset, int length) throws Exception {
if (fStandaloneReader != -1 && fValidating) {
int elementIndex = fCurrentElementIndex;
if (getElementDeclIsExternal(elementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
}
}
public void ignorableWhitespace(int stringIndex) throws Exception {
if (fStandaloneReader != -1 && fValidating) {
int elementIndex = fCurrentElementIndex;
if (getElementDeclIsExternal(elementIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_WHITE_SPACE_IN_ELEMENT_CONTENT_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION);
}
}
}
public int lookupEntity(int entityNameIndex) {
int entityIndex = fEntityPool.lookupEntity(entityNameIndex);
return entityIndex;
}
public boolean externalReferenceInContent(int entityIndex) throws Exception {
boolean external = fEntityPool.isExternalEntity(entityIndex);
if (fStandaloneReader != -1 && fValidating) {
if (external) {
reportRecoverableXMLError(XMLMessages.MSG_EXTERNAL_ENTITY_NOT_PERMITTED,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fEntityPool.getEntityName(entityIndex));
} else if (fEntityPool.getEntityDeclIsExternal(entityIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_REFERENCE_TO_EXTERNALLY_DECLARED_ENTITY_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fEntityPool.getEntityName(entityIndex));
}
}
return external;
}
public int valueOfReferenceInAttValue(int entityIndex) throws Exception {
if (fStandaloneReader != -1 && fValidating && fEntityPool.getEntityDeclIsExternal(entityIndex)) {
reportRecoverableXMLError(XMLMessages.MSG_REFERENCE_TO_EXTERNALLY_DECLARED_ENTITY_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fEntityPool.getEntityName(entityIndex));
}
int entityValue = fEntityPool.getEntityValue(entityIndex);
return entityValue;
}
public boolean isExternalEntity(int entityIndex) {
boolean external = fEntityPool.isExternalEntity(entityIndex);
return external;
}
public boolean isUnparsedEntity(int entityIndex) {
boolean external = fEntityPool.isUnparsedEntity(entityIndex);
return external;
}
public int getEntityValue(int entityIndex) {
int value = fEntityPool.getEntityValue(entityIndex);
return value;
}
public String getPublicIdOfEntity(int entityIndex) {
int publicId = fEntityPool.getPublicId(entityIndex);
return fStringPool.toString(publicId);
}
public String getSystemIdOfEntity(int entityIndex) {
int systemId = fEntityPool.getSystemId(entityIndex);
return fStringPool.toString(systemId);
}
public int lookupParameterEntity(int peNameIndex) throws Exception {
int peIndex = -1;
if (fParameterEntityPool != null)
peIndex = fParameterEntityPool.lookupEntity(peNameIndex);
if (peIndex == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITY_NOT_DECLARED,
XMLMessages.VC_ENTITY_DECLARED,
peNameIndex);
}
return peIndex;
}
public boolean isExternalParameterEntity(int peIndex) {
boolean external = fParameterEntityPool.isExternalEntity(peIndex);
return external;
}
public int getParameterEntityValue(int peIndex) {
int value = fParameterEntityPool.getEntityValue(peIndex);
return value;
}
public String getPublicIdOfParameterEntity(int peIndex) {
int publicId = fParameterEntityPool.getPublicId(peIndex);
return fStringPool.toString(publicId);
}
public String getSystemIdOfParameterEntity(int peIndex) {
int systemId = fParameterEntityPool.getSystemId(peIndex);
return fStringPool.toString(systemId);
}
public void rootElementSpecified(int rootElementType) throws Exception {
if (fDynamicValidation && !fSeenDoctypeDecl) {
setValidating(false);
}
if (fValidating) {
if (fRootElementType != -1 && rootElementType != fRootElementType) {
reportRecoverableXMLError(XMLMessages.MSG_ROOT_ELEMENT_TYPE,
XMLMessages.VC_ROOT_ELEMENT_TYPE,
fRootElementType, rootElementType);
}
}
if (fNamespacesEnabled) {
if (fNamespacesScope == null) {
fNamespacesScope = new NamespacesScope(this);
fNamespacesPrefix = fStringPool.addSymbol("xmlns");
fNamespacesScope.setNamespaceForPrefix(fNamespacesPrefix, -1);
int xmlSymbol = fStringPool.addSymbol("xml");
int xmlNamespace = fStringPool.addSymbol("http://www.w3.org/XML/1998/namespace");
fNamespacesScope.setNamespaceForPrefix(xmlSymbol, xmlNamespace);
}
}
}
public boolean attributeSpecified(int elementType, XMLAttrList attrList, int attrName, Locator attrNameLocator, int attValue) throws Exception {
if (!fValidating && fAttlistDeclCount == 0) {
int attType = fCDATASymbol;
if (fAttrIndex == -1)
fAttrIndex = attrList.startAttrList();
return attrList.addAttr(attrName, attValue, attType, true, true) != -1;
}
int attDefIndex = getAttDef(elementType, attrName);
if (attDefIndex == -1) {
if (fValidating) {
// REVISIT - cache the elem/attr tuple so that we only give
// this error once for each unique occurrence
Object[] args = { fStringPool.toString(elementType),
fStringPool.toString(attrName) };
fErrorReporter.reportError(attrNameLocator,
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ATTRIBUTE_NOT_DECLARED,
XMLMessages.VC_ATTRIBUTE_VALUE_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
int attType = fCDATASymbol;
if (fAttrIndex == -1)
fAttrIndex = attrList.startAttrList();
return attrList.addAttr(attrName, attValue, attType, true, true) != -1;
}
int attType = getAttType(attDefIndex);
if (attType != fCDATASymbol) {
AttributeValidator av = getAttributeValidator(attDefIndex);
int enumHandle = (attType == fNOTATIONSymbol || attType == fENUMERATIONSymbol) ?
getEnumeration(attDefIndex) : -1;
attValue = av.normalize(elementType, attrName, attValue, attType, enumHandle);
}
if (fAttrIndex == -1)
fAttrIndex = attrList.startAttrList();
return attrList.addAttr(attrName, attValue, attType, true, true) != -1;
}
public boolean startElement(int elementType, XMLAttrList attrList) throws Exception {
int attrIndex = fAttrIndex;
fAttrIndex = -1;
if (fElementDeclCount == 0 && fAttlistDeclCount == 0 && !fValidating && !fNamespacesEnabled) {
return false;
}
int elementIndex = fStringPool.getDeclaration(elementType);
int contentSpecType = (elementIndex == -1) ? -1 : getContentSpecType(elementIndex);
if (contentSpecType == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
elementType);
}
if (fAttlistDeclCount != 0 && elementIndex != -1) {
attrIndex = addDefaultAttributes(elementIndex, attrList, attrIndex, fValidating, fStandaloneReader != -1);
}
if (DEBUG_PRINT_ATTRIBUTES) {
String element = fStringPool.toString(elementType);
System.out.print("startElement: <" + element);
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
//
// Namespace support
//
if (fNamespacesEnabled) {
fNamespacesScope.increaseDepth();
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, uri);
} else {
int attPrefix = fStringPool.getPrefixForQName(attName);
if (attPrefix == fNamespacesPrefix) {
attPrefix = fStringPool.getLocalPartForQName(attName);
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(attPrefix, uri);
}
}
index = attrList.getNextAttr(index);
}
}
int prefix = fStringPool.getPrefixForQName(elementType);
int elementURI;
if (prefix == -1) {
elementURI = fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING);
if (elementURI != -1) {
fStringPool.setURIForQName(elementType, elementURI);
}
} else {
elementURI = fNamespacesScope.getNamespaceForPrefix(prefix);
if (elementURI == -1) {
Object[] args = { fStringPool.toString(prefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
fStringPool.setURIForQName(elementType, elementURI);
}
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = fStringPool.getPrefixForQName(attName);
if (attPrefix != fNamespacesPrefix) {
- if (attPrefix == -1) {
- fStringPool.setURIForQName(attName, elementURI);
- } else {
+ //if (attPrefix == -1) {
+ // Confirmed by NS spec, and all IBM devs...
+ // An Attr w/o a prefix should not inherit
+ // the Element's prefix. -rip
+ //fStringPool.setURIForQName(attName, elementURI);
+ //} else {
+ if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
fStringPool.setURIForQName(attName, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
}
if (fElementDepth >= 0) {
int[] children = fElementChildren[fElementDepth];
int childCount = fElementChildCount[fElementDepth];
try {
children[childCount] = elementType;
} catch (NullPointerException ex) {
children = fElementChildren[fElementDepth] = new int[256];
childCount = 0; // should really assert this...
children[childCount] = elementType;
} catch (ArrayIndexOutOfBoundsException ex) {
int[] newChildren = new int[childCount * 2];
System.arraycopy(children, 0, newChildren, 0, childCount);
children = fElementChildren[fElementDepth] = newChildren;
children[childCount] = elementType;
}
fElementChildCount[fElementDepth] = ++childCount;
}
fElementDepth++;
if (fElementDepth == fElementTypeStack.length) {
int[] newStack = new int[fElementDepth * 2];
System.arraycopy(fElementTypeStack, 0, newStack, 0, fElementDepth);
fElementTypeStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fElementIndexStack, 0, newStack, 0, fElementDepth);
fElementIndexStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, fElementDepth);
fContentSpecTypeStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fElementChildCount, 0, newStack, 0, fElementDepth);
fElementChildCount = newStack;
int[][] newContentStack = new int[fElementDepth * 2][];
System.arraycopy(fElementChildren, 0, newContentStack, 0, fElementDepth);
fElementChildren = newContentStack;
}
fCurrentElementType = elementType;
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
fElementTypeStack[fElementDepth] = elementType;
fElementIndexStack[fElementDepth] = elementIndex;
fContentSpecTypeStack[fElementDepth] = contentSpecType;
fElementChildCount[fElementDepth] = 0;
return contentSpecType == fCHILDRENSymbol;
}
public boolean endElement(int elementType) throws Exception {
if (!fValidating && !fNamespacesEnabled && fElementDeclCount == 0 && fAttlistDeclCount == 0) {
return false;
}
if (fValidating) {
int elementIndex = fCurrentElementIndex;
if (elementIndex != -1 && fCurrentContentSpecType != -1) {
int childCount = peekChildCount();
int result = checkContent(elementIndex, childCount, peekChildren());
if (result != -1) {
int majorCode = result != childCount ? XMLMessages.MSG_CONTENT_INVALID : XMLMessages.MSG_CONTENT_INCOMPLETE;
reportRecoverableXMLError(majorCode,
0,
fStringPool.toString(elementType),
getContentSpecAsString(elementIndex));
}
}
}
if (fElementDepth-- < 0)
throw new RuntimeException("VAL001 Element stack underflow");
if (fElementDepth < 0) {
fCurrentElementType = -1;
fCurrentElementIndex = -1;
fCurrentContentSpecType = -1;
//
// Check after document is fully parsed
// (1) check that there was an element with a matching id for every
// IDREF and IDREFS attr (V_IDREF0)
//
if (fValidating && fIdRefs != null)
checkIdRefs();
} else {
fCurrentElementType = fElementTypeStack[fElementDepth];
fCurrentElementIndex = fElementIndexStack[fElementDepth];
fCurrentContentSpecType = fContentSpecTypeStack[fElementDepth];
}
if (fNamespacesEnabled)
fNamespacesScope.decreaseDepth();
return fCurrentContentSpecType == fCHILDRENSymbol;
}
//
// Attribute Normalization/Validation
//
interface AttributeValidator {
int normalize(int elementType, int attrName, int attValue, int attType, int enumHandle) throws Exception;
}
final class AttValidatorCDATA implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
return attValueHandle;
}
}
final class AttValidatorID implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
if (!XMLCharacterProperties.validName(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_ID_INVALID,
XMLMessages.VC_ID,
fStringPool.toString(attrName), newAttValue);
}
//
// ID - check that the id value is unique within the document (V_TAG8)
//
if (elementType != -1 && !addId(attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ID_NOT_UNIQUE,
XMLMessages.VC_ID,
fStringPool.toString(attrName), newAttValue);
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
}
}
final class AttValidatorIDREF implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
if (!XMLCharacterProperties.validName(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_IDREF_INVALID,
XMLMessages.VC_IDREF,
fStringPool.toString(attrName), newAttValue);
}
//
// IDREF - remember the id value
//
if (elementType != -1)
addIdRef(attValueHandle);
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
}
}
final class AttValidatorIDREFS implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String idName = tokenizer.nextToken();
if (fValidating) {
if (!XMLCharacterProperties.validName(idName)) {
ok = false;
}
//
// IDREFS - remember the id values
//
if (elementType != -1)
addIdRef(fStringPool.addSymbol(idName));
}
sb.append(idName);
if (!tokenizer.hasMoreTokens())
break;
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_IDREFS_INVALID,
XMLMessages.VC_IDREF,
fStringPool.toString(attrName), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueHandle = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
}
return attValueHandle;
}
}
final class AttValidatorENTITY implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// ENTITY - check that the value is an unparsed entity name (V_TAGa)
//
int entity = fEntityPool.lookupEntity(attValueHandle);
if (entity == -1 || !fEntityPool.isUnparsedEntity(entity)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITY_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attrName), newAttValue);
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
}
}
final class AttValidatorENTITIES implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String entityName = tokenizer.nextToken();
//
// ENTITIES - check that each value is an unparsed entity name (V_TAGa)
//
if (fValidating) {
int entity = fEntityPool.lookupEntity(fStringPool.addSymbol(entityName));
if (entity == -1 || !fEntityPool.isUnparsedEntity(entity)) {
ok = false;
}
}
sb.append(entityName);
if (!tokenizer.hasMoreTokens())
break;
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_ENTITIES_INVALID,
XMLMessages.VC_ENTITY_NAME,
fStringPool.toString(attrName), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueHandle = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
}
return attValueHandle;
}
}
final class AttValidatorNMTOKEN implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
if (!XMLCharacterProperties.validNmtoken(newAttValue)) {
reportRecoverableXMLError(XMLMessages.MSG_NMTOKEN_INVALID,
XMLMessages.VC_NAME_TOKEN,
fStringPool.toString(attrName), newAttValue);
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
}
}
final class AttValidatorNMTOKENS implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
StringTokenizer tokenizer = new StringTokenizer(attValue);
StringBuffer sb = new StringBuffer(attValue.length());
boolean ok = true;
if (tokenizer.hasMoreTokens()) {
while (true) {
String nmtoken = tokenizer.nextToken();
if (fValidating && !XMLCharacterProperties.validNmtoken(nmtoken)) {
ok = false;
}
sb.append(nmtoken);
if (!tokenizer.hasMoreTokens())
break;
sb.append(' ');
}
}
String newAttValue = sb.toString();
if (fValidating && (!ok || newAttValue.length() == 0)) {
reportRecoverableXMLError(XMLMessages.MSG_NMTOKENS_INVALID,
XMLMessages.VC_NAME_TOKEN,
fStringPool.toString(attrName), newAttValue);
}
if (!newAttValue.equals(attValue)) {
attValueHandle = fStringPool.addString(newAttValue);
if (fValidating && invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
}
return attValueHandle;
}
}
final class AttValidatorNOTATION implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// NOTATION - check that the value is in the AttDef enumeration (V_TAGo)
//
if (!fStringPool.stringInList(enumHandle, attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
XMLMessages.VC_NOTATION_ATTRIBUTES,
fStringPool.toString(attrName),
newAttValue, fStringPool.stringListAsString(enumHandle));
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
}
}
final class AttValidatorENUMERATION implements AttributeValidator {
public int normalize(int elementType, int attrName, int attValueHandle, int attType, int enumHandle) throws Exception {
//
// Normalize attribute based upon attribute type...
//
String attValue = fStringPool.toString(attValueHandle);
String newAttValue = attValue.trim();
if (fValidating) {
// REVISIT - can we release the old string?
if (newAttValue != attValue) {
if (invalidStandaloneAttDef(elementType, attrName)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTVALUE_CHANGED_DURING_NORMALIZATION_WHEN_STANDALONE,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
fStringPool.toString(attrName), attValue, newAttValue);
}
attValueHandle = fStringPool.addSymbol(newAttValue);
} else {
attValueHandle = fStringPool.addSymbol(attValueHandle);
}
//
// ENUMERATION - check that value is in the AttDef enumeration (V_TAG9)
//
if (!fStringPool.stringInList(enumHandle, attValueHandle)) {
reportRecoverableXMLError(XMLMessages.MSG_ATTRIBUTE_VALUE_NOT_IN_LIST,
XMLMessages.VC_ENUMERATION,
fStringPool.toString(attrName),
newAttValue, fStringPool.stringListAsString(enumHandle));
}
} else if (newAttValue != attValue) {
// REVISIT - can we release the old string?
attValueHandle = fStringPool.addSymbol(newAttValue);
}
return attValueHandle;
}
}
//
// element stack
//
private void charDataInContent() {
int[] children = fElementChildren[fElementDepth];
int childCount = fElementChildCount[fElementDepth];
try {
children[childCount] = -1;
} catch (NullPointerException ex) {
children = fElementChildren[fElementDepth] = new int[256];
childCount = 0; // should really assert this...
children[childCount] = -1;
} catch (ArrayIndexOutOfBoundsException ex) {
int[] newChildren = new int[childCount * 2];
System.arraycopy(children, 0, newChildren, 0, childCount);
children = fElementChildren[fElementDepth] = newChildren;
children[childCount] = -1;
}
fElementChildCount[fElementDepth] = ++childCount;
}
private int peekChildCount() {
return fElementChildCount[fElementDepth];
}
private int[] peekChildren() {
return fElementChildren[fElementDepth];
}
/**
* Check that the content of an element is valid.
* <p>
* This is the method of primary concern to the validator. This method is called
* upon the scanner reaching the end tag of an element. At that time, the
* element's children must be structurally validated, so it calls this method.
* The index of the element being checked (in the decl pool), is provided as
* well as an array of element name indexes of the children. The validator must
* confirm that this element can have these children in this order.
* <p>
* This can also be called to do 'what if' testing of content models just to see
* if they would be valid.
* <p>
* Note that the element index is an index into the element decl pool, whereas
* the children indexes are name indexes, i.e. into the string pool.
* <p>
* A value of -1 in the children array indicates a PCDATA node. All other
* indexes will be positive and represent child elements. The count can be
* zero, since some elements have the EMPTY content model and that must be
* confirmed.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of this
* element.
* @param childCount The number of entries in the <code>children</code> array.
* @param children The children of this element. Each integer is an index within
* the <code>StringPool</code> of the child element name. An index
* of -1 is used to indicate an occurrence of non-whitespace character
* data.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed. If the value returned is equal to the number
* of children, then additional content is required to reach a valid
* ending state.
*
* @exception Exception Thrown on error.
*/
public int checkContent(int elementIndex, int childCount, int[] children) throws Exception
{
// Get the element name index from the element
final int elementType = fCurrentElementType;
if (DEBUG_PRINT_CONTENT)
{
String strTmp = fStringPool.toString(elementType);
System.out.println
(
"Name: "
+ strTmp
+ ", Count: "
+ childCount
+ ", ContentSpec: "
+ getContentSpecAsString(elementIndex)
);
for (int index = 0; index < childCount && index < 10; index++) {
if (index == 0) System.out.print(" (");
String childName = (children[index] == -1) ? "#PCDATA" : fStringPool.toString(children[index]);
if (index + 1 == childCount)
System.out.println(childName + ")");
else if (index + 1 == 10)
System.out.println(childName + ",...)");
else
System.out.print(childName + ",");
}
}
// Get out the content spec for this element
final int contentSpec = fCurrentContentSpecType;
//
// Deal with the possible types of content. We try to optimized here
// by dealing specially with content models that don't require the
// full DFA treatment.
//
if (contentSpec == fEMPTYSymbol)
{
//
// If the child count is greater than zero, then this is
// an error right off the bat at index 0.
//
if (childCount != 0)
return 0;
}
else if (contentSpec == fANYSymbol)
{
//
// This one is open game so we don't pass any judgement on it
// at all. Its assumed to fine since it can hold anything.
//
}
else if (contentSpec == fMIXEDSymbol || contentSpec == fCHILDRENSymbol)
{
// Get the content model for this element, faulting it in if needed
XMLContentModel cmElem = null;
try
{
cmElem = getContentModel(elementIndex);
return cmElem.validateContent(childCount, children);
}
catch(CMException excToCatch)
{
// REVISIT - Translate the caught exception to the public error API
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
}
else if (contentSpec == -1)
{
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
elementType);
}
else
{
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_CST,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
// We succeeded
return -1;
}
/**
* Returns information about which elements can be placed at a particular point
* in the passed element's content model.
* <p>
* Note that the incoming content model to test must be valid at least up to
* the insertion point. If not, then -1 will be returned and the info object
* will not have been filled in.
* <p>
* If, on return, the info.isValidEOC flag is set, then the 'insert after'
* elemement is a valid end of content, i.e. nothing needs to be inserted
* after it to make the parent element's content model valid.
*
* @param elementIndex The index within the <code>ElementDeclPool</code> of the
* element which is being querying.
* @param fullyValid Only return elements that can be inserted and still
* maintain the validity of subsequent elements past the
* insertion point (if any). If the insertion point is at
* the end, and this is true, then only elements that can
* be legal final states will be returned.
* @param info An object that contains the required input data for the method,
* and which will contain the output information if successful.
*
* @return The value -1 if fully valid, else the 0 based index of the child
* that first failed before the insertion point. If the value
* returned is equal to the number of children, then the specified
* children are valid but additional content is required to reach a
* valid ending state.
*
* @exception Exception Thrown on error.
*
* @see InsertableElementsInfo
*/
public int whatCanGoHere(int elementIndex
, boolean fullyValid
, InsertableElementsInfo info) throws Exception
{
//
// Do some basic sanity checking on the info packet. First, make sure
// that insertAt is not greater than the child count. It can be equal,
// which means to get appendable elements, but not greater. Or, if
// the current children array is null, that's bad too.
//
// Since the current children array must have a blank spot for where
// the insert is going to be, the child count must always be at least
// one.
//
// Make sure that the child count is not larger than the current children
// array. It can be equal, which means get appendable elements, but not
// greater.
//
if ((info.insertAt > info.childCount)
|| (info.curChildren == null)
|| (info.childCount < 1)
|| (info.childCount > info.curChildren.length))
{
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
ImplementationMessages.VAL_WCGHI,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
int retVal = 0;
try
{
// Get the content model for this element
final XMLContentModel cmElem = getContentModel(elementIndex);
// And delegate this call to it
retVal = cmElem.whatCanGoHere(fullyValid, info);
}
catch(CMException excToCatch)
{
// REVISIT - Translate caught error to the public error handler interface
int majorCode = excToCatch.getErrorCode();
fErrorReporter.reportError(fErrorReporter.getLocator(),
ImplementationMessages.XERCES_IMPLEMENTATION_DOMAIN,
majorCode,
0,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
}
return retVal;
}
// -----------------------------------------------------------------------
// Private methods
// -----------------------------------------------------------------------
//
// When the element has a 'CHILDREN' model, this method is called to
// create the content model object. It looks for some special case simple
// models and creates SimpleContentModel objects for those. For the rest
// it creates the standard DFA style model.
//
private final XMLContentModel createChildModel(int elementIndex) throws CMException
{
//
// Get the content spec node for the element we are working on.
// This will tell us what kind of node it is, which tells us what
// kind of model we will try to create.
//
XMLContentSpecNode specNode = new XMLContentSpecNode();
int contentSpecIndex = getContentSpecHandle(elementIndex);
getContentSpecNode(contentSpecIndex, specNode);
//
// Check that the left value is not -1, since any content model
// with PCDATA should be MIXED, so we should not have gotten here.
//
if (specNode.value == -1)
throw new CMException(ImplementationMessages.VAL_NPCD);
if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
{
//
// Its a single leaf, so its an 'a' type of content model, i.e.
// just one instance of one element. That one is definitely a
// simple content model.
//
return new SimpleContentModel(specNode.value, -1, specNode.type);
}
else if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_CHOICE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_SEQ))
{
//
// Lets see if both of the children are leafs. If so, then it
// it has to be a simple content model
//
XMLContentSpecNode specLeft = new XMLContentSpecNode();
XMLContentSpecNode specRight = new XMLContentSpecNode();
getContentSpecNode(specNode.value, specLeft);
getContentSpecNode(specNode.otherValue, specRight);
if ((specLeft.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
&& (specRight.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF))
{
//
// Its a simple choice or sequence, so we can do a simple
// content model for it.
//
return new SimpleContentModel
(
specLeft.value
, specRight.value
, specNode.type
);
}
}
else if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE))
{
//
// Its a repetition, so see if its one child is a leaf. If so
// its a repetition of a single element, so we can do a simple
// content model for that.
//
XMLContentSpecNode specLeft = new XMLContentSpecNode();
getContentSpecNode(specNode.value, specLeft);
if (specLeft.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
{
//
// It is, so we can create a simple content model here that
// will check for this repetition. We pass -1 for the unused
// right node.
//
return new SimpleContentModel(specLeft.value, -1, specNode.type);
}
}
else
{
throw new CMException(ImplementationMessages.VAL_CST);
}
//
// Its not a simple content model, so here we have to create a DFA
// for this element. So we create a DFAContentModel object. He
// encapsulates all of the work to create the DFA.
//
fLeafCount = 0;
CMNode cmn = buildSyntaxTree(contentSpecIndex, specNode);
return new DFAContentModel
(
fStringPool
, cmn
, fLeafCount
);
}
//
// This method will handle the querying of the content model for a
// particular element. If the element does not have a content model, then
// it will be created.
//
private XMLContentModel getContentModel(int elementIndex) throws CMException
{
// See if a content model already exists first
XMLContentModel cmRet = getElementContentModel(elementIndex);
// If we have one, just return that. Otherwise, gotta create one
if (cmRet != null)
return cmRet;
// Get the type of content this element has
final int contentSpec = getContentSpecType(elementIndex);
// And create the content model according to the spec type
if (contentSpec == fMIXEDSymbol)
{
//
// Just create a mixel content model object. This type of
// content model is optimized for mixed content validation.
//
XMLContentSpecNode specNode = new XMLContentSpecNode();
int contentSpecIndex = getContentSpecHandle(elementIndex);
makeContentList(contentSpecIndex, specNode);
cmRet = new MixedContentModel(fCount, fContentList);
}
else if (contentSpec == fCHILDRENSymbol)
{
//
// This method will create an optimal model for the complexity
// of the element's defined model. If its simple, it will create
// a SimpleContentModel object. If its a simple list, it will
// create a SimpleListContentModel object. If its complex, it
// will create a DFAContentModel object.
//
cmRet = createChildModel(elementIndex);
}
else
{
throw new CMException(ImplementationMessages.VAL_CST);
}
// Add the new model to the content model for this element
setContentModel(elementIndex, cmRet);
return cmRet;
}
//
//
//
protected void reportRecoverableXMLError(int majorCode, int minorCode) throws Exception {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
null,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1) throws Exception {
Object[] args = { fStringPool.toString(stringIndex1) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1) throws Exception {
Object[] args = { string1 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, int stringIndex1, int stringIndex2) throws Exception {
Object[] args = { fStringPool.toString(stringIndex1), fStringPool.toString(stringIndex2) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2) throws Exception {
Object[] args = { string1, string2 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
protected void reportRecoverableXMLError(int majorCode, int minorCode, String string1, String string2, String string3) throws Exception {
Object[] args = { string1, string2, string3 };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
majorCode,
minorCode,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
//
// XMLEntityHandler interface
//
public void readerChange(XMLEntityHandler.EntityReader nextReader, int nextReaderId) throws Exception {
fDTDScanner.readerChange(nextReader, nextReaderId);
}
public void endOfInput(int entityNameIndex, boolean moreToFollow) throws Exception {
if (fValidating) {
int readerDepth = fEntityHandler.getReaderDepth();
if (fDTDScanner.getReadingContentSpec()) {
int parenDepth = fDTDScanner.parenDepth();
if (readerDepth != parenDepth) {
reportRecoverableXMLError(XMLMessages.MSG_IMPROPER_GROUP_NESTING,
XMLMessages.VC_PROPER_GROUP_PE_NESTING,
entityNameIndex);
}
} else {
int markupDepth = fDTDScanner.markupDepth();
if (readerDepth != markupDepth) {
reportRecoverableXMLError(XMLMessages.MSG_IMPROPER_DECLARATION_NESTING,
XMLMessages.VC_PROPER_DECLARATION_PE_NESTING,
entityNameIndex);
}
}
}
fDTDScanner.endOfInput(entityNameIndex, moreToFollow);
}
public int saveCurrentLocation() {
return -1;
}
public boolean validVersionNum(String version) {
return XMLCharacterProperties.validVersionNum(version);
}
public boolean validEncName(String encoding) {
return XMLCharacterProperties.validEncName(encoding);
}
public int validPublicId(String publicId) {
return XMLCharacterProperties.validPublicId(publicId);
}
public void doctypeDecl(int rootElementType, int publicId, int systemId) throws Exception {
fRootElementType = rootElementType;
fEventHandler.startDTD(rootElementType, publicId, systemId);
}
public void startReadingFromExternalSubset(int publicId, int systemId) throws Exception {
fEntityHandler.startReadingFromExternalSubset(fStringPool.toString(publicId),
fStringPool.toString(systemId),
fDTDScanner.markupDepth());
}
public void stopReadingFromExternalSubset() throws Exception {
fEntityHandler.stopReadingFromExternalSubset();
}
public int addElementDecl(int elementType) throws Exception {
int elementIndex = addElement(elementType);
return elementIndex;
}
public int addElementDecl(int elementType, int contentSpecType, int contentSpec) throws Exception {
int elementIndex = addElementDecl(elementType, contentSpecType, contentSpec, !usingStandaloneReader());
if (elementIndex == -1) {
if (fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_ALREADY_DECLARED,
XMLMessages.VC_UNIQUE_ELEMENT_TYPE_DECLARATION,
elementType);
}
} else {
fEventHandler.elementDecl(elementType, getContentSpec(elementIndex));
fElementDeclCount++;
}
return elementIndex;
}
public int addAttDef(int elementIndex, int attName, int attType, int enumeration, int attDefaultType, int attDefaultValue) throws Exception {
int attDefIndex = addAttDef(elementIndex, attName, attType, enumeration, attDefaultType, attDefaultValue, !usingStandaloneReader(), fValidating, fWarningOnDuplicateAttDef);
if (attDefIndex != -1) {
String enumString = (enumeration == -1) ? null : fStringPool.stringListAsString(enumeration);
fEventHandler.attlistDecl(getElementType(elementIndex), attName, attType, enumString, attDefaultType, attDefaultValue);
fAttlistDeclCount++;
}
return attDefIndex;
}
public int addUniqueLeafNode(int nodeValue) throws Exception {
int csn = addContentSpecNode(XMLContentSpecNode.CONTENTSPECNODE_LEAF, nodeValue, -1, true);
if (csn == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_DUPLICATE_TYPE_IN_MIXED_CONTENT,
XMLMessages.VC_NO_DUPLICATE_TYPES,
nodeValue);
}
return csn;
}
public int addContentSpecNode(int nodeType, int nodeValue) throws Exception {
return addContentSpecNode(nodeType, nodeValue, -1, false);
}
public int addContentSpecNode(int nodeType, int nodeValue, int otherNodeValue) throws Exception {
return addContentSpecNode(nodeType, nodeValue, otherNodeValue, false);
}
public int addInternalPEDecl(int name, int value, int location) throws Exception {
if (fParameterEntityPool == null)
fParameterEntityPool = new EntityPool(fStringPool, fErrorReporter, false);
int entityIndex = fParameterEntityPool.addEntityDecl(name, value, location, -1, -1, -1, !usingStandaloneReader());
fEventHandler.internalPEDecl(name, value);
return entityIndex;
}
public int addExternalPEDecl(int name, int publicId, int systemId) throws Exception {
if (fParameterEntityPool == null)
fParameterEntityPool = new EntityPool(fStringPool, fErrorReporter, false);
int entityIndex = fParameterEntityPool.addEntityDecl(name, -1, -1, publicId, systemId, -1, !usingStandaloneReader());
fEventHandler.externalPEDecl(name, publicId, systemId);
return entityIndex;
}
public int addInternalEntityDecl(int name, int value, int location) throws Exception {
int entityIndex = fEntityPool.addEntityDecl(name, value, location, -1, -1, -1, !usingStandaloneReader());
fEventHandler.internalEntityDecl(name, value);
return entityIndex;
}
public int addExternalEntityDecl(int name, int publicId, int systemId) throws Exception {
int entityIndex = fEntityPool.addEntityDecl(name, -1, -1, publicId, systemId, -1, !usingStandaloneReader());
fEventHandler.externalEntityDecl(name, publicId, systemId);
return entityIndex;
}
public int addUnparsedEntityDecl(int name, int publicId, int systemId, int notationName) throws Exception {
int entityIndex = fEntityPool.addEntityDecl(name, -1, -1, publicId, systemId, notationName, !usingStandaloneReader());
fEventHandler.unparsedEntityDecl(name, publicId, systemId, notationName);
if (fEntityPool.lookupNotation(notationName) == -1) {
Object[] args = { fStringPool.toString(name),
fStringPool.toString(notationName) };
fEntityPool.addRequiredNotation(notationName,
fErrorReporter.getLocator(),
XMLMessages.MSG_NOTATION_NOT_DECLARED_FOR_UNPARSED_ENTITYDECL,
XMLMessages.VC_NOTATION_DECLARED,
args);
}
return entityIndex;
}
public int startEnumeration() {
return fStringPool.startStringList();
}
public void addNameToEnumeration(int enumHandle, int elementType, int attrName, int nameIndex, boolean isNotationType) {
fStringPool.addStringToList(enumHandle, nameIndex);
if (isNotationType && fEntityPool.lookupNotation(nameIndex) == -1) {
Object[] args = { fStringPool.toString(elementType),
fStringPool.toString(attrName),
fStringPool.toString(nameIndex) };
fEntityPool.addRequiredNotation(nameIndex,
fErrorReporter.getLocator(),
XMLMessages.MSG_NOTATION_NOT_DECLARED_FOR_NOTATIONTYPE_ATTRIBUTE,
XMLMessages.VC_NOTATION_DECLARED,
args);
}
}
public void endEnumeration(int enumHandle) {
fStringPool.finishStringList(enumHandle);
}
public int addNotationDecl(int notationName, int publicId, int systemId) throws Exception {
//
// REVISIT - I am making an arbitrary decision that is not covered by the
// spec (or I missed it). If we see a second NotationDecl for the same name,
// we will ignore the latter declaration. This seems consistent with the
// usual behavior of such things in the spec, but it might also be good to
// generate a warning that this has occurred. The addNotation() method will
// return -1 if we already have a declaration for this name. This will slow
// down the parser in direct relation to the number of NotationDecl names.
//
int notationIndex = fEntityPool.addNotationDecl(notationName, publicId, systemId, !usingStandaloneReader());
if (notationIndex != -1)
fEventHandler.notationDecl(notationName, publicId, systemId);
return notationIndex;
}
public void callProcessingInstruction(int target, int data) throws Exception {
fEventHandler.processingInstructionInDTD(target, data);
}
public void callComment(int comment) throws Exception {
fEventHandler.commentInDTD(comment);
}
public int scanElementType(XMLEntityHandler.EntityReader entityReader, char fastchar) throws Exception {
if (!fNamespacesEnabled) {
return entityReader.scanName(fastchar);
}
int elementType = entityReader.scanQName(fastchar);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
return elementType;
}
public int checkForElementTypeWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastchar) throws Exception {
if (!fNamespacesEnabled) {
return entityReader.scanName(fastchar);
}
int elementType = entityReader.scanQName(fastchar);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
return elementType;
}
public int checkForAttributeNameWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastchar) throws Exception {
if (!fNamespacesEnabled) {
return entityReader.scanName(fastchar);
}
int attrName = entityReader.scanQName(fastchar);
if (entityReader.lookingAtChar(':', false)) {
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_TWO_COLONS_IN_QNAME,
XMLMessages.P5_INVALID_CHARACTER,
null,
XMLErrorReporter.ERRORTYPE_FATAL_ERROR);
entityReader.skipPastNmtoken(' ');
}
return attrName;
}
public int checkForNameWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception {
//
// REVISIT - what does this have to do with PE references?
//
int valueIndex = entityReader.scanName(fastcheck);
return valueIndex;
}
public int checkForNmtokenWithPEReference(XMLEntityHandler.EntityReader entityReader, char fastcheck) throws Exception {
//
// REVISIT - what does this have to do with PE references?
//
int nameOffset = entityReader.currentOffset();
entityReader.skipPastNmtoken(fastcheck);
int nameLength = entityReader.currentOffset() - nameOffset;
if (nameLength == 0)
return -1;
int valueIndex = entityReader.addSymbol(nameOffset, nameLength);
return valueIndex;
}
public int scanDefaultAttValue(int elementType, int attrName, int attType, int enumeration) throws Exception {
if (fValidating && attType == fIDSymbol) {
reportRecoverableXMLError(XMLMessages.MSG_ID_DEFAULT_TYPE_INVALID,
XMLMessages.VC_ID_ATTRIBUTE_DEFAULT,
attrName);
}
int defaultAttValue = fDTDScanner.scanDefaultAttValue(elementType, attrName);
if (defaultAttValue == -1)
return -1;
if (attType != fCDATASymbol) {
AttributeValidator av = getValidatorForAttType(attType);
defaultAttValue = av.normalize(-1, attrName, defaultAttValue, attType, enumeration);
}
return defaultAttValue;
}
//
// This method will build our syntax tree by recursively going though
// the element's content model and creating new CMNode type node for
// the model, and rewriting '?' and '+' nodes along the way.
//
// On final return, the head node of the syntax tree will be returned.
// This top node will be a sequence node with the left side being the
// rewritten content, and the right side being a special end of content
// node.
//
// We also count the non-epsilon leaf nodes, which is an important value
// that is used in a number of places later.
//
private int fLeafCount = 0;
private final CMNode
buildSyntaxTree(int startNode, XMLContentSpecNode specNode) throws CMException
{
// We will build a node at this level for the new tree
CMNode nodeRet = null;
getContentSpecNode(startNode, specNode);
//
// If this node is a leaf, then its an easy one. We just add it
// to the tree.
//
if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
{
//
// Create a new leaf node, and pass it the current leaf count,
// which is its DFA state position. Bump the leaf count after
// storing it. This makes the positions zero based since we
// store first and then increment.
//
nodeRet = new CMLeaf(specNode.type, specNode.value, fLeafCount++);
}
else
{
//
// Its not a leaf, so we have to recurse its left and maybe right
// nodes. Save both values before we recurse and trash the node.
//
final int leftNode = specNode.value;
final int rightNode = specNode.otherValue;
if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_CHOICE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_SEQ))
{
//
// Recurse on both children, and return a binary op node
// with the two created sub nodes as its children. The node
// type is the same type as the source.
//
nodeRet = new CMBinOp
(
specNode.type
, buildSyntaxTree(leftNode, specNode)
, buildSyntaxTree(rightNode, specNode)
);
}
else if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE)
{
// This one is fine as is, just change to our form
nodeRet = new CMUniOp
(
specNode.type
, buildSyntaxTree(leftNode, specNode)
);
}
else if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE)
{
// Convert to (x|epsilon)
nodeRet = new CMBinOp
(
XMLContentSpecNode.CONTENTSPECNODE_CHOICE
, buildSyntaxTree(leftNode, specNode)
, new CMLeaf(XMLContentSpecNode.CONTENTSPECNODE_LEAF, fEpsilonIndex)
);
}
else if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE)
{
// Convert to (x,x*)
nodeRet = new CMBinOp
(
XMLContentSpecNode.CONTENTSPECNODE_SEQ
, buildSyntaxTree(leftNode, specNode)
, new CMUniOp
(
XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE
, buildSyntaxTree(leftNode, specNode)
)
);
}
else
{
throw new CMException(ImplementationMessages.VAL_CST);
}
}
// And return our new node for this level
return nodeRet;
}
private int fCount = 0;
private int[] fContentList = new int[64];
private final void makeContentList(int startNode, XMLContentSpecNode specNode) throws CMException {
//
// Ok, we need to build up an array of the possible children
// under this element. The mixed content model can only be a
// repeated series of alternations with no numeration or ordering.
// So we call a local recursive method to iterate the tree and
// build up the array.
//
// So we get the content spec of the element, which gives us the
// starting node. Everything else kicks off from there. We pass
// along a content node for each iteration to use so that it does
// not have to create and trash lots of objects.
//
while (true)
{
fCount = 0;
try
{
fCount = buildContentList
(
startNode
, 0
, specNode
);
}
catch(IndexOutOfBoundsException excToCatch)
{
//
// Expand the array and try it again. Yes, this is
// piggy, but the odds of it ever actually happening
// are slim to none.
//
fContentList = new int[fContentList.length * 2];
fCount = 0;
continue;
}
// We survived, so break out
break;
}
}
private final int buildContentList( int startNode
, int count
, XMLContentSpecNode specNode) throws CMException
{
// Get the content spec for the passed start node
getContentSpecNode(startNode, specNode);
// If this node is a leaf, then add it to our list and return.
if (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_LEAF)
{
fContentList[count++] = specNode.value;
return count;
}
//
// Its not a leaf, so we have to recurse its left and maybe right
// nodes. Save both values before we recurse and trash the node.
//
final int leftNode = specNode.value;
final int rightNode = specNode.otherValue;
if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_CHOICE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_SEQ))
{
//
// Recurse on the left and right nodes of this guy, making sure
// to keep the count correct.
//
count = buildContentList(leftNode, count, specNode);
count = buildContentList(rightNode, count, specNode);
}
else if ((specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE)
|| (specNode.type == XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE))
{
// Just do the left node on this one
count = buildContentList(leftNode, count, specNode);
}
else
{
throw new CMException(ImplementationMessages.VAL_CST);
}
// And return our accumlated new count
return count;
}
//
// Chunk size constants
//
private static final int CHUNK_SHIFT = 8; // 2^8 = 256
private static final int CHUNK_SIZE = (1 << CHUNK_SHIFT);
private static final int CHUNK_MASK = CHUNK_SIZE - 1;
private static final int INITIAL_CHUNK_COUNT = (1 << (10 - CHUNK_SHIFT)); // 2^10 = 1k
//
// Instance variables
//
//
// Element list
//
private int fElementCount = 0;
private int[][] fElementType = new int[INITIAL_CHUNK_COUNT][];
private byte[][] fElementDeclIsExternal = new byte[INITIAL_CHUNK_COUNT][];
private int[][] fContentSpecType = new int[INITIAL_CHUNK_COUNT][];
private int[][] fContentSpec = new int[INITIAL_CHUNK_COUNT][];
private XMLContentModel[][] fContentModel = new XMLContentModel[INITIAL_CHUNK_COUNT][];
private int[][] fAttlistHead = new int[INITIAL_CHUNK_COUNT][];
private int[][] fAttlistTail = new int[INITIAL_CHUNK_COUNT][];
//
// ContentSpecNode list
//
private int fNodeCount = 0;
private byte[][] fNodeType = new byte[INITIAL_CHUNK_COUNT][];
private int[][] fNodeValue = new int[INITIAL_CHUNK_COUNT][];
//
// AttDef list
//
private int fAttDefCount = 0;
private int[][] fAttName = new int[INITIAL_CHUNK_COUNT][];
private int[][] fAttType = new int[INITIAL_CHUNK_COUNT][];
private AttributeValidator[][] fAttValidator = new AttributeValidator[INITIAL_CHUNK_COUNT][];
private int[][] fEnumeration = new int[INITIAL_CHUNK_COUNT][];
private int[][] fAttDefaultType = new int[INITIAL_CHUNK_COUNT][];
private int[][] fAttValue = new int[INITIAL_CHUNK_COUNT][];
private byte[][] fAttDefIsExternal = new byte[INITIAL_CHUNK_COUNT][];
private int[][] fNextAttDef = new int[INITIAL_CHUNK_COUNT][];
//
//
//
private Hashtable fIdDefs = null;
private Hashtable fIdRefs = null;
private Object fNullValue = null;
private AttributeValidator fAttValidatorCDATA = null;
private AttributeValidator fAttValidatorID = null;
private AttributeValidator fAttValidatorIDREF = null;
private AttributeValidator fAttValidatorIDREFS = null;
private AttributeValidator fAttValidatorENTITY = null;
private AttributeValidator fAttValidatorENTITIES = null;
private AttributeValidator fAttValidatorNMTOKEN = null;
private AttributeValidator fAttValidatorNMTOKENS = null;
private AttributeValidator fAttValidatorNOTATION = null;
private AttributeValidator fAttValidatorENUMERATION = null;
//
//
//
private void poolReset() {
int chunk = 0;
int index = 0;
for (int i = 0; i < fElementCount; i++) {
fContentModel[chunk][index] = null;
if (++index == CHUNK_SIZE) {
chunk++;
index = 0;
}
}
fElementCount = 0;
fNodeCount = 0;
fAttDefCount = 0;
if (fIdDefs != null)
fIdDefs.clear();
if (fIdRefs != null)
fIdRefs.clear();
}
//
// Element entries
//
private boolean ensureElementCapacity(int chunk) {
try {
return fElementType[chunk][0] == 0;
} catch (ArrayIndexOutOfBoundsException ex) {
byte[][] newByteArray = new byte[chunk * 2][];
System.arraycopy(fElementDeclIsExternal, 0, newByteArray, 0, chunk);
fElementDeclIsExternal = newByteArray;
int[][] newIntArray = new int[chunk * 2][];
System.arraycopy(fElementType, 0, newIntArray, 0, chunk);
fElementType = newIntArray;
newIntArray = new int[chunk * 2][];
System.arraycopy(fContentSpecType, 0, newIntArray, 0, chunk);
fContentSpecType = newIntArray;
newIntArray = new int[chunk * 2][];
System.arraycopy(fContentSpec, 0, newIntArray, 0, chunk);
fContentSpec = newIntArray;
XMLContentModel[][] newContentModel = new XMLContentModel[chunk * 2][];
System.arraycopy(fContentModel, 0, newContentModel, 0, chunk);
fContentModel = newContentModel;
newIntArray = new int[chunk * 2][];
System.arraycopy(fAttlistHead, 0, newIntArray, 0, chunk);
fAttlistHead = newIntArray;
newIntArray = new int[chunk * 2][];
System.arraycopy(fAttlistTail, 0, newIntArray, 0, chunk);
fAttlistTail = newIntArray;
} catch (NullPointerException ex) {
}
fElementType[chunk] = new int[CHUNK_SIZE];
fElementDeclIsExternal[chunk] = new byte[CHUNK_SIZE];
fContentSpecType[chunk] = new int[CHUNK_SIZE];
fContentSpec[chunk] = new int[CHUNK_SIZE];
fContentModel[chunk] = new XMLContentModel[CHUNK_SIZE];
fAttlistHead[chunk] = new int[CHUNK_SIZE];
fAttlistTail[chunk] = new int[CHUNK_SIZE];
return true;
}
private int lookupElement(int elementType) {
return fStringPool.getDeclaration(elementType);
}
private int addElement(int elementType) {
int elementIndex = fStringPool.getDeclaration(elementType);
if (elementIndex != -1)
return elementIndex;
int chunk = fElementCount >> CHUNK_SHIFT;
int index = fElementCount & CHUNK_MASK;
ensureElementCapacity(chunk);
fElementType[chunk][index] = elementType;
fElementDeclIsExternal[chunk][index] = 0;
fContentSpecType[chunk][index] = -1;
fContentSpec[chunk][index] = -1;
fContentModel[chunk][index] = null;
fAttlistHead[chunk][index] = -1;
fAttlistTail[chunk][index] = -1;
fStringPool.setDeclaration(elementType, fElementCount);
return fElementCount++;
}
private int addElementDecl(int elementType, int contentSpecType, int contentSpec, boolean isExternal) {
//System.out.println("Pool " + this + " add " + decl.elementType + " (" + fStringPool.toString(decl.elementType) + ")");
int elementIndex = fStringPool.getDeclaration(elementType);
if (elementIndex != -1) {
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
if (fContentSpecType[chunk][index] != -1)
return -1;
fElementDeclIsExternal[chunk][index] = (byte)(isExternal ? 1 : 0);
fContentSpecType[chunk][index] = contentSpecType;
fContentSpec[chunk][index] = contentSpec;
fContentModel[chunk][index] = null;
return elementIndex;
}
int chunk = fElementCount >> CHUNK_SHIFT;
int index = fElementCount & CHUNK_MASK;
ensureElementCapacity(chunk);
fElementType[chunk][index] = elementType;
fElementDeclIsExternal[chunk][index] = (byte)(isExternal ? 1 : 0);
fContentSpecType[chunk][index] = contentSpecType;
fContentSpec[chunk][index] = contentSpec;
fContentModel[chunk][index] = null;
fAttlistHead[chunk][index] = -1;
fAttlistTail[chunk][index] = -1;
fStringPool.setDeclaration(elementType, fElementCount);
return fElementCount++;
}
private int getElementType(int elementIndex) {
if (elementIndex < 0 || elementIndex >= fElementCount)
return -1;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
return fElementType[chunk][index];
}
private boolean getElementDeclIsExternal(int elementIndex) {
if (elementIndex < 0 || elementIndex >= fElementCount)
return false;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
return (fElementDeclIsExternal[chunk][index] != 0);
}
private int getContentSpecType(int elementIndex) {
if (elementIndex < 0 || elementIndex >= fElementCount)
return -1;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
return fContentSpecType[chunk][index];
}
class ContentSpecImpl implements XMLValidator.ContentSpec {
public StringPool fStringPool;
public int fHandle;
public int fType;
public String toString() {
if (fType == fMIXEDSymbol || fType == fCHILDRENSymbol)
return getContentSpecNodeAsString(fHandle);
else
return fStringPool.toString(fType);
}
public int getType() {
return fType;
}
public int getHandle() {
return fHandle;
}
public void getNode(int handle, XMLContentSpecNode node) {
getContentSpecNode(handle, node);
}
}
ContentSpecImpl fContentSpecImpl = null;
private XMLValidator.ContentSpec getContentSpec(int elementIndex) {
if (elementIndex < 0 || elementIndex >= fElementCount)
return null;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
if (fContentSpecImpl == null)
fContentSpecImpl = new ContentSpecImpl();
fContentSpecImpl.fStringPool = fStringPool;
fContentSpecImpl.fHandle = fContentSpec[chunk][index];
fContentSpecImpl.fType = fContentSpecType[chunk][index];
return fContentSpecImpl;
}
private int getContentSpecHandle(int elementIndex) {
if (elementIndex < 0 || elementIndex >= fElementCount)
return -1;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
return fContentSpec[chunk][index];
}
public String getContentSpecAsString(int elementIndex) {
if (elementIndex < 0 || elementIndex >= fElementCount)
return null;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
int contentSpecType = fContentSpecType[chunk][index];
if (contentSpecType == fMIXEDSymbol || contentSpecType == fCHILDRENSymbol)
return getContentSpecNodeAsString(fContentSpec[chunk][index]);
else
return fStringPool.toString(contentSpecType);
}
private XMLContentModel getElementContentModel(int elementIndex) {
if (elementIndex < 0 || elementIndex >= fElementCount)
return null;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
return fContentModel[chunk][index];
}
private void setContentModel(int elementIndex, XMLContentModel cm) {
if (elementIndex < 0 || elementIndex >= fElementCount)
return;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
fContentModel[chunk][index] = cm;
}
//
// contentspec entries
//
private boolean ensureNodeCapacity(int chunk) {
try {
return fNodeType[chunk][0] == 0;
} catch (ArrayIndexOutOfBoundsException ex) {
byte[][] newByteArray = new byte[chunk * 2][];
System.arraycopy(fNodeType, 0, newByteArray, 0, chunk);
fNodeType = newByteArray;
int[][] newIntArray = new int[chunk * 2][];
System.arraycopy(fNodeValue, 0, newIntArray, 0, chunk);
fNodeValue = newIntArray;
} catch (NullPointerException ex) {
}
fNodeType[chunk] = new byte[CHUNK_SIZE];
fNodeValue[chunk] = new int[CHUNK_SIZE];
return true;
}
//
//
//
private int addContentSpecLeafNode(int nodeValue) throws Exception {
//
// Check that we have not seen this value before...
//
if (nodeValue != -1) {
int nodeCount = fNodeCount;
int chunk = fNodeCount >> CHUNK_SHIFT;
int index = fNodeCount & CHUNK_MASK;
while (true) {
if (index-- == 0) {
index = CHUNK_SIZE - 1;
chunk--;
}
int nodeType = fNodeType[chunk][index];
if (nodeType == XMLContentSpecNode.CONTENTSPECNODE_LEAF) {
int otherNodeValue = fNodeValue[chunk][index];
if (otherNodeValue == -1)
break;
if (otherNodeValue == nodeValue) {
return -1;
}
}
}
}
int chunk = fNodeCount >> CHUNK_SHIFT;
int index = fNodeCount & CHUNK_MASK;
ensureNodeCapacity(chunk);
fNodeType[chunk][index] = (byte)XMLContentSpecNode.CONTENTSPECNODE_LEAF;
fNodeValue[chunk][index] = nodeValue;
return fNodeCount++;
}
//
//
//
private int addContentSpecNode(int nodeType, int nodeValue, int otherNodeValue, boolean mustBeUnique) throws Exception {
if (mustBeUnique) // REVISIT - merge these methods...
return addContentSpecLeafNode(nodeValue);
int chunk = fNodeCount >> CHUNK_SHIFT;
int index = fNodeCount & CHUNK_MASK;
ensureNodeCapacity(chunk);
switch (nodeType) {
case XMLContentSpecNode.CONTENTSPECNODE_LEAF:
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE:
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE:
case XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE:
fNodeType[chunk][index] = (byte)nodeType;
fNodeValue[chunk][index] = nodeValue;
return fNodeCount++;
case XMLContentSpecNode.CONTENTSPECNODE_CHOICE:
case XMLContentSpecNode.CONTENTSPECNODE_SEQ:
fNodeType[chunk][index] = (byte)nodeType;
fNodeValue[chunk][index] = nodeValue;
int nodeIndex = fNodeCount++;
if (++index == CHUNK_SIZE) {
chunk++;
ensureNodeCapacity(chunk);
index = 0;
}
fNodeType[chunk][index] = (byte)(nodeType | 64); // flag second entry for consistancy checking
fNodeValue[chunk][index] = otherNodeValue;
fNodeCount++;
return nodeIndex;
default:
return -1;
}
}
protected void getContentSpecNode(int contentSpecIndex, XMLContentSpecNode csn) {
int chunk = contentSpecIndex >> CHUNK_SHIFT;
int index = contentSpecIndex & CHUNK_MASK;
csn.type = fNodeType[chunk][index];
csn.value = fNodeValue[chunk][index];
if (csn.type == XMLContentSpecNode.CONTENTSPECNODE_CHOICE || csn.type == XMLContentSpecNode.CONTENTSPECNODE_SEQ) {
if (++index == CHUNK_SIZE) {
chunk++;
index = 0;
}
csn.otherValue = fNodeValue[chunk][index];
} else
csn.otherValue = -1;
}
private void appendContentSpecNode(int contentSpecIndex, StringBuffer sb, boolean noParen) {
int chunk = contentSpecIndex >> CHUNK_SHIFT;
int index = contentSpecIndex & CHUNK_MASK;
int type = fNodeType[chunk][index];
int value = fNodeValue[chunk][index];
switch (type) {
case XMLContentSpecNode.CONTENTSPECNODE_LEAF:
sb.append(value == -1 ? "#PCDATA" : fStringPool.toString(value));
return;
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE:
appendContentSpecNode(value, sb, false);
sb.append('?');
return;
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE:
appendContentSpecNode(value, sb, false);
sb.append('*');
return;
case XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE:
appendContentSpecNode(value, sb, false);
sb.append('+');
return;
case XMLContentSpecNode.CONTENTSPECNODE_CHOICE:
case XMLContentSpecNode.CONTENTSPECNODE_SEQ:
if (!noParen)
sb.append('(');
int leftChunk = value >> CHUNK_SHIFT;
int leftIndex = value & CHUNK_MASK;
int leftType = fNodeType[leftChunk][leftIndex];
appendContentSpecNode(value, sb, leftType == type);
sb.append(type == XMLContentSpecNode.CONTENTSPECNODE_CHOICE ? '|' : ',');
if (++index == CHUNK_SIZE) {
chunk++;
index = 0;
}
appendContentSpecNode(fNodeValue[chunk][index], sb, false);
if (!noParen)
sb.append(')');
return;
default:
return;
}
}
public String getContentSpecNodeAsString(int contentSpecIndex) {
int chunk = contentSpecIndex >> CHUNK_SHIFT;
int index = contentSpecIndex & CHUNK_MASK;
int type = fNodeType[chunk][index];
int value = fNodeValue[chunk][index];
StringBuffer sb = new StringBuffer();
switch (type) {
case XMLContentSpecNode.CONTENTSPECNODE_LEAF:
sb.append("(" + (value == -1 ? "#PCDATA" : fStringPool.toString(value)) + ")");
break;
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE:
chunk = value >> CHUNK_SHIFT;
index = value & CHUNK_MASK;
if (fNodeType[chunk][index] == XMLContentSpecNode.CONTENTSPECNODE_LEAF) {
value = fNodeValue[chunk][index];
sb.append("(" + (value == -1 ? "#PCDATA" : fStringPool.toString(value)) + ")?");
} else
appendContentSpecNode(contentSpecIndex, sb, false);
break;
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE:
chunk = value >> CHUNK_SHIFT;
index = value & CHUNK_MASK;
if (fNodeType[chunk][index] == XMLContentSpecNode.CONTENTSPECNODE_LEAF) {
value = fNodeValue[chunk][index];
sb.append("(" + (value == -1 ? "#PCDATA" : fStringPool.toString(value)) + ")*");
} else
appendContentSpecNode(contentSpecIndex, sb, false);
break;
case XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE:
chunk = value >> CHUNK_SHIFT;
index = value & CHUNK_MASK;
if (fNodeType[chunk][index] == XMLContentSpecNode.CONTENTSPECNODE_LEAF) {
value = fNodeValue[chunk][index];
sb.append("(" + (value == -1 ? "#PCDATA" : fStringPool.toString(value)) + ")+");
} else
appendContentSpecNode(contentSpecIndex, sb, false);
break;
case XMLContentSpecNode.CONTENTSPECNODE_CHOICE:
case XMLContentSpecNode.CONTENTSPECNODE_SEQ:
appendContentSpecNode(contentSpecIndex, sb, false);
break;
default:
return null;
}
return sb.toString();
}
//
// attribute list interfaces
//
private boolean ensureAttrCapacity(int chunk) {
try {
return fAttName[chunk][0] == 0;
} catch (ArrayIndexOutOfBoundsException ex) {
byte[][] newByteArray = new byte[chunk * 2][];
System.arraycopy(fAttDefIsExternal, 0, newByteArray, 0, chunk);
fAttDefIsExternal = newByteArray;
int[][] newIntArray = new int[chunk * 2][];
System.arraycopy(fAttName, 0, newIntArray, 0, chunk);
fAttName = newIntArray;
newIntArray = new int[chunk * 2][];
System.arraycopy(fAttType, 0, newIntArray, 0, chunk);
fAttType = newIntArray;
newIntArray = new int[chunk * 2][];
System.arraycopy(fEnumeration, 0, newIntArray, 0, chunk);
fEnumeration = newIntArray;
newIntArray = new int[chunk * 2][];
System.arraycopy(fAttDefaultType, 0, newIntArray, 0, chunk);
fAttDefaultType = newIntArray;
newIntArray = new int[chunk * 2][];
System.arraycopy(fAttValue, 0, newIntArray, 0, chunk);
fAttValue = newIntArray;
newIntArray = new int[chunk * 2][];
System.arraycopy(fNextAttDef, 0, newIntArray, 0, chunk);
fNextAttDef = newIntArray;
AttributeValidator[][] newValidatorArray = new AttributeValidator[chunk * 2][];
System.arraycopy(fAttValidator, 0, newValidatorArray, 0, chunk);
fAttValidator = newValidatorArray;
} catch (NullPointerException ex) {
}
fAttDefIsExternal[chunk] = new byte[CHUNK_SIZE];
fAttName[chunk] = new int[CHUNK_SIZE];
fAttType[chunk] = new int[CHUNK_SIZE];
fAttValidator[chunk] = new AttributeValidator[CHUNK_SIZE];
fEnumeration[chunk] = new int[CHUNK_SIZE];
fAttDefaultType[chunk] = new int[CHUNK_SIZE];
fAttValue[chunk] = new int[CHUNK_SIZE];
fNextAttDef[chunk] = new int[CHUNK_SIZE];
return true;
}
//
private int addAttDef(int elementIndex, int attName, int attType, int enumeration, int attDefaultType, int attDefaultValue, boolean isExternal, boolean validationEnabled, boolean warnOnDuplicate) throws Exception {
//
// check fields
//
int elemChunk = elementIndex >> CHUNK_SHIFT;
int elemIndex = elementIndex & CHUNK_MASK;
int attlistIndex = fAttlistHead[elemChunk][elemIndex];
int dupID = -1;
int dupNotation = -1;
while (attlistIndex != -1) {
int attrChunk = attlistIndex >> CHUNK_SHIFT;
int attrIndex = attlistIndex & CHUNK_MASK;
if (fStringPool.equalNames(fAttName[attrChunk][attrIndex], attName)) {
if (warnOnDuplicate) {
Object[] args = { fStringPool.toString(fElementType[elemChunk][elemIndex]),
fStringPool.toString(attName) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DUPLICATE_ATTDEF,
XMLMessages.P53_DUPLICATE,
args,
XMLErrorReporter.ERRORTYPE_WARNING);
}
return -1;
}
if (validationEnabled) {
if (attType == fIDSymbol && fAttType[attrChunk][attrIndex] == fIDSymbol)
dupID = fAttName[attrChunk][attrIndex];
if (attType == fNOTATIONSymbol && fAttType[attrChunk][attrIndex] == fNOTATIONSymbol)
dupNotation = fAttName[attrChunk][attrIndex];
}
attlistIndex = fNextAttDef[attrChunk][attrIndex];
}
if (validationEnabled) {
if (dupID != -1) {
Object[] args = { fStringPool.toString(fElementType[elemChunk][elemIndex]),
fStringPool.toString(dupID),
fStringPool.toString(attName) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_MORE_THAN_ONE_ID_ATTRIBUTE,
XMLMessages.VC_ONE_ID_PER_ELEMENT_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
return -1;
}
if (dupNotation != -1) {
Object[] args = { fStringPool.toString(fElementType[elemChunk][elemIndex]),
fStringPool.toString(dupNotation),
fStringPool.toString(attName) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_MORE_THAN_ONE_NOTATION_ATTRIBUTE,
XMLMessages.VC_ONE_NOTATION_PER_ELEMENT_TYPE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
return -1;
}
}
//
// save the fields
//
int chunk = fAttDefCount >> CHUNK_SHIFT;
int index = fAttDefCount & CHUNK_MASK;
ensureAttrCapacity(chunk);
fAttName[chunk][index] = attName;
fAttType[chunk][index] = attType;
fAttValidator[chunk][index] = getValidatorForAttType(attType);
fEnumeration[chunk][index] = enumeration;
fAttDefaultType[chunk][index] = attDefaultType;
fAttDefIsExternal[chunk][index] = (byte)(isExternal ? 1 : 0);
fAttValue[chunk][index] = attDefaultValue;
//
// add to the attr list for this element
//
int nextIndex = -1;
if (attDefaultValue != -1) {
nextIndex = fAttlistHead[elemChunk][elemIndex];
fAttlistHead[elemChunk][elemIndex] = fAttDefCount;
if (nextIndex == -1)
fAttlistTail[elemChunk][elemIndex] = fAttDefCount;
} else {
nextIndex = fAttlistTail[elemChunk][elemIndex];
fAttlistTail[elemChunk][elemIndex] = fAttDefCount;
if (nextIndex == -1)
fAttlistHead[elemChunk][elemIndex] = fAttDefCount;
else {
fNextAttDef[nextIndex >> CHUNK_SHIFT][nextIndex & CHUNK_MASK] = fAttDefCount;
nextIndex = -1;
}
}
fNextAttDef[chunk][index] = nextIndex;
return fAttDefCount++;
}
private AttributeValidator getValidatorForAttType(int attType) {
if (attType == fCDATASymbol) {
if (fAttValidatorCDATA == null)
fAttValidatorCDATA = new AttValidatorCDATA();
return fAttValidatorCDATA;
}
if (attType == fIDSymbol) {
if (fAttValidatorID == null)
fAttValidatorID = new AttValidatorID();
return fAttValidatorID;
}
if (attType == fIDREFSymbol) {
if (fAttValidatorIDREF == null)
fAttValidatorIDREF = new AttValidatorIDREF();
return fAttValidatorIDREF;
}
if (attType == fIDREFSSymbol) {
if (fAttValidatorIDREFS == null)
fAttValidatorIDREFS = new AttValidatorIDREFS();
return fAttValidatorIDREFS;
}
if (attType == fENTITYSymbol) {
if (fAttValidatorENTITY == null)
fAttValidatorENTITY = new AttValidatorENTITY();
return fAttValidatorENTITY;
}
if (attType == fENTITIESSymbol) {
if (fAttValidatorENTITIES == null)
fAttValidatorENTITIES = new AttValidatorENTITIES();
return fAttValidatorENTITIES;
}
if (attType == fNMTOKENSymbol) {
if (fAttValidatorNMTOKEN == null)
fAttValidatorNMTOKEN = new AttValidatorNMTOKEN();
return fAttValidatorNMTOKEN;
}
if (attType == fNMTOKENSSymbol) {
if (fAttValidatorNMTOKENS == null)
fAttValidatorNMTOKENS = new AttValidatorNMTOKENS();
return fAttValidatorNMTOKENS;
}
if (attType == fNOTATIONSymbol) {
if (fAttValidatorNOTATION == null)
fAttValidatorNOTATION = new AttValidatorNOTATION();
return fAttValidatorNOTATION;
}
if (attType == fENUMERATIONSymbol) {
if (fAttValidatorENUMERATION == null)
fAttValidatorENUMERATION = new AttValidatorENUMERATION();
return fAttValidatorENUMERATION;
}
throw new RuntimeException("VAL002 getValidatorForAttType(" + fStringPool.toString(attType) + ")");
}
private int getAttDef(int elementType, int attrName) {
int elementIndex = fStringPool.getDeclaration(elementType);
if (elementIndex == -1)
return -1;
int chunk = elementIndex >> CHUNK_SHIFT;
int index = elementIndex & CHUNK_MASK;
int attDefIndex = fAttlistHead[chunk][index];
while (attDefIndex != -1) {
chunk = attDefIndex >> CHUNK_SHIFT;
index = attDefIndex & CHUNK_MASK;
if (fAttName[chunk][index] == attrName || fStringPool.equalNames(fAttName[chunk][index], attrName))
return attDefIndex;
attDefIndex = fNextAttDef[chunk][index];
}
return -1;
}
private boolean getAttDefIsExternal(int attDefIndex) {
int chunk = attDefIndex >> CHUNK_SHIFT;
int index = attDefIndex & CHUNK_MASK;
return (fAttDefIsExternal[chunk][index] != 0);
}
private int getAttName(int attDefIndex) {
int chunk = attDefIndex >> CHUNK_SHIFT;
int index = attDefIndex & CHUNK_MASK;
return fAttName[chunk][index];
}
private int getAttValue(int attDefIndex) {
int chunk = attDefIndex >> CHUNK_SHIFT;
int index = attDefIndex & CHUNK_MASK;
return fAttValue[chunk][index];
}
private AttributeValidator getAttributeValidator(int attDefIndex) {
int chunk = attDefIndex >> CHUNK_SHIFT;
int index = attDefIndex & CHUNK_MASK;
return fAttValidator[chunk][index];
}
private int getAttType(int attDefIndex) {
int chunk = attDefIndex >> CHUNK_SHIFT;
int index = attDefIndex & CHUNK_MASK;
return fAttType[chunk][index];
}
private int getAttDefaultType(int attDefIndex) {
int chunk = attDefIndex >> CHUNK_SHIFT;
int index = attDefIndex & CHUNK_MASK;
return fAttDefaultType[chunk][index];
}
private int getEnumeration(int attDefIndex) {
int chunk = attDefIndex >> CHUNK_SHIFT;
int index = attDefIndex & CHUNK_MASK;
return fEnumeration[chunk][index];
}
private int addDefaultAttributes(int elementIndex, XMLAttrList attrList, int attrIndex, boolean validationEnabled, boolean standalone) throws Exception {
//
// Check after all specified attrs are scanned
// (1) report error for REQUIRED attrs that are missing (V_TAGc)
// (2) check that FIXED attrs have matching value (V_TAGd)
// (3) add default attrs (FIXED and NOT_FIXED)
//
int elemChunk = elementIndex >> CHUNK_SHIFT;
int elemIndex = elementIndex & CHUNK_MASK;
int attlistIndex = fAttlistHead[elemChunk][elemIndex];
int firstCheck = attrIndex;
int lastCheck = -1;
//System.err.println("specified attributes for element type " + fStringPool.toString(fElementType[elemChunk][elemIndex]));
while (attlistIndex != -1) {
int adChunk = attlistIndex >> CHUNK_SHIFT;
int adIndex = attlistIndex & CHUNK_MASK;
int attName = fAttName[adChunk][adIndex];
int attType = fAttType[adChunk][adIndex];
int attDefType = fAttDefaultType[adChunk][adIndex];
int attValue = fAttValue[adChunk][adIndex];
boolean specified = false;
boolean required = attDefType == fREQUIREDSymbol;
if (firstCheck != -1) {
boolean cdata = attType == fCDATASymbol;
if (!cdata || required || attValue != -1) {
int i = attrList.getFirstAttr(firstCheck);
while (i != -1 && (lastCheck == -1 || i <= lastCheck)) {
if (fStringPool.equalNames(attrList.getAttrName(i), attName)) {
//System.err.println(fStringPool.toString(attrList.getAttrName(i)) + " == " + fStringPool.toString(attName));
if (validationEnabled && attDefType == fFIXEDSymbol) {
int alistValue = attrList.getAttValue(i);
if (alistValue != attValue &&
!fStringPool.toString(alistValue).equals(fStringPool.toString(attValue))) {
Object[] args = { fStringPool.toString(fElementType[elemChunk][elemIndex]),
fStringPool.toString(attName),
fStringPool.toString(alistValue),
fStringPool.toString(attValue) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_FIXED_ATTVALUE_INVALID,
XMLMessages.VC_FIXED_ATTRIBUTE_DEFAULT,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
specified = true;
break;
}
//System.err.println(fStringPool.toString(attrList.getAttrName(i)) + " != " + fStringPool.toString(attName));
i = attrList.getNextAttr(i);
}
}
}
if (!specified) {
if (required) {
if (validationEnabled) {
Object[] args = { fStringPool.toString(fElementType[elemChunk][elemIndex]),
fStringPool.toString(attName) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_REQUIRED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_REQUIRED_ATTRIBUTE,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
} else if (attValue != -1) {
if (validationEnabled && standalone && fAttDefIsExternal[adChunk][adIndex] != 0) {
Object[] args = { fStringPool.toString(fElementType[elemChunk][elemIndex]),
fStringPool.toString(attName) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_DEFAULTED_ATTRIBUTE_NOT_SPECIFIED,
XMLMessages.VC_STANDALONE_DOCUMENT_DECLARATION,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
if (attType == fIDREFSymbol) {
addIdRef(attValue);
} else if (attType == fIDREFSSymbol) {
StringTokenizer tokenizer = new StringTokenizer(fStringPool.toString(attValue));
while (tokenizer.hasMoreTokens()) {
String idName = tokenizer.nextToken();
addIdRef(fStringPool.addSymbol(idName));
}
}
if (attrIndex == -1)
attrIndex = attrList.startAttrList();
int newAttr = attrList.addAttr(attName, attValue, attType, false, false);
if (lastCheck == -1)
lastCheck = newAttr;
}
}
attlistIndex = fNextAttDef[adChunk][adIndex];
}
return attrIndex;
}
//
//
//
protected boolean addId(int idIndex) {
//System.err.println("addId(" + fStringPool.toString(idIndex) + ") " + idIndex);
Integer key = new Integer(idIndex);
if (fIdDefs == null)
fIdDefs = new Hashtable();
else if (fIdDefs.containsKey(key))
return false;
if (fNullValue == null)
fNullValue = new Object();
fIdDefs.put(key, fNullValue/*new Integer(elementType)*/);
return true;
}
protected void addIdRef(int idIndex) {
//System.err.println("addIdRef(" + fStringPool.toString(idIndex) + ") " + idIndex);
Integer key = new Integer(idIndex);
if (fIdDefs != null && fIdDefs.containsKey(key))
return;
if (fIdRefs == null)
fIdRefs = new Hashtable();
else if (fIdRefs.containsKey(key))
return;
if (fNullValue == null)
fNullValue = new Object();
fIdRefs.put(key, fNullValue/*new Integer(elementType)*/);
}
/**
* Check that all ID references were to ID attributes present in the document.
* <p>
* This method is a convenience call that allows the validator to do any id ref
* checks above and beyond those done by the scanner. The scanner does the checks
* specificied in the XML spec, i.e. that ID refs refer to ids which were
* eventually defined somewhere in the document.
* <p>
* If the validator is for a Schema perhaps, which defines id semantics beyond
* those of the XML specificiation, this is where that extra checking would be
* done. For most validators, this is a no-op.
*
* @exception Exception Thrown on error.
*/
private void checkIdRefs() throws Exception {
if (fIdRefs == null)
return;
Enumeration en = fIdRefs.keys();
while (en.hasMoreElements()) {
Integer key = (Integer)en.nextElement();
if (fIdDefs == null || !fIdDefs.containsKey(key)) {
Object[] args = { fStringPool.toString(key.intValue()) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_ELEMENT_WITH_ID_REQUIRED,
XMLMessages.VC_IDREF,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
}
}
/**
* Checks that all declared elements refer to declared elements
* in their content models. This method calls out to the error
* handler to indicate warnings.
*/
private void checkDeclaredElements() throws Exception {
for (int i = 0; i < fElementCount; i++) {
int type = getContentSpecType(i);
if (type == fMIXEDSymbol || type == fCHILDRENSymbol) {
int chunk = i >> CHUNK_SHIFT;
int index = i & CHUNK_MASK;
int contentSpecIndex = fContentSpec[chunk][index];
checkDeclaredElements(i, contentSpecIndex);
}
}
}
/**
* Does a recursive (if necessary) check on the specified element's
* content spec to make sure that all children refer to declared
* elements.
* <p>
* This method assumes that it will only be called when there is
* a validation handler.
*/
private void checkDeclaredElements(int elementIndex, int contentSpecIndex) throws Exception {
// get spec type and value
int chunk = contentSpecIndex >> CHUNK_SHIFT;
int index = contentSpecIndex & CHUNK_MASK;
int type = fNodeType[chunk][index];
int value = fNodeValue[chunk][index];
// handle type
switch (type) {
// #PCDATA | element
case XMLContentSpecNode.CONTENTSPECNODE_LEAF: {
// perform check for declared element
if (value != -1 && fStringPool.getDeclaration(value) == -1) {
int elemChunk = elementIndex >> CHUNK_SHIFT;
int elemIndex = elementIndex & CHUNK_MASK;
int elementType = fElementType[elemChunk][elemIndex];
Object[] args = { fStringPool.toString(elementType),
fStringPool.toString(value) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XML_DOMAIN,
XMLMessages.MSG_UNDECLARED_ELEMENT_IN_CONTENTSPEC,
XMLMessages.P45_UNDECLARED_ELEMENT_IN_CONTENTSPEC,
args,
XMLErrorReporter.ERRORTYPE_WARNING);
}
break;
}
// (...)? | (...)* | (...)+
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_ONE:
case XMLContentSpecNode.CONTENTSPECNODE_ZERO_OR_MORE:
case XMLContentSpecNode.CONTENTSPECNODE_ONE_OR_MORE: {
checkDeclaredElements(elementIndex, value);
break;
}
// (... , ...) | (... | ...)
case XMLContentSpecNode.CONTENTSPECNODE_CHOICE:
case XMLContentSpecNode.CONTENTSPECNODE_SEQ: {
checkDeclaredElements(elementIndex, value);
if (++index == CHUNK_SIZE) {
chunk++;
index = 0;
}
checkDeclaredElements(elementIndex, fNodeValue[chunk][index]);
break;
}
}
}
}
| true | true | public boolean startElement(int elementType, XMLAttrList attrList) throws Exception {
int attrIndex = fAttrIndex;
fAttrIndex = -1;
if (fElementDeclCount == 0 && fAttlistDeclCount == 0 && !fValidating && !fNamespacesEnabled) {
return false;
}
int elementIndex = fStringPool.getDeclaration(elementType);
int contentSpecType = (elementIndex == -1) ? -1 : getContentSpecType(elementIndex);
if (contentSpecType == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
elementType);
}
if (fAttlistDeclCount != 0 && elementIndex != -1) {
attrIndex = addDefaultAttributes(elementIndex, attrList, attrIndex, fValidating, fStandaloneReader != -1);
}
if (DEBUG_PRINT_ATTRIBUTES) {
String element = fStringPool.toString(elementType);
System.out.print("startElement: <" + element);
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
//
// Namespace support
//
if (fNamespacesEnabled) {
fNamespacesScope.increaseDepth();
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, uri);
} else {
int attPrefix = fStringPool.getPrefixForQName(attName);
if (attPrefix == fNamespacesPrefix) {
attPrefix = fStringPool.getLocalPartForQName(attName);
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(attPrefix, uri);
}
}
index = attrList.getNextAttr(index);
}
}
int prefix = fStringPool.getPrefixForQName(elementType);
int elementURI;
if (prefix == -1) {
elementURI = fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING);
if (elementURI != -1) {
fStringPool.setURIForQName(elementType, elementURI);
}
} else {
elementURI = fNamespacesScope.getNamespaceForPrefix(prefix);
if (elementURI == -1) {
Object[] args = { fStringPool.toString(prefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
fStringPool.setURIForQName(elementType, elementURI);
}
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = fStringPool.getPrefixForQName(attName);
if (attPrefix != fNamespacesPrefix) {
if (attPrefix == -1) {
fStringPool.setURIForQName(attName, elementURI);
} else {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
fStringPool.setURIForQName(attName, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
}
if (fElementDepth >= 0) {
int[] children = fElementChildren[fElementDepth];
int childCount = fElementChildCount[fElementDepth];
try {
children[childCount] = elementType;
} catch (NullPointerException ex) {
children = fElementChildren[fElementDepth] = new int[256];
childCount = 0; // should really assert this...
children[childCount] = elementType;
} catch (ArrayIndexOutOfBoundsException ex) {
int[] newChildren = new int[childCount * 2];
System.arraycopy(children, 0, newChildren, 0, childCount);
children = fElementChildren[fElementDepth] = newChildren;
children[childCount] = elementType;
}
fElementChildCount[fElementDepth] = ++childCount;
}
fElementDepth++;
if (fElementDepth == fElementTypeStack.length) {
int[] newStack = new int[fElementDepth * 2];
System.arraycopy(fElementTypeStack, 0, newStack, 0, fElementDepth);
fElementTypeStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fElementIndexStack, 0, newStack, 0, fElementDepth);
fElementIndexStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, fElementDepth);
fContentSpecTypeStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fElementChildCount, 0, newStack, 0, fElementDepth);
fElementChildCount = newStack;
int[][] newContentStack = new int[fElementDepth * 2][];
System.arraycopy(fElementChildren, 0, newContentStack, 0, fElementDepth);
fElementChildren = newContentStack;
}
fCurrentElementType = elementType;
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
fElementTypeStack[fElementDepth] = elementType;
fElementIndexStack[fElementDepth] = elementIndex;
fContentSpecTypeStack[fElementDepth] = contentSpecType;
fElementChildCount[fElementDepth] = 0;
return contentSpecType == fCHILDRENSymbol;
}
| public boolean startElement(int elementType, XMLAttrList attrList) throws Exception {
int attrIndex = fAttrIndex;
fAttrIndex = -1;
if (fElementDeclCount == 0 && fAttlistDeclCount == 0 && !fValidating && !fNamespacesEnabled) {
return false;
}
int elementIndex = fStringPool.getDeclaration(elementType);
int contentSpecType = (elementIndex == -1) ? -1 : getContentSpecType(elementIndex);
if (contentSpecType == -1 && fValidating) {
reportRecoverableXMLError(XMLMessages.MSG_ELEMENT_NOT_DECLARED,
XMLMessages.VC_ELEMENT_VALID,
elementType);
}
if (fAttlistDeclCount != 0 && elementIndex != -1) {
attrIndex = addDefaultAttributes(elementIndex, attrList, attrIndex, fValidating, fStandaloneReader != -1);
}
if (DEBUG_PRINT_ATTRIBUTES) {
String element = fStringPool.toString(elementType);
System.out.print("startElement: <" + element);
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
System.out.print(" " + fStringPool.toString(attrList.getAttrName(index)) + "=\"" +
fStringPool.toString(attrList.getAttValue(index)) + "\"");
index = attrList.getNextAttr(index);
}
}
System.out.println(">");
}
//
// Namespace support
//
if (fNamespacesEnabled) {
fNamespacesScope.increaseDepth();
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (fStringPool.equalNames(attName, fNamespacesPrefix)) {
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(StringPool.EMPTY_STRING, uri);
} else {
int attPrefix = fStringPool.getPrefixForQName(attName);
if (attPrefix == fNamespacesPrefix) {
attPrefix = fStringPool.getLocalPartForQName(attName);
int uri = fStringPool.addSymbol(attrList.getAttValue(index));
fNamespacesScope.setNamespaceForPrefix(attPrefix, uri);
}
}
index = attrList.getNextAttr(index);
}
}
int prefix = fStringPool.getPrefixForQName(elementType);
int elementURI;
if (prefix == -1) {
elementURI = fNamespacesScope.getNamespaceForPrefix(StringPool.EMPTY_STRING);
if (elementURI != -1) {
fStringPool.setURIForQName(elementType, elementURI);
}
} else {
elementURI = fNamespacesScope.getNamespaceForPrefix(prefix);
if (elementURI == -1) {
Object[] args = { fStringPool.toString(prefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
fStringPool.setURIForQName(elementType, elementURI);
}
if (attrIndex != -1) {
int index = attrList.getFirstAttr(attrIndex);
while (index != -1) {
int attName = attrList.getAttrName(index);
if (!fStringPool.equalNames(attName, fNamespacesPrefix)) {
int attPrefix = fStringPool.getPrefixForQName(attName);
if (attPrefix != fNamespacesPrefix) {
//if (attPrefix == -1) {
// Confirmed by NS spec, and all IBM devs...
// An Attr w/o a prefix should not inherit
// the Element's prefix. -rip
//fStringPool.setURIForQName(attName, elementURI);
//} else {
if (attPrefix != -1) {
int uri = fNamespacesScope.getNamespaceForPrefix(attPrefix);
if (uri == -1) {
Object[] args = { fStringPool.toString(attPrefix) };
fErrorReporter.reportError(fErrorReporter.getLocator(),
XMLMessages.XMLNS_DOMAIN,
XMLMessages.MSG_PREFIX_DECLARED,
XMLMessages.NC_PREFIX_DECLARED,
args,
XMLErrorReporter.ERRORTYPE_RECOVERABLE_ERROR);
}
fStringPool.setURIForQName(attName, uri);
}
}
}
index = attrList.getNextAttr(index);
}
}
}
if (fElementDepth >= 0) {
int[] children = fElementChildren[fElementDepth];
int childCount = fElementChildCount[fElementDepth];
try {
children[childCount] = elementType;
} catch (NullPointerException ex) {
children = fElementChildren[fElementDepth] = new int[256];
childCount = 0; // should really assert this...
children[childCount] = elementType;
} catch (ArrayIndexOutOfBoundsException ex) {
int[] newChildren = new int[childCount * 2];
System.arraycopy(children, 0, newChildren, 0, childCount);
children = fElementChildren[fElementDepth] = newChildren;
children[childCount] = elementType;
}
fElementChildCount[fElementDepth] = ++childCount;
}
fElementDepth++;
if (fElementDepth == fElementTypeStack.length) {
int[] newStack = new int[fElementDepth * 2];
System.arraycopy(fElementTypeStack, 0, newStack, 0, fElementDepth);
fElementTypeStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fElementIndexStack, 0, newStack, 0, fElementDepth);
fElementIndexStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fContentSpecTypeStack, 0, newStack, 0, fElementDepth);
fContentSpecTypeStack = newStack;
newStack = new int[fElementDepth * 2];
System.arraycopy(fElementChildCount, 0, newStack, 0, fElementDepth);
fElementChildCount = newStack;
int[][] newContentStack = new int[fElementDepth * 2][];
System.arraycopy(fElementChildren, 0, newContentStack, 0, fElementDepth);
fElementChildren = newContentStack;
}
fCurrentElementType = elementType;
fCurrentElementIndex = elementIndex;
fCurrentContentSpecType = contentSpecType;
fElementTypeStack[fElementDepth] = elementType;
fElementIndexStack[fElementDepth] = elementIndex;
fContentSpecTypeStack[fElementDepth] = contentSpecType;
fElementChildCount[fElementDepth] = 0;
return contentSpecType == fCHILDRENSymbol;
}
|
diff --git a/src/bt.java b/src/bt.java
index dc5877d..fb2acaf 100644
--- a/src/bt.java
+++ b/src/bt.java
@@ -1,89 +1,89 @@
public class bt extends fu {
private int a;
public bt(int paramInt) {
super(paramInt);
this.a = (paramInt + 256);
a(ga.m[(paramInt + 256)].a(2));
}
@Override
public boolean a(hl paramhl, fx paramfx, eo parameo, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
// hMod: Bail if we have nothing of the items in hand
if (paramhl.a == 0) {
return false;
}
// hMod: Store blockInfo of the one we clicked
int blockClickedId = parameo.a(paramInt1, paramInt2, paramInt3);
Block blockClicked = new Block(blockClickedId, paramInt1, paramInt2, paramInt3 );
if (blockClickedId == ga.aS.bh) {
paramInt4 = 0;
} else {
if (paramInt4 == 0) {
paramInt2--;
}
if (paramInt4 == 1) {
paramInt2++;
}
if (paramInt4 == 2) {
paramInt3--;
}
if (paramInt4 == 3) {
paramInt3++;
}
if (paramInt4 == 4) {
paramInt1--;
}
if (paramInt4 == 5) {
paramInt1++;
}
}
// hMod: Store faceClicked (must be here to have the 'snow' special case).
blockClicked.setFaceClicked(Block.Face.fromId( paramInt4 ));
// hMod: And the block we're about to place
Block blockPlaced = new Block( this.a, paramInt1, paramInt2, paramInt3 );
// hMod Store all the old settings 'externally' in case someone changes blockPlaced.
int oldMaterial = parameo.a(paramInt1, paramInt2, paramInt3);
int oldData = parameo.b(paramInt1, paramInt2, paramInt3);
if (parameo.a(this.a, paramInt1, paramInt2, paramInt3, false)) {
ga localga = ga.m[this.a];
//hMod: Take over block placement
if (parameo.a(paramInt1, paramInt2, paramInt3, this.a)) {
// hMod: Check if this was playerPlaced and call the hook
if (paramfx instanceof er && (Boolean) etc.getLoader().callHook(PluginLoader.Hook.BLOCK_PLACE, new Object[]{((er)paramfx).getPlayer(), blockPlaced, blockClicked, new Item(paramhl)})) {
// hMod: Undo!
// Specialcase iceblocks, replace with 'glass' first (so it doesnt explode into water)
if (this.a == 79) {
parameo.a(paramInt1, paramInt2, paramInt3, 20 );
}
parameo.a(paramInt1, paramInt2, paramInt3, oldMaterial );
parameo.c(paramInt1, paramInt2, paramInt3, oldData );
// hMod: Refund the item the player lost >.>
// or not, this occasionally dupes items! we'll do this when notch implements serverside invs.
//((er)paramfx).a.b(new ff(paramhl, 1));
return false;
} else {
parameo.f(paramInt1, paramInt2, paramInt3);
parameo.g(paramInt1, paramInt2, paramInt3, this.a);
ga.m[this.a].c(parameo, paramInt1, paramInt2, paramInt3, paramInt4);
- ga.m[this.a].a(parameo, paramInt1, paramInt2, paramInt3, paramfx);
- parameo.a(paramInt1 + 0.5F, paramInt2 + 0.5F, paramInt3 + 0.5F, localga.bq.c(), (localga.bq.a() + 1.0F) / 2.0F,
- localga.bq.b() * 0.8F);
+ // hMod: Downcast fx to jy; demanded for inheritane to work >.>
+ ga.m[this.a].a(parameo, paramInt1, paramInt2, paramInt3, (jy)paramfx);
+ parameo.a(paramInt1 + 0.5F, paramInt2 + 0.5F, paramInt3 + 0.5F, localga.bq.c(), (localga.bq.a() + 1.0F) / 2.0F, localga.bq.b() * 0.8F);
paramhl.a -= 1;
}
}
}
return true;
}
}
| true | true | public boolean a(hl paramhl, fx paramfx, eo parameo, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
// hMod: Bail if we have nothing of the items in hand
if (paramhl.a == 0) {
return false;
}
// hMod: Store blockInfo of the one we clicked
int blockClickedId = parameo.a(paramInt1, paramInt2, paramInt3);
Block blockClicked = new Block(blockClickedId, paramInt1, paramInt2, paramInt3 );
if (blockClickedId == ga.aS.bh) {
paramInt4 = 0;
} else {
if (paramInt4 == 0) {
paramInt2--;
}
if (paramInt4 == 1) {
paramInt2++;
}
if (paramInt4 == 2) {
paramInt3--;
}
if (paramInt4 == 3) {
paramInt3++;
}
if (paramInt4 == 4) {
paramInt1--;
}
if (paramInt4 == 5) {
paramInt1++;
}
}
// hMod: Store faceClicked (must be here to have the 'snow' special case).
blockClicked.setFaceClicked(Block.Face.fromId( paramInt4 ));
// hMod: And the block we're about to place
Block blockPlaced = new Block( this.a, paramInt1, paramInt2, paramInt3 );
// hMod Store all the old settings 'externally' in case someone changes blockPlaced.
int oldMaterial = parameo.a(paramInt1, paramInt2, paramInt3);
int oldData = parameo.b(paramInt1, paramInt2, paramInt3);
if (parameo.a(this.a, paramInt1, paramInt2, paramInt3, false)) {
ga localga = ga.m[this.a];
//hMod: Take over block placement
if (parameo.a(paramInt1, paramInt2, paramInt3, this.a)) {
// hMod: Check if this was playerPlaced and call the hook
if (paramfx instanceof er && (Boolean) etc.getLoader().callHook(PluginLoader.Hook.BLOCK_PLACE, new Object[]{((er)paramfx).getPlayer(), blockPlaced, blockClicked, new Item(paramhl)})) {
// hMod: Undo!
// Specialcase iceblocks, replace with 'glass' first (so it doesnt explode into water)
if (this.a == 79) {
parameo.a(paramInt1, paramInt2, paramInt3, 20 );
}
parameo.a(paramInt1, paramInt2, paramInt3, oldMaterial );
parameo.c(paramInt1, paramInt2, paramInt3, oldData );
// hMod: Refund the item the player lost >.>
// or not, this occasionally dupes items! we'll do this when notch implements serverside invs.
//((er)paramfx).a.b(new ff(paramhl, 1));
return false;
} else {
parameo.f(paramInt1, paramInt2, paramInt3);
parameo.g(paramInt1, paramInt2, paramInt3, this.a);
ga.m[this.a].c(parameo, paramInt1, paramInt2, paramInt3, paramInt4);
ga.m[this.a].a(parameo, paramInt1, paramInt2, paramInt3, paramfx);
parameo.a(paramInt1 + 0.5F, paramInt2 + 0.5F, paramInt3 + 0.5F, localga.bq.c(), (localga.bq.a() + 1.0F) / 2.0F,
localga.bq.b() * 0.8F);
paramhl.a -= 1;
}
}
}
return true;
}
| public boolean a(hl paramhl, fx paramfx, eo parameo, int paramInt1, int paramInt2, int paramInt3, int paramInt4) {
// hMod: Bail if we have nothing of the items in hand
if (paramhl.a == 0) {
return false;
}
// hMod: Store blockInfo of the one we clicked
int blockClickedId = parameo.a(paramInt1, paramInt2, paramInt3);
Block blockClicked = new Block(blockClickedId, paramInt1, paramInt2, paramInt3 );
if (blockClickedId == ga.aS.bh) {
paramInt4 = 0;
} else {
if (paramInt4 == 0) {
paramInt2--;
}
if (paramInt4 == 1) {
paramInt2++;
}
if (paramInt4 == 2) {
paramInt3--;
}
if (paramInt4 == 3) {
paramInt3++;
}
if (paramInt4 == 4) {
paramInt1--;
}
if (paramInt4 == 5) {
paramInt1++;
}
}
// hMod: Store faceClicked (must be here to have the 'snow' special case).
blockClicked.setFaceClicked(Block.Face.fromId( paramInt4 ));
// hMod: And the block we're about to place
Block blockPlaced = new Block( this.a, paramInt1, paramInt2, paramInt3 );
// hMod Store all the old settings 'externally' in case someone changes blockPlaced.
int oldMaterial = parameo.a(paramInt1, paramInt2, paramInt3);
int oldData = parameo.b(paramInt1, paramInt2, paramInt3);
if (parameo.a(this.a, paramInt1, paramInt2, paramInt3, false)) {
ga localga = ga.m[this.a];
//hMod: Take over block placement
if (parameo.a(paramInt1, paramInt2, paramInt3, this.a)) {
// hMod: Check if this was playerPlaced and call the hook
if (paramfx instanceof er && (Boolean) etc.getLoader().callHook(PluginLoader.Hook.BLOCK_PLACE, new Object[]{((er)paramfx).getPlayer(), blockPlaced, blockClicked, new Item(paramhl)})) {
// hMod: Undo!
// Specialcase iceblocks, replace with 'glass' first (so it doesnt explode into water)
if (this.a == 79) {
parameo.a(paramInt1, paramInt2, paramInt3, 20 );
}
parameo.a(paramInt1, paramInt2, paramInt3, oldMaterial );
parameo.c(paramInt1, paramInt2, paramInt3, oldData );
// hMod: Refund the item the player lost >.>
// or not, this occasionally dupes items! we'll do this when notch implements serverside invs.
//((er)paramfx).a.b(new ff(paramhl, 1));
return false;
} else {
parameo.f(paramInt1, paramInt2, paramInt3);
parameo.g(paramInt1, paramInt2, paramInt3, this.a);
ga.m[this.a].c(parameo, paramInt1, paramInt2, paramInt3, paramInt4);
// hMod: Downcast fx to jy; demanded for inheritane to work >.>
ga.m[this.a].a(parameo, paramInt1, paramInt2, paramInt3, (jy)paramfx);
parameo.a(paramInt1 + 0.5F, paramInt2 + 0.5F, paramInt3 + 0.5F, localga.bq.c(), (localga.bq.a() + 1.0F) / 2.0F, localga.bq.b() * 0.8F);
paramhl.a -= 1;
}
}
}
return true;
}
|
diff --git a/Exomizer/junit/src/exomizer/tests/UCSCKGParserTest.java b/Exomizer/junit/src/exomizer/tests/UCSCKGParserTest.java
index 477521ea..f4841f07 100644
--- a/Exomizer/junit/src/exomizer/tests/UCSCKGParserTest.java
+++ b/Exomizer/junit/src/exomizer/tests/UCSCKGParserTest.java
@@ -1,78 +1,78 @@
package exomizer.tests;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.PrintStream;
import java.util.ArrayList;
import exomizer.io.KGLine;
import exomizer.io.UCSCKGParser;
import exomizer.common.Constants;
import org.junit.Test;
import org.junit.BeforeClass;
import junit.framework.Assert;
public class UCSCKGParserTest implements Constants {
private static UCSCKGParser parser = null;
private ArrayList<KGLine> knownGeneList=null;
@BeforeClass public static void setUp() throws IOException {
System.out.println("ABout");
File tmp = File.createTempFile("ucsckg-test","ucsckg-test");
PrintStream ps = new PrintStream(new FileOutputStream(tmp));
ps.append("uc009vis.3 chr1 - 14361 16765 14361 14361 4 14361,14969,15795,16606, 14829,15038,15942,16765, uc009vis.3\n");
ps.close();
- String mypath="/home/peter/data/ucsc/knownGene.txt";
+ String mypath="/home/peter/data/ucsc";
//parser = new UCSCKGParser(tmp.getAbsolutePath());
parser = new UCSCKGParser(mypath);
}
/* @Before
public void setUp() throws IOException
{
System.out.println("ABout");
File tmp = File.createTempFile("ucsckg-test","ucsckg-test");
System.out.println("ABout to read." +tmp.getAbsolutePath());
PrintStream ps = new PrintStream(new FileOutputStream(tmp));
ps.append("uc009vis.3 chr1 - 14361 16765 14361 14361 4 14361,14969,15795,16606, 14829,15038,15942,16765, uc009vis.3\n");
ps.append("uc009viv.2 chr1 - 14406 29370 14406 14406 7 14406,16857,17232,17605,17914,24737,29320, 16765,17055,17368,17742,18061,24891,29370, uc009viv.2\n");
ps.close();
System.out.println("ABout to parse." +tmp.getAbsolutePath());
this.parser = new UCSCKGParser(tmp.getAbsolutePath());
parser.parseFile();
this.knownGeneList = parser.getKnownGeneList();
}
*/
@Test public void testSizeOfKGList() {
try {
parser.parseFile();
} catch (Throwable e) {
System.out.println("EX");//e.printTrackTrace();
}
int N = 3;//this.knownGeneList.size();
Assert.assertEquals(1,N);
}
@Test public void testSizeOfKGLis2t() {
int N = 3;//this.knownGeneList.size();
Assert.assertEquals(1,N);
}
}
| true | true | @BeforeClass public static void setUp() throws IOException {
System.out.println("ABout");
File tmp = File.createTempFile("ucsckg-test","ucsckg-test");
PrintStream ps = new PrintStream(new FileOutputStream(tmp));
ps.append("uc009vis.3 chr1 - 14361 16765 14361 14361 4 14361,14969,15795,16606, 14829,15038,15942,16765, uc009vis.3\n");
ps.close();
String mypath="/home/peter/data/ucsc/knownGene.txt";
//parser = new UCSCKGParser(tmp.getAbsolutePath());
parser = new UCSCKGParser(mypath);
}
| @BeforeClass public static void setUp() throws IOException {
System.out.println("ABout");
File tmp = File.createTempFile("ucsckg-test","ucsckg-test");
PrintStream ps = new PrintStream(new FileOutputStream(tmp));
ps.append("uc009vis.3 chr1 - 14361 16765 14361 14361 4 14361,14969,15795,16606, 14829,15038,15942,16765, uc009vis.3\n");
ps.close();
String mypath="/home/peter/data/ucsc";
//parser = new UCSCKGParser(tmp.getAbsolutePath());
parser = new UCSCKGParser(mypath);
}
|
diff --git a/owsproxyserver/src/org/deegree/ogcwebservices/wms/operation/GetFeatureInfo.java b/owsproxyserver/src/org/deegree/ogcwebservices/wms/operation/GetFeatureInfo.java
index 88271f9..5904e5f 100644
--- a/owsproxyserver/src/org/deegree/ogcwebservices/wms/operation/GetFeatureInfo.java
+++ b/owsproxyserver/src/org/deegree/ogcwebservices/wms/operation/GetFeatureInfo.java
@@ -1,633 +1,636 @@
/*---------------- FILE HEADER ------------------------------------------
This file is part of deegree.
Copyright (C) 2001-2006 by:
EXSE, Department of Geography, University of Bonn
http://www.giub.uni-bonn.de/deegree/
lat/lon GmbH
http://www.lat-lon.de
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:
Andreas Poth
lat/lon GmbH
Aennchenstr. 19
53177 Bonn
Germany
E-Mail: [email protected]
Prof. Dr. Klaus Greve
Department of Geography
University of Bonn
Meckenheimer Allee 166
53115 Bonn
Germany
E-Mail: [email protected]
---------------------------------------------------------------------------*/
package org.deegree.ogcwebservices.wms.operation;
import java.awt.Point;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.StringTokenizer;
import org.deegree.framework.log.ILogger;
import org.deegree.framework.log.LoggerFactory;
import org.deegree.framework.util.ColorUtils;
import org.deegree.framework.util.StringTools;
import org.deegree.graphics.sld.StyledLayerDescriptor;
import org.deegree.ogcbase.ExceptionCode;
import org.deegree.ogcwebservices.InconsistentRequestException;
import org.deegree.ogcwebservices.OGCWebServiceException;
import org.deegree.ogcwebservices.wms.InvalidPointException;
/**
* @author Katharina Lupp <a href="mailto:[email protected]">Katharina Lupp </a>
* @version $Revision: 1.18 $ $Date: 2006/11/22 15:38:31 $
*/
public class GetFeatureInfo extends WMSRequestBase {
private static final long serialVersionUID = 1197866346790857492L;
private static final ILogger LOGGER = LoggerFactory.getLogger( GetFeatureInfo.class );
private List<String> queryLayers = null;
private Point clickPoint = null;
private String exceptions = null;
private String infoFormat = null;
private StyledLayerDescriptor sld = null;
private GetMap getMapRequestCopy = null;
private int featureCount = 1;
private boolean infoFormatIsDefault = false;
/**
* creates a <tt>WMSFeatureInfoRequest</tt> from the request parameters.
*
* @return an instance of <tt>WMSFeatureInfoRequest</tt>
* @param version
* VERSION=version (R): Request version.
* @param id the request id
* @param queryLayers
* QUERY_LAYERS=layer_list (R): Comma-separated list of one or
* more layers to be queried.
* @param getMapRequestCopy
* <map_request_copy> (R): Partial copy of the Map request
* parameters that generated the map for which information is
* desired.
* @param infoFormat
* INFO_FORMAT=output_format (O): Return format of feature
* information (MIME type).
* @param featureCount
* FEATURE_COUNT=number (O): Number of features about which to
* return information (default=1).
* @param clickPoint
* X=pixel_column (R): X coordinate in pixels of feature
* (measured from upper left corner=0) Y=pixel_row (R): Y
* coordinate in pixels of feature (measured from upper left
* corner=0)
* @param exceptions
* EXCEPTIONS=exception_format (O): The format in which
* exceptions are to be reported by the WMS
* (default=application/vnd.ogc.se_xml).
* @param sld
* StyledLayerDescriptor
* @param vendorSpecificParameter
* Vendor-specific parameters (O): Optional experimental
* parameters.
*/
public static GetFeatureInfo create( String version, String id, String[] queryLayers,
GetMap getMapRequestCopy, String infoFormat,
int featureCount, java.awt.Point clickPoint,
String exceptions, StyledLayerDescriptor sld,
Map<String, String> vendorSpecificParameter ) {
LOGGER.entering();
GetFeatureInfo fir = new GetFeatureInfo( version, id, queryLayers, getMapRequestCopy,
infoFormat, featureCount, clickPoint, exceptions,
sld, vendorSpecificParameter );
LOGGER.exiting();
return fir;
}
/**
* creates a <tt>WMSFeatureInfoRequest</tt> from a <tt>HashMap</tt> that
* contains the request parameters as key-value-pairs. Keys are expected to
* be in upper case notation.
*
* @param model
* <tt>HashMap</tt> containing the request parameters
* @return an instance of <tt>WMSFeatureInfoRequest</tt>
* @throws OGCWebServiceException
*/
public static GetFeatureInfo create( Map<String, String> model )
throws OGCWebServiceException {
LOGGER.entering();
// VERSION
String version = model.get( "VERSION" );
if ( version == null ) {
version = model.get( "WMTVER" );
}
if ( version == null ) {
throw new InconsistentRequestException(
"VERSION-value must be set in the GetFeatureInfo request" );
}
// Some WMS Client, like ArcMAP, only send the QUERY_LAYERS parameter without a LAYERS parameter.
// However, some WMS server like MapServer fail in case there is no LAYERS parameter send.
// Thus, we add a LAYERS parameter in case only a QUERY_LAYERS parameter is available.
// -> Keep this in sync with the code in com.camptocamp.owsproxy.OWSProxyServlet::doGet
if (model.containsKey("QUERY_LAYERS") && !model.containsKey("LAYERS")) {
model.put("LAYERS", model.get("QUERY_LAYERS"));
}
boolean is130 = ( "1.3.0".compareTo( version ) <= 0 );
// ID
String id = model.get( "ID" );
if ( id == null ) {
throw new InconsistentRequestException(
"ID-value must be set in the GetFeatureInfo request" );
}
// QUERY_LAYERS
String layerlist = model.remove( "QUERY_LAYERS" );
String[] queryLayers = null;
if ( layerlist != null ) {
StringTokenizer st = new StringTokenizer( layerlist, "," );
queryLayers = new String[st.countTokens()];
int i = 0;
while ( st.hasMoreTokens() ) {
queryLayers[i++] = st.nextToken();
}
} else {
throw new InconsistentRequestException(
"QUERY_LAYERS-value must be set in the GetFeatureInfo request" );
}
// INFO_FORMAT (mime-type)
String infoFormat = model.remove( "INFO_FORMAT" );
boolean infoFormatDefault = false;
if ( infoFormat == null ) {
infoFormat = "application/vnd.ogc.gml";
infoFormatDefault = true;
}
// FEATURE_COUNT (default=1)
String feco = model.remove( "FEATURE_COUNT" );
int featureCount = 1;
if ( feco != null ) {
featureCount = Integer.parseInt( feco.trim() );
}
if ( featureCount < 0 ) {
featureCount = 1;
}
// X, Y (measured from upper left corner=0)
String X;
String Y;
if ( is130 ) {
X = "I";
Y = "J";
} else {
X = "X";
Y = "Y";
}
String xstring = model.remove( X );
String ystring = model.remove( Y );
java.awt.Point clickPoint = null;
if ( ( xstring != null ) & ( ystring != null ) ) {
try {
int x = Integer.parseInt( xstring.trim() );
int y = Integer.parseInt( ystring.trim() );
clickPoint = new java.awt.Point( x, y );
} catch ( NumberFormatException nfe ) {
LOGGER.logError( nfe.getLocalizedMessage(), nfe );
throw new OGCWebServiceException( "GetFeatureInfo", "Invalid point parameter",
ExceptionCode.INVALID_POINT );
}
} else {
throw new InconsistentRequestException(
X
+ "- and/or "
+ Y
+ "-value must be set in the GetFeatureInfo request" );
}
// EXCEPTIONS (default=application/vnd.ogc.se_xml)
String exceptions = model.get( "EXCEPTIONS" );
if ( exceptions == null ) {
if ( is130 ) {
exceptions = "XML";
} else {
exceptions = "application/vnd.ogc.se_xml";
}
}
// <map_request_copy>
GetMap getMapRequestCopy = null;
try {
- getMapRequestCopy = GetMap.create( model );
+ if(!model.containsKey("FORMAT")){
+ model.put("FORMAT", "image/jpeg");
+ }
+ getMapRequestCopy = GetMap.create( model );
} catch ( Exception ex ) {
throw new InconsistentRequestException(
"\nAn Exception "
+ "occured in creating the GetMap request-copy included in the "
+ "GetFeatureInfo-Operations:\n"
+ "--> Location: WMSProtocolFactory, createGetFeatureInfoRequest(int, HashMap)\n"
+ ex.getMessage() );
}
// check for consistency
if ( clickPoint.x > getMapRequestCopy.getWidth()
|| clickPoint.y > getMapRequestCopy.getHeight() ) {
throw new InvalidPointException( "The requested point is not valid." );
}
// VendorSpecificParameter; because all defined parameters has been
// removed
// from the model the vendorSpecificParameters are what left
Map<String, String> vendorSpecificParameter = model;
// StyledLayerDescriptor
StyledLayerDescriptor sld = getMapRequestCopy.getStyledLayerDescriptor();
LOGGER.exiting();
GetFeatureInfo res = create( version, id, queryLayers, getMapRequestCopy, infoFormat,
featureCount, clickPoint, exceptions, sld,
vendorSpecificParameter );
res.infoFormatIsDefault = infoFormatDefault;
return res;
}
/**
* Creates a new WMSFeatureInfoRequest_Impl object.
*
* @param version
* @param id
* @param queryLayers
* @param getMapRequestCopy
* @param infoFormat
* @param featureCount
* @param clickPoint
* @param exceptions
* @param sld
* @param vendorSpecificParameter
*/
private GetFeatureInfo( String version, String id, String[] queryLayers,
GetMap getMapRequestCopy, String infoFormat, int featureCount,
Point clickPoint, String exceptions, StyledLayerDescriptor sld,
Map<String, String> vendorSpecificParameter ) {
super( version, id, vendorSpecificParameter );
this.queryLayers = new ArrayList<String>();
setQueryLayers( queryLayers );
setGetMapRequestCopy( getMapRequestCopy );
setGetMapRequestCopy( getMapRequestCopy );
setFeatureCount( featureCount );
setClickPoint( clickPoint );
setExceptions( exceptions );
setStyledLayerDescriptor( sld );
setInfoFormat( infoFormat );
}
/**
* <map request copy> is not a name/value pair like the other parameters.
* Instead, most of the GetMap request parameters that generated the
* original map are repeated. Two are omitted because GetFeatureInfo
* provides its own values: VERSION and REQUEST. The remainder of the GetMap
* request shall be embedded contiguously in the GetFeatureInfo request.
* @return a copy of the original request
*/
public GetMap getGetMapRequestCopy() {
return getMapRequestCopy;
}
/**
* sets the <GetMapRequestCopy>
* @param getMapRequestCopy
*/
public void setGetMapRequestCopy( GetMap getMapRequestCopy ) {
this.getMapRequestCopy = getMapRequestCopy;
}
/**
* The required QUERY_LAYERS parameter states the map layer(s) from which
* feature information is desired to be retrieved. Its value is a comma-
* separated list of one or more map layers that are returned as an array.
* This parameter shall contain at least one layer name, but may contain
* fewer layers than the original GetMap request.
* <p>
* </p>
* If any layer in this list is not contained in the Capabilities XML of the
* WMS, the results are undefined and the WMS shall produce an exception
* response.
* @return the layer names
*/
public String[] getQueryLayers() {
return queryLayers.toArray( new String[queryLayers.size()] );
}
/**
* adds the <QueryLayers>
* @param queryLayers
*/
public void addQueryLayers( String queryLayers ) {
this.queryLayers.add( queryLayers );
}
/**
* sets the <QueryLayers>
* @param queryLayers
*/
public void setQueryLayers( String[] queryLayers ) {
this.queryLayers.clear();
if ( queryLayers != null ) {
for ( int i = 0; i < queryLayers.length; i++ ) {
this.queryLayers.add( queryLayers[i] );
}
}
}
/**
* The optional INFO_FORMAT indicates what format to use when returning the
* feature information. Supported values for a GetFeatureInfo request on a
* WMS instance are listed as MIME types in one or more <Format>elements
* inside the <Request><FeatureInfo>element of its Capabilities XML. The
* entire MIME type string in <Format>is used as the value of the
* INFO_FORMAT parameter. In an HTTP environment, the MIME type shall be set
* on the returned object using the Content-type entity header.
* <p>
* </p>
* <b>EXAMPLE: </b> <tt> The parameter INFO_FORMAT=application/vnd.ogc.gml
* requests that the feature information be formatted in Geography Markup
* Language (GML).</tt>
* @return the format
*/
public String getInfoFormat() {
return infoFormat;
}
/**
* sets the <InfoFormat>
* @param infoFormat
*/
public void setInfoFormat( String infoFormat ) {
this.infoFormat = infoFormat;
}
/**
* The optional FEATURE_COUNT parameter states the maximum number of
* features for which feature information should be returned. Its value is a
* positive integer greater than zero. The default value is 1 if this
* parameter is omitted.
* @return the count
*/
public int getFeatureCount() {
return featureCount;
}
/**
* sets the <FeatureCount>
* @param featureCount
*/
public void setFeatureCount( int featureCount ) {
this.featureCount = featureCount;
}
/**
* The required X and Y parameters indicate a point of interest on the map.
* X and Y identify a single point within the borders of the WIDTH and
* HEIGHT parameters of the embedded GetMap request. The origin is set to
* (0,0) centered in the pixel at the upper left corner; X increases to the
* right and Y increases downward. X and Y are retruned as java.awt.Point
* class/datastructure.
* @return the point of interest
*/
public Point getClickPoint() {
return clickPoint;
}
/**
* sets the <ClickPoint>
* @param clickPoint
*/
public void setClickPoint( Point clickPoint ) {
this.clickPoint = clickPoint;
}
/**
* The optional EXCEPTIONS parameter states the manner in which errors are
* to be reported to the client. The default value is
* application/vnd.ogc.se_xml if this parameter is absent from the request.
* At present, not other values are defined for the WMS GetFeatureInfo
* request.
* @return the exception format
*/
public String getExceptions() {
return exceptions;
}
/**
* sets the <Exception>
* @param exceptions
*/
public void setExceptions( String exceptions ) {
this.exceptions = exceptions;
}
/**
* returns the SLD the request is made of. This implies that a 'simple' HTTP
* GET-Request will be transformed into a valid SLD. This is mandatory
* within a JaGo WMS.
* <p>
* </p>
* This mean even if a GetMap request is send using the HTTP GET method, an
* implementing class has to map the request to a SLD data sructure.
* @return the sld
*/
public StyledLayerDescriptor getStyledLayerDescriptor() {
return sld;
}
/**
* sets the SLD the request is made of. This implies that a 'simple' HTTP
* GET-Request or a part of it will be transformed into a valid SLD. For
* convenience it is asumed that the SLD names just a single layer to
* generate display elements of.
* @param sld
*/
public void setStyledLayerDescriptor( StyledLayerDescriptor sld ) {
this.sld = sld;
}
@Override
public String toString() {
try {
return getRequestParameter();
} catch ( OGCWebServiceException e ) {
e.printStackTrace();
}
return super.toString();
}
/**
* returns the parameter of a HTTP GET request.
*
*/
@Override
public String getRequestParameter()
throws OGCWebServiceException {
// indicates if the request parameters are decoded as SLD. deegree won't
// perform SLD requests through HTTP GET
if ( ( getMapRequestCopy.getBoundingBox() == null ) || ( queryLayers.size() == 0 ) ) {
throw new OGCWebServiceException( "Operations can't be expressed as HTTP GET request " );
}
StringBuffer sb = new StringBuffer( "service=WMS" );
if ( getVersion().compareTo( "1.0.0" ) <= 0 ) {
sb.append( "&VERSION=" + getVersion() + "&REQUEST=feature_info" );
sb.append( "&TRANSPARENT=" + getMapRequestCopy.getTransparency() );
} else {
sb.append( "&VERSION=" + getVersion() + "&REQUEST=GetFeatureInfo" );
sb.append( "&TRANSPARENCY=" + getMapRequestCopy.getTransparency() );
}
sb.append( "&WIDTH=" + getMapRequestCopy.getWidth() );
sb.append( "&HEIGHT=" + getMapRequestCopy.getHeight() );
sb.append( "&FORMAT=" + getMapRequestCopy.getFormat() );
sb.append( "&EXCEPTIONS=" + getExceptions() );
sb.append( "&BGCOLOR=" );
sb.append( ColorUtils.toHexCode( "0x", getMapRequestCopy.getBGColor() ) );
if ( "1.3.0".compareTo( getVersion() ) <= 0 ) {
sb.append( "&CRS=" + getMapRequestCopy.getSrs() );
sb.append( "&BBOX=" ).append( getMapRequestCopy.getBoundingBox().getMin().getY() );
sb.append( ',' ).append( getMapRequestCopy.getBoundingBox().getMin().getX() );
sb.append( ',' ).append( getMapRequestCopy.getBoundingBox().getMax().getY() );
sb.append( ',' ).append( getMapRequestCopy.getBoundingBox().getMax().getX() );
} else {
sb.append( "&SRS=" + getMapRequestCopy.getSrs() );
sb.append( "&BBOX=" ).append( getMapRequestCopy.getBoundingBox().getMin().getX() );
sb.append( ',' ).append( getMapRequestCopy.getBoundingBox().getMin().getY() );
sb.append( ',' ).append( getMapRequestCopy.getBoundingBox().getMax().getX() );
sb.append( ',' ).append( getMapRequestCopy.getBoundingBox().getMax().getY() );
}
GetMap.Layer[] layers = getMapRequestCopy.getLayers();
String l = "";
String s = "";
for ( int i = 0; i < layers.length; i++ ) {
l += ( layers[i].getName() + "," );
s += ( layers[i].getStyleName() + "," );
}
l = l.substring( 0, l.length() - 1 );
s = s.substring( 0, s.length() - 1 );
sb.append( "&LAYERS=" + l );
// replace $DEFAULT with "", which is what WMSses expect
StringTools.replace( s, "$DEFAULT", "", true );
sb.append( "&STYLES=" + s );
// TODO
// append time, elevation and sample dimension
String[] qlayers = getQueryLayers();
String ql = "";
for ( int i = 0; i < qlayers.length; i++ ) {
ql += ( qlayers[i] + "," );
}
ql = ql.substring( 0, ql.length() - 1 );
sb.append( "&QUERY_LAYERS=" + ql );
sb.append( "&FEATURE_COUNT=" + getFeatureCount() );
sb.append( "&INFO_FORMAT=" + getInfoFormat() );
if ( "1.3.0".compareTo( getVersion() ) <= 0 ) {
sb.append( "&I=" + clickPoint.x );
sb.append( "&J=" + clickPoint.y );
} else {
sb.append( "&X=" + clickPoint.x );
sb.append( "&Y=" + clickPoint.y );
}
return sb.toString();
}
/**
* @return whether the info format is the default setting
*/
public boolean isInfoFormatDefault() {
return infoFormatIsDefault;
}
}
/* ********************************************************************
Changes to this class. What the people have been up to:
$Log: GetFeatureInfo.java,v $
Revision 1.18 2006/11/22 15:38:31 schmitz
Fixed more exception handling, especially for the GetFeatureInfo request.
Revision 1.17 2006/10/17 20:31:18 poth
*** empty log message ***
Revision 1.16 2006/09/15 09:18:29 schmitz
Updated WMS to use SLD or SLD_BODY sld documents as default when also giving
LAYERS and STYLES parameters at the same time.
Revision 1.15 2006/09/08 08:42:02 schmitz
Updated the WMS to be 1.1.1 conformant once again.
Cleaned up the WMS code.
Added cite WMS test data.
Revision 1.14 2006/09/05 08:33:23 schmitz
GetFeatureInfo now uses one of the configured formats as default, not always GML.
Revision 1.13 2006/09/01 12:28:43 schmitz
Fixed two bugs:
$DEFAULT is no longer appended instead of empty string in remote WMS requests (STYLE parameter).
The FORMATS attribute now returns once more a String[] in the GetWMSLayerListener class.
Revision 1.12 2006/07/13 12:24:45 poth
adaptions required according to changes in org.deegree.ogcwebservice.wms.operations.GetMap
Revision 1.11 2006/07/12 14:46:16 poth
comment footer added
********************************************************************** */
| true | true | public static GetFeatureInfo create( Map<String, String> model )
throws OGCWebServiceException {
LOGGER.entering();
// VERSION
String version = model.get( "VERSION" );
if ( version == null ) {
version = model.get( "WMTVER" );
}
if ( version == null ) {
throw new InconsistentRequestException(
"VERSION-value must be set in the GetFeatureInfo request" );
}
// Some WMS Client, like ArcMAP, only send the QUERY_LAYERS parameter without a LAYERS parameter.
// However, some WMS server like MapServer fail in case there is no LAYERS parameter send.
// Thus, we add a LAYERS parameter in case only a QUERY_LAYERS parameter is available.
// -> Keep this in sync with the code in com.camptocamp.owsproxy.OWSProxyServlet::doGet
if (model.containsKey("QUERY_LAYERS") && !model.containsKey("LAYERS")) {
model.put("LAYERS", model.get("QUERY_LAYERS"));
}
boolean is130 = ( "1.3.0".compareTo( version ) <= 0 );
// ID
String id = model.get( "ID" );
if ( id == null ) {
throw new InconsistentRequestException(
"ID-value must be set in the GetFeatureInfo request" );
}
// QUERY_LAYERS
String layerlist = model.remove( "QUERY_LAYERS" );
String[] queryLayers = null;
if ( layerlist != null ) {
StringTokenizer st = new StringTokenizer( layerlist, "," );
queryLayers = new String[st.countTokens()];
int i = 0;
while ( st.hasMoreTokens() ) {
queryLayers[i++] = st.nextToken();
}
} else {
throw new InconsistentRequestException(
"QUERY_LAYERS-value must be set in the GetFeatureInfo request" );
}
// INFO_FORMAT (mime-type)
String infoFormat = model.remove( "INFO_FORMAT" );
boolean infoFormatDefault = false;
if ( infoFormat == null ) {
infoFormat = "application/vnd.ogc.gml";
infoFormatDefault = true;
}
// FEATURE_COUNT (default=1)
String feco = model.remove( "FEATURE_COUNT" );
int featureCount = 1;
if ( feco != null ) {
featureCount = Integer.parseInt( feco.trim() );
}
if ( featureCount < 0 ) {
featureCount = 1;
}
// X, Y (measured from upper left corner=0)
String X;
String Y;
if ( is130 ) {
X = "I";
Y = "J";
} else {
X = "X";
Y = "Y";
}
String xstring = model.remove( X );
String ystring = model.remove( Y );
java.awt.Point clickPoint = null;
if ( ( xstring != null ) & ( ystring != null ) ) {
try {
int x = Integer.parseInt( xstring.trim() );
int y = Integer.parseInt( ystring.trim() );
clickPoint = new java.awt.Point( x, y );
} catch ( NumberFormatException nfe ) {
LOGGER.logError( nfe.getLocalizedMessage(), nfe );
throw new OGCWebServiceException( "GetFeatureInfo", "Invalid point parameter",
ExceptionCode.INVALID_POINT );
}
} else {
throw new InconsistentRequestException(
X
+ "- and/or "
+ Y
+ "-value must be set in the GetFeatureInfo request" );
}
// EXCEPTIONS (default=application/vnd.ogc.se_xml)
String exceptions = model.get( "EXCEPTIONS" );
if ( exceptions == null ) {
if ( is130 ) {
exceptions = "XML";
} else {
exceptions = "application/vnd.ogc.se_xml";
}
}
// <map_request_copy>
GetMap getMapRequestCopy = null;
try {
getMapRequestCopy = GetMap.create( model );
} catch ( Exception ex ) {
throw new InconsistentRequestException(
"\nAn Exception "
+ "occured in creating the GetMap request-copy included in the "
+ "GetFeatureInfo-Operations:\n"
+ "--> Location: WMSProtocolFactory, createGetFeatureInfoRequest(int, HashMap)\n"
+ ex.getMessage() );
}
// check for consistency
if ( clickPoint.x > getMapRequestCopy.getWidth()
|| clickPoint.y > getMapRequestCopy.getHeight() ) {
throw new InvalidPointException( "The requested point is not valid." );
}
// VendorSpecificParameter; because all defined parameters has been
// removed
// from the model the vendorSpecificParameters are what left
Map<String, String> vendorSpecificParameter = model;
// StyledLayerDescriptor
StyledLayerDescriptor sld = getMapRequestCopy.getStyledLayerDescriptor();
LOGGER.exiting();
GetFeatureInfo res = create( version, id, queryLayers, getMapRequestCopy, infoFormat,
featureCount, clickPoint, exceptions, sld,
vendorSpecificParameter );
res.infoFormatIsDefault = infoFormatDefault;
return res;
}
| public static GetFeatureInfo create( Map<String, String> model )
throws OGCWebServiceException {
LOGGER.entering();
// VERSION
String version = model.get( "VERSION" );
if ( version == null ) {
version = model.get( "WMTVER" );
}
if ( version == null ) {
throw new InconsistentRequestException(
"VERSION-value must be set in the GetFeatureInfo request" );
}
// Some WMS Client, like ArcMAP, only send the QUERY_LAYERS parameter without a LAYERS parameter.
// However, some WMS server like MapServer fail in case there is no LAYERS parameter send.
// Thus, we add a LAYERS parameter in case only a QUERY_LAYERS parameter is available.
// -> Keep this in sync with the code in com.camptocamp.owsproxy.OWSProxyServlet::doGet
if (model.containsKey("QUERY_LAYERS") && !model.containsKey("LAYERS")) {
model.put("LAYERS", model.get("QUERY_LAYERS"));
}
boolean is130 = ( "1.3.0".compareTo( version ) <= 0 );
// ID
String id = model.get( "ID" );
if ( id == null ) {
throw new InconsistentRequestException(
"ID-value must be set in the GetFeatureInfo request" );
}
// QUERY_LAYERS
String layerlist = model.remove( "QUERY_LAYERS" );
String[] queryLayers = null;
if ( layerlist != null ) {
StringTokenizer st = new StringTokenizer( layerlist, "," );
queryLayers = new String[st.countTokens()];
int i = 0;
while ( st.hasMoreTokens() ) {
queryLayers[i++] = st.nextToken();
}
} else {
throw new InconsistentRequestException(
"QUERY_LAYERS-value must be set in the GetFeatureInfo request" );
}
// INFO_FORMAT (mime-type)
String infoFormat = model.remove( "INFO_FORMAT" );
boolean infoFormatDefault = false;
if ( infoFormat == null ) {
infoFormat = "application/vnd.ogc.gml";
infoFormatDefault = true;
}
// FEATURE_COUNT (default=1)
String feco = model.remove( "FEATURE_COUNT" );
int featureCount = 1;
if ( feco != null ) {
featureCount = Integer.parseInt( feco.trim() );
}
if ( featureCount < 0 ) {
featureCount = 1;
}
// X, Y (measured from upper left corner=0)
String X;
String Y;
if ( is130 ) {
X = "I";
Y = "J";
} else {
X = "X";
Y = "Y";
}
String xstring = model.remove( X );
String ystring = model.remove( Y );
java.awt.Point clickPoint = null;
if ( ( xstring != null ) & ( ystring != null ) ) {
try {
int x = Integer.parseInt( xstring.trim() );
int y = Integer.parseInt( ystring.trim() );
clickPoint = new java.awt.Point( x, y );
} catch ( NumberFormatException nfe ) {
LOGGER.logError( nfe.getLocalizedMessage(), nfe );
throw new OGCWebServiceException( "GetFeatureInfo", "Invalid point parameter",
ExceptionCode.INVALID_POINT );
}
} else {
throw new InconsistentRequestException(
X
+ "- and/or "
+ Y
+ "-value must be set in the GetFeatureInfo request" );
}
// EXCEPTIONS (default=application/vnd.ogc.se_xml)
String exceptions = model.get( "EXCEPTIONS" );
if ( exceptions == null ) {
if ( is130 ) {
exceptions = "XML";
} else {
exceptions = "application/vnd.ogc.se_xml";
}
}
// <map_request_copy>
GetMap getMapRequestCopy = null;
try {
if(!model.containsKey("FORMAT")){
model.put("FORMAT", "image/jpeg");
}
getMapRequestCopy = GetMap.create( model );
} catch ( Exception ex ) {
throw new InconsistentRequestException(
"\nAn Exception "
+ "occured in creating the GetMap request-copy included in the "
+ "GetFeatureInfo-Operations:\n"
+ "--> Location: WMSProtocolFactory, createGetFeatureInfoRequest(int, HashMap)\n"
+ ex.getMessage() );
}
// check for consistency
if ( clickPoint.x > getMapRequestCopy.getWidth()
|| clickPoint.y > getMapRequestCopy.getHeight() ) {
throw new InvalidPointException( "The requested point is not valid." );
}
// VendorSpecificParameter; because all defined parameters has been
// removed
// from the model the vendorSpecificParameters are what left
Map<String, String> vendorSpecificParameter = model;
// StyledLayerDescriptor
StyledLayerDescriptor sld = getMapRequestCopy.getStyledLayerDescriptor();
LOGGER.exiting();
GetFeatureInfo res = create( version, id, queryLayers, getMapRequestCopy, infoFormat,
featureCount, clickPoint, exceptions, sld,
vendorSpecificParameter );
res.infoFormatIsDefault = infoFormatDefault;
return res;
}
|
diff --git a/asi/src/asi/val/widget_receiver.java b/asi/src/asi/val/widget_receiver.java
index 54287e0..eb51cb7 100644
--- a/asi/src/asi/val/widget_receiver.java
+++ b/asi/src/asi/val/widget_receiver.java
@@ -1,321 +1,321 @@
package asi.val;
import java.util.Vector;
import android.app.PendingIntent;
import android.appwidget.AppWidgetManager;
import android.appwidget.AppWidgetProvider;
import android.content.ComponentName;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.util.Log;
import android.view.View;
import android.widget.RemoteViews;
import android.widget.Toast;
public class widget_receiver extends AppWidgetProvider {
public static final String PREFERENCE = "asi_pref";
public static final String SHOW_CURRENT = "asi.val.action.SHOW_CURRENT";
public static final String SHOW_NEXT = "asi.val.action.SHOW_NEXT";
public static final String CHECK_CURRENT = "asi.val.action.CHECK_CURRENT";
public static final String UPDATE_WIDGET = "asi.val.action.UPDATE_WIDGET";
private Vector<article> articles;
private String url = "http://www.arretsurimages.net/tous-les-contenus.rss";
public void onUpdate(Context context, AppWidgetManager appWidgetManager,
int[] appWidgetIds) {
final int N = appWidgetIds.length;
for (int i = 0; i < N; i++) {
Log.d("ASI", "Widget update:" + appWidgetIds[i]);
int appWidgetId = appWidgetIds[i];
// Lien vers la page courante d'asi
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
// On defini les action sur les elements du widget
this.defined_intent(context, views, appWidgetIds);
views.setTextViewText(R.id.widget_message, "Mise à jour en cours");
// views.setInt(R.id.widget_message, "setBackgroundResource",
// R.color.color_text);
views.setTextColor(R.id.widget_color, R.color.color_text);
views.setTextViewText(R.id.widget_next_texte, "0/0");
views.setViewVisibility(R.id.widget_check, View.INVISIBLE);
appWidgetManager.updateAppWidget(appWidgetId, views);
try {
rss_download d = new rss_download(url);
Log.d("ASI", "widget telechargement");
if (i == 0) {
d.get_rss_articles();
articles = d.getArticles();
// on rcherche si ils sont déjà lus
articles = this.get_new_articles(articles, context);
Log.d("ASI", "download_artciles:" + articles.size());
} else
articles = this.get_datas(context).get_widget_article();
if (articles.size() == 0)
throw new StopException("Pas de nouveau article");
views.setTextViewText(R.id.widget_message, articles
.elementAt(0).getTitle());
// views.setInt(R.id.widget_message, "setBackgroundResource",
// Color.parseColor(articles.elementAt(0).getColor()));
views.setTextColor(R.id.widget_color,
Color.parseColor(articles.elementAt(0).getColor()));
views.setTextViewText(R.id.widget_next_texte,
"1/" + articles.size());
// Tell the AppWidgetManager to perform an update on the current
// App Widget
appWidgetManager.updateAppWidget(appWidgetId, views);
Toast.makeText(context, "ASI widget à jour", Toast.LENGTH_SHORT)
.show();
} catch (StopException e) {
views.setTextViewText(R.id.widget_message,
"Aucun article non lu");
appWidgetManager.updateAppWidget(appWidgetId, views);
Log.e("ASI", "Error widget " + e.getMessage());
} catch (Exception e) {
views.setTextViewText(R.id.widget_message,
"Erreur de mise à jour");
appWidgetManager.updateAppWidget(appWidgetId, views);
Log.e("ASI", "Error widget " + e.getMessage());
} finally {
if (articles == null) {
articles = new Vector<article>();
}
this.get_datas(context).save_widget_article(articles);
this.get_datas(context).save_widget_posi(0);
}
}
}
private void defined_intent(Context context, RemoteViews views,
int[] appWidgetIds) {
// Create an Intent to launch asi main
Intent intent = new Intent(context, main.class);
intent.addCategory(Intent.CATEGORY_LAUNCHER);
intent.setAction(Intent.ACTION_MAIN);
intent.addFlags(Intent.FLAG_ACTIVITY_RESET_TASK_IF_NEEDED);
PendingIntent pendingIntent = PendingIntent.getActivity(context, 0,
intent, PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_asi, pendingIntent);
// lien vers la page des vidéos
intent = new Intent(context, download_view.class);
pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_art, pendingIntent);
// lien vers la page des téléchargement
intent = new Intent(context, SD_video_view.class);
pendingIntent = PendingIntent.getActivity(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_emi, pendingIntent);
// update du widget
intent = new Intent(context, widget_receiver.class);
// intent.setAction(AppWidgetManager.ACTION_APPWIDGET_UPDATE);
// intent.putExtra(AppWidgetManager.EXTRA_APPWIDGET_IDS, appWidgetIds);
intent.setAction(UPDATE_WIDGET);
intent.putExtra("IDS", appWidgetIds);
pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT // no flags
);
views.setOnClickPendingIntent(R.id.widget_chro, pendingIntent);
// Check de l'article en cours
intent = new Intent(context, widget_receiver.class);
intent.setAction(CHECK_CURRENT);
pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_vite, pendingIntent);
intent = new Intent(context, widget_receiver.class);
intent.setAction(SHOW_CURRENT);
pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_mes, pendingIntent);
intent = new Intent(context, widget_receiver.class);
intent.setAction(SHOW_NEXT);
pendingIntent = PendingIntent.getBroadcast(context, 0, intent,
PendingIntent.FLAG_UPDATE_CURRENT);
views.setOnClickPendingIntent(R.id.widget_next, pendingIntent);
}
private void defined_article(RemoteViews views,Context context,int posi){
if (articles.size() != 0) {
views.setTextViewText(R.id.widget_message,
articles.elementAt(posi).getTitle());
// views.setInt(R.id.widget_message, "setBackgroundResource",
// Color.parseColor(articles.elementAt(posi).getColor()));
views.setTextColor(R.id.widget_color,
Color.parseColor(articles.elementAt(posi).getColor()));
this.get_datas(context).save_widget_posi(posi);
views.setTextViewText(R.id.widget_next_texte, (posi + 1) + "/"
+ articles.size());
if (this.get_datas(context).contain_articles_lues(
articles.elementAt(posi).getUri()))
views.setViewVisibility(R.id.widget_check, View.VISIBLE);
else
views.setViewVisibility(R.id.widget_check, View.INVISIBLE);
}else{
views.setTextViewText(R.id.widget_message,"Aucun article non lu");
views.setTextColor(R.id.widget_color, R.color.color_text);
views.setTextViewText(R.id.widget_next_texte, "0/0");
views.setViewVisibility(R.id.widget_check, View.INVISIBLE);
}
}
public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
Log.d("ASI", "Action=" + action);
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else if (SHOW_CURRENT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
intent = new Intent(context, page.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (posi < articles.size()) {
intent.putExtra("url", articles.elementAt(posi).getUri());
intent.putExtra("titre", articles.elementAt(posi).getTitle());
context.startActivity(intent);
}
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
// On met l'artcile courant lu et on rend visible l'image check
- //views.setViewVisibility(R.id.widget_check, View.VISIBLE);
this.defined_article(views, context, posi);
+ views.setViewVisibility(R.id.widget_check, View.VISIBLE);
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
manager.updateAppWidget(thisWidget, views);
} else if (SHOW_NEXT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
if ((posi + 1) == articles.size())
posi = 0;
else
posi++;
Log.d("ASI", "position widget;" + posi);
Log.d("ASI", "save_articles:" + articles.size());
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
this.defined_article(views, context, posi);
// views.setViewVisibility(R.id.widget_check, View.INVISIBLE);
// if (articles.size() != 0) {
// views.setTextViewText(R.id.widget_message,
// articles.elementAt(posi).getTitle());
// // views.setInt(R.id.widget_message, "setBackgroundResource",
// // Color.parseColor(articles.elementAt(posi).getColor()));
// views.setTextColor(R.id.widget_color,
// Color.parseColor(articles.elementAt(posi).getColor()));
// this.get_datas(context).save_widget_posi(posi);
// views.setTextViewText(R.id.widget_next_texte, (posi + 1) + "/"
// + articles.size());
// if (this.get_datas(context).contain_articles_lues(
// articles.elementAt(posi).getUri()))
// views.setViewVisibility(R.id.widget_check, View.VISIBLE);
// }
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
// int[] temp = manager.getAppWidgetIds(thisWidget);
// for(int z=0;z<temp.length;z++)
// Log.d("ASI","intent update of:"+temp[z]);
manager.updateAppWidget(thisWidget, views);
// appWidgetManager.updateAppWidget(appWidgetId, views);
} else if (CHECK_CURRENT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
if (posi < articles.size())
this.get_datas(context).add_articles_lues(
articles.elementAt(posi).getUri());
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
// On met l'artcile courant lu et on rend visible l'image check
//views.setViewVisibility(R.id.widget_check, View.VISIBLE);
this.defined_article(views, context, posi);
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
manager.updateAppWidget(thisWidget, views);
} else if (UPDATE_WIDGET.equals(action)) {
int[] ids = intent.getIntArrayExtra("IDS");
this.onUpdate(context, AppWidgetManager.getInstance(context), ids);
} else {
super.onReceive(context, intent);
}
}
public void onDisabled(Context context) {
super.onDisabled(context);
Log.d("ASI", "disabled widget");
}
public void onEnabled(Context context) {
super.onEnabled(context);
Log.d("ASI", "enabled widget");
}
public void onDeleted(Context context, int[] appWidgetIds) {
super.onDeleted(context, appWidgetIds);
Log.d("ASI", "deleted widget");
}
private Vector<article> get_new_articles(Vector<article> articles2,
Context c) {
// TODO Auto-generated method stub
Vector<article> ar = new Vector<article>();
for (int i = 0; i < articles2.size(); i++) {
if (!this.get_datas(c).contain_articles_lues(
articles2.elementAt(i).getUri()))
ar.add(articles2.elementAt(i));
}
return (ar);
}
public shared_datas get_datas(Context c) {
shared_datas datas = shared_datas.shared;
if (datas == null)
return (new shared_datas(c));
datas.setContext(c);
return datas;
}
}
| false | true | public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
Log.d("ASI", "Action=" + action);
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else if (SHOW_CURRENT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
intent = new Intent(context, page.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (posi < articles.size()) {
intent.putExtra("url", articles.elementAt(posi).getUri());
intent.putExtra("titre", articles.elementAt(posi).getTitle());
context.startActivity(intent);
}
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
// On met l'artcile courant lu et on rend visible l'image check
//views.setViewVisibility(R.id.widget_check, View.VISIBLE);
this.defined_article(views, context, posi);
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
manager.updateAppWidget(thisWidget, views);
} else if (SHOW_NEXT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
if ((posi + 1) == articles.size())
posi = 0;
else
posi++;
Log.d("ASI", "position widget;" + posi);
Log.d("ASI", "save_articles:" + articles.size());
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
this.defined_article(views, context, posi);
// views.setViewVisibility(R.id.widget_check, View.INVISIBLE);
// if (articles.size() != 0) {
// views.setTextViewText(R.id.widget_message,
// articles.elementAt(posi).getTitle());
// // views.setInt(R.id.widget_message, "setBackgroundResource",
// // Color.parseColor(articles.elementAt(posi).getColor()));
// views.setTextColor(R.id.widget_color,
// Color.parseColor(articles.elementAt(posi).getColor()));
// this.get_datas(context).save_widget_posi(posi);
// views.setTextViewText(R.id.widget_next_texte, (posi + 1) + "/"
// + articles.size());
// if (this.get_datas(context).contain_articles_lues(
// articles.elementAt(posi).getUri()))
// views.setViewVisibility(R.id.widget_check, View.VISIBLE);
// }
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
// int[] temp = manager.getAppWidgetIds(thisWidget);
// for(int z=0;z<temp.length;z++)
// Log.d("ASI","intent update of:"+temp[z]);
manager.updateAppWidget(thisWidget, views);
// appWidgetManager.updateAppWidget(appWidgetId, views);
} else if (CHECK_CURRENT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
if (posi < articles.size())
this.get_datas(context).add_articles_lues(
articles.elementAt(posi).getUri());
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
// On met l'artcile courant lu et on rend visible l'image check
//views.setViewVisibility(R.id.widget_check, View.VISIBLE);
this.defined_article(views, context, posi);
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
manager.updateAppWidget(thisWidget, views);
} else if (UPDATE_WIDGET.equals(action)) {
int[] ids = intent.getIntArrayExtra("IDS");
this.onUpdate(context, AppWidgetManager.getInstance(context), ids);
} else {
super.onReceive(context, intent);
}
}
| public void onReceive(Context context, Intent intent) {
// v1.5 fix that doesn't call onDelete Action
final String action = intent.getAction();
Log.d("ASI", "Action=" + action);
if (AppWidgetManager.ACTION_APPWIDGET_DELETED.equals(action)) {
final int appWidgetId = intent.getExtras().getInt(
AppWidgetManager.EXTRA_APPWIDGET_ID,
AppWidgetManager.INVALID_APPWIDGET_ID);
if (appWidgetId != AppWidgetManager.INVALID_APPWIDGET_ID) {
this.onDeleted(context, new int[] { appWidgetId });
}
} else if (SHOW_CURRENT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
intent = new Intent(context, page.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
if (posi < articles.size()) {
intent.putExtra("url", articles.elementAt(posi).getUri());
intent.putExtra("titre", articles.elementAt(posi).getTitle());
context.startActivity(intent);
}
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
// On met l'artcile courant lu et on rend visible l'image check
this.defined_article(views, context, posi);
views.setViewVisibility(R.id.widget_check, View.VISIBLE);
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
manager.updateAppWidget(thisWidget, views);
} else if (SHOW_NEXT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
if ((posi + 1) == articles.size())
posi = 0;
else
posi++;
Log.d("ASI", "position widget;" + posi);
Log.d("ASI", "save_articles:" + articles.size());
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
this.defined_article(views, context, posi);
// views.setViewVisibility(R.id.widget_check, View.INVISIBLE);
// if (articles.size() != 0) {
// views.setTextViewText(R.id.widget_message,
// articles.elementAt(posi).getTitle());
// // views.setInt(R.id.widget_message, "setBackgroundResource",
// // Color.parseColor(articles.elementAt(posi).getColor()));
// views.setTextColor(R.id.widget_color,
// Color.parseColor(articles.elementAt(posi).getColor()));
// this.get_datas(context).save_widget_posi(posi);
// views.setTextViewText(R.id.widget_next_texte, (posi + 1) + "/"
// + articles.size());
// if (this.get_datas(context).contain_articles_lues(
// articles.elementAt(posi).getUri()))
// views.setViewVisibility(R.id.widget_check, View.VISIBLE);
// }
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
// int[] temp = manager.getAppWidgetIds(thisWidget);
// for(int z=0;z<temp.length;z++)
// Log.d("ASI","intent update of:"+temp[z]);
manager.updateAppWidget(thisWidget, views);
// appWidgetManager.updateAppWidget(appWidgetId, views);
} else if (CHECK_CURRENT.equals(action)) {
articles = this.get_datas(context)
.get_widget_article();
int posi = this.get_datas(context).get_widget_posi();
if (posi < articles.size())
this.get_datas(context).add_articles_lues(
articles.elementAt(posi).getUri());
RemoteViews views = new RemoteViews(context.getPackageName(),
R.layout.widget_asi);
// On met l'artcile courant lu et on rend visible l'image check
//views.setViewVisibility(R.id.widget_check, View.VISIBLE);
this.defined_article(views, context, posi);
ComponentName thisWidget = new ComponentName(context,
widget_receiver.class);
AppWidgetManager manager = AppWidgetManager.getInstance(context);
// On redefini les action sur les elements du widget
this.defined_intent(context, views,
manager.getAppWidgetIds(thisWidget));
manager.updateAppWidget(thisWidget, views);
} else if (UPDATE_WIDGET.equals(action)) {
int[] ids = intent.getIntArrayExtra("IDS");
this.onUpdate(context, AppWidgetManager.getInstance(context), ids);
} else {
super.onReceive(context, intent);
}
}
|
diff --git a/depot/source/main/apper/src/com/pjab/apper/AppFetcher.java b/depot/source/main/apper/src/com/pjab/apper/AppFetcher.java
index e7e8d3a..795d7cf 100644
--- a/depot/source/main/apper/src/com/pjab/apper/AppFetcher.java
+++ b/depot/source/main/apper/src/com/pjab/apper/AppFetcher.java
@@ -1,90 +1,90 @@
package com.pjab.apper;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentLinkedQueue;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.IOException;
import java.sql.Connection;
import java.util.Properties;
import com.pjab.apper.AppData;
import com.pjab.apper.AppConfig;
import com.pjab.apper.AppParser;
import com.pjab.apper.Crawler;
import com.pjab.apper.DataMapping;
import com.pjab.apper.DatabaseConfig;
import com.pjab.apper.DatabaseUtils;
import com.pjab.apper.URLInfo;
import com.pjab.apper.Utils;
public class AppFetcher {
private final Properties props;
private DataMapping dm;
public AppFetcher ()
{
AppConfig aconfig = AppConfig.getInstance();
props = aconfig.getProperties();
dm = aconfig.getMapping("itunes_web_html_mapping");
}
public boolean fetchApp(String appUrl)
{
ConcurrentLinkedQueue<URLInfo>processQueue = new ConcurrentLinkedQueue<URLInfo>();
ConcurrentHashMap<String, Boolean> seenURLs = new ConcurrentHashMap<String, Boolean>();
Connection conn = DatabaseConfig.getInstance().getConnection();
URLInfo newURLInfo = new URLInfo(appUrl,"",0);
String outputAppDir = props.getProperty(ApperConstants.OUTPUT_APP_DIR);
String appDataDir = props.getProperty(ApperConstants.OUTPUT_DATA_DIR);
Crawler crawler = new Crawler(processQueue,seenURLs,0,outputAppDir);
String fileName = crawler.crawl(newURLInfo);
System.out.println(fileName);
if(fileName.length() == 0)
return false;
AppParser parser = new AppParser(outputAppDir + "/" + fileName);
try {
AppData appData = parser.parseWithDataMappings(dm);
- String appDataFile = appDataDir + fileName;
+ String appDataFile = appDataDir + "/" + fileName;
System.out.println(appDataFile);
Utils.printToFile(appDataFile, appData.toJSON());
System.out.println("Writing to database");
DatabaseUtils.insertAppInfoIfNotExists(conn, appData);
return true;
}catch (Exception e)
{
System.out.println("Exception thrown for file" + e.getMessage());
e.printStackTrace();
//break;
}
return false;
}
public static void main(String [] args) throws Exception
{
AppConfig aconfig = AppConfig.getInstance();
aconfig.init(args);
Properties prop = Utils.loadProperties("default.properties");
AppFetcher fetcher = new AppFetcher();
String seedURL = "http://www.appvamp.com/ihandy-flashlight-free/";
fetcher.fetchApp(seedURL);
}
}
| true | true | public boolean fetchApp(String appUrl)
{
ConcurrentLinkedQueue<URLInfo>processQueue = new ConcurrentLinkedQueue<URLInfo>();
ConcurrentHashMap<String, Boolean> seenURLs = new ConcurrentHashMap<String, Boolean>();
Connection conn = DatabaseConfig.getInstance().getConnection();
URLInfo newURLInfo = new URLInfo(appUrl,"",0);
String outputAppDir = props.getProperty(ApperConstants.OUTPUT_APP_DIR);
String appDataDir = props.getProperty(ApperConstants.OUTPUT_DATA_DIR);
Crawler crawler = new Crawler(processQueue,seenURLs,0,outputAppDir);
String fileName = crawler.crawl(newURLInfo);
System.out.println(fileName);
if(fileName.length() == 0)
return false;
AppParser parser = new AppParser(outputAppDir + "/" + fileName);
try {
AppData appData = parser.parseWithDataMappings(dm);
String appDataFile = appDataDir + fileName;
System.out.println(appDataFile);
Utils.printToFile(appDataFile, appData.toJSON());
System.out.println("Writing to database");
DatabaseUtils.insertAppInfoIfNotExists(conn, appData);
return true;
}catch (Exception e)
{
System.out.println("Exception thrown for file" + e.getMessage());
e.printStackTrace();
//break;
}
return false;
}
| public boolean fetchApp(String appUrl)
{
ConcurrentLinkedQueue<URLInfo>processQueue = new ConcurrentLinkedQueue<URLInfo>();
ConcurrentHashMap<String, Boolean> seenURLs = new ConcurrentHashMap<String, Boolean>();
Connection conn = DatabaseConfig.getInstance().getConnection();
URLInfo newURLInfo = new URLInfo(appUrl,"",0);
String outputAppDir = props.getProperty(ApperConstants.OUTPUT_APP_DIR);
String appDataDir = props.getProperty(ApperConstants.OUTPUT_DATA_DIR);
Crawler crawler = new Crawler(processQueue,seenURLs,0,outputAppDir);
String fileName = crawler.crawl(newURLInfo);
System.out.println(fileName);
if(fileName.length() == 0)
return false;
AppParser parser = new AppParser(outputAppDir + "/" + fileName);
try {
AppData appData = parser.parseWithDataMappings(dm);
String appDataFile = appDataDir + "/" + fileName;
System.out.println(appDataFile);
Utils.printToFile(appDataFile, appData.toJSON());
System.out.println("Writing to database");
DatabaseUtils.insertAppInfoIfNotExists(conn, appData);
return true;
}catch (Exception e)
{
System.out.println("Exception thrown for file" + e.getMessage());
e.printStackTrace();
//break;
}
return false;
}
|
diff --git a/src/main/java/net/krinsoft/privileges/commands/GroupSetCommand.java b/src/main/java/net/krinsoft/privileges/commands/GroupSetCommand.java
index f6502fe..fab5da7 100644
--- a/src/main/java/net/krinsoft/privileges/commands/GroupSetCommand.java
+++ b/src/main/java/net/krinsoft/privileges/commands/GroupSetCommand.java
@@ -1,51 +1,56 @@
package net.krinsoft.privileges.commands;
import net.krinsoft.privileges.Privileges;
import org.bukkit.ChatColor;
import org.bukkit.OfflinePlayer;
import org.bukkit.command.CommandSender;
import org.bukkit.permissions.PermissionDefault;
import java.util.List;
/**
*
* @author krinsdeath
*/
public class GroupSetCommand extends GroupCommand {
public GroupSetCommand(Privileges plugin) {
super(plugin);
setName("Privileges: Group Set");
setCommandUsage("/pgs [player] [group]");
setArgRange(2, 2);
addKey("privileges group set");
addKey("priv group set");
addKey("pgroup set");
addKey("pgroups");
addKey("pg set");
addKey("pgs");
setPermission("privileges.group.set", "Allows this user to change other users' groups.", PermissionDefault.OP);
}
@Override
public void runCommand(CommandSender sender, List<String> args) {
OfflinePlayer target = plugin.getServer().getOfflinePlayer(args.get(0));
if (target == null) {
sender.sendMessage("No player with the name '" + args.get(0) + "' could be found.");
return;
}
if (!plugin.getGroupManager().checkRank(sender, target)) {
sender.sendMessage(ChatColor.RED + "That user's rank is too high.");
return;
}
- if (!plugin.getGroupManager().checkRank(sender, plugin.getGroupManager().getGroup(args.get(1)).getRank())) {
- sender.sendMessage(ChatColor.RED + "That group's rank is too high.");
+ try {
+ if (!plugin.getGroupManager().checkRank(sender, plugin.getGroupManager().getGroup(args.get(1)).getRank())) {
+ sender.sendMessage(ChatColor.RED + "That group's rank is too high.");
+ return;
+ }
+ } catch (NullPointerException e) {
+ sender.sendMessage(ChatColor.RED + "No such group exists.");
return;
}
plugin.getGroupManager().setGroup(target.getName(), args.get(1));
sender.sendMessage(colorize(ChatColor.GREEN, target.getName()) + "'s group has been set to " + colorize(ChatColor.GREEN, args.get(1)));
plugin.log(">> " + sender.getName() + ": Set " + target.getName() + "'s group to '" + args.get(1) + "'");
}
}
| true | true | public void runCommand(CommandSender sender, List<String> args) {
OfflinePlayer target = plugin.getServer().getOfflinePlayer(args.get(0));
if (target == null) {
sender.sendMessage("No player with the name '" + args.get(0) + "' could be found.");
return;
}
if (!plugin.getGroupManager().checkRank(sender, target)) {
sender.sendMessage(ChatColor.RED + "That user's rank is too high.");
return;
}
if (!plugin.getGroupManager().checkRank(sender, plugin.getGroupManager().getGroup(args.get(1)).getRank())) {
sender.sendMessage(ChatColor.RED + "That group's rank is too high.");
return;
}
plugin.getGroupManager().setGroup(target.getName(), args.get(1));
sender.sendMessage(colorize(ChatColor.GREEN, target.getName()) + "'s group has been set to " + colorize(ChatColor.GREEN, args.get(1)));
plugin.log(">> " + sender.getName() + ": Set " + target.getName() + "'s group to '" + args.get(1) + "'");
}
| public void runCommand(CommandSender sender, List<String> args) {
OfflinePlayer target = plugin.getServer().getOfflinePlayer(args.get(0));
if (target == null) {
sender.sendMessage("No player with the name '" + args.get(0) + "' could be found.");
return;
}
if (!plugin.getGroupManager().checkRank(sender, target)) {
sender.sendMessage(ChatColor.RED + "That user's rank is too high.");
return;
}
try {
if (!plugin.getGroupManager().checkRank(sender, plugin.getGroupManager().getGroup(args.get(1)).getRank())) {
sender.sendMessage(ChatColor.RED + "That group's rank is too high.");
return;
}
} catch (NullPointerException e) {
sender.sendMessage(ChatColor.RED + "No such group exists.");
return;
}
plugin.getGroupManager().setGroup(target.getName(), args.get(1));
sender.sendMessage(colorize(ChatColor.GREEN, target.getName()) + "'s group has been set to " + colorize(ChatColor.GREEN, args.get(1)));
plugin.log(">> " + sender.getName() + ": Set " + target.getName() + "'s group to '" + args.get(1) + "'");
}
|
diff --git a/offbudget/src/main/java/edu/unlv/kilo/domain/ItemEntity.java b/offbudget/src/main/java/edu/unlv/kilo/domain/ItemEntity.java
index d7f84f2..1cf3386 100644
--- a/offbudget/src/main/java/edu/unlv/kilo/domain/ItemEntity.java
+++ b/offbudget/src/main/java/edu/unlv/kilo/domain/ItemEntity.java
@@ -1,81 +1,81 @@
package edu.unlv.kilo.domain;
import java.util.Date;
import java.util.HashSet;
import java.util.Set;
import javax.persistence.CascadeType;
import javax.persistence.ManyToMany;
import org.joda.time.DateTime;
import org.joda.time.Days;
import org.springframework.roo.addon.javabean.RooJavaBean;
import org.springframework.roo.addon.jpa.activerecord.RooJpaActiveRecord;
import org.springframework.roo.addon.tostring.RooToString;
@RooJavaBean
@RooToString
@RooJpaActiveRecord
public class ItemEntity {
@ManyToMany(cascade = CascadeType.ALL)
private Set<TransactionEntity> transactions = new HashSet<TransactionEntity>();
@ManyToMany(cascade = CascadeType.ALL)
private Set<ItemAdjustment> adjustments = new HashSet<ItemAdjustment>();
private String description;
private boolean inflation;
private boolean recurrenceIsAutomatic;
private int recurrenceManualInterval;
public ItemEntity(String description, boolean inflation, boolean recurrenceIsAutomatic, int recurrenceManualInterval) {
this.description = description;
this.inflation = inflation;
this.recurrenceIsAutomatic = recurrenceIsAutomatic;
this.recurrenceManualInterval = recurrenceManualInterval;
}
/**
* Calculate the average interval to find the base interval between transactions for this item
* @return Average number of days between transactions. 0 if an interval cannot be calculated.
*/
public int getBaseRecurrenceInterval() {
if (!recurrenceIsAutomatic) {
return recurrenceManualInterval;
}
// Find the average interval from recurring transactions
if (transactions.size() <= 1) {
return 0;
}
boolean first = true;
Date firstDate = null;
Date lastDate = null;
int numberRecurringTransactions = 0;
for (TransactionEntity transaction : transactions) {
// Disregard non-recurring transactions
if (!transaction.isRecurring()) {
continue;
}
++numberRecurringTransactions;
if (first && transaction.isRecurring()) {
firstDate = transaction.getTimeof();
lastDate = transaction.getTimeof();
first = false;
continue;
}
lastDate = transaction.getTimeof();
}
Days days = Days.daysBetween(new DateTime(firstDate), new DateTime(lastDate));
- return days.getDays();
+ return days.getDays() / numberRecurringTransactions;
}
}
| true | true | public int getBaseRecurrenceInterval() {
if (!recurrenceIsAutomatic) {
return recurrenceManualInterval;
}
// Find the average interval from recurring transactions
if (transactions.size() <= 1) {
return 0;
}
boolean first = true;
Date firstDate = null;
Date lastDate = null;
int numberRecurringTransactions = 0;
for (TransactionEntity transaction : transactions) {
// Disregard non-recurring transactions
if (!transaction.isRecurring()) {
continue;
}
++numberRecurringTransactions;
if (first && transaction.isRecurring()) {
firstDate = transaction.getTimeof();
lastDate = transaction.getTimeof();
first = false;
continue;
}
lastDate = transaction.getTimeof();
}
Days days = Days.daysBetween(new DateTime(firstDate), new DateTime(lastDate));
return days.getDays();
}
| public int getBaseRecurrenceInterval() {
if (!recurrenceIsAutomatic) {
return recurrenceManualInterval;
}
// Find the average interval from recurring transactions
if (transactions.size() <= 1) {
return 0;
}
boolean first = true;
Date firstDate = null;
Date lastDate = null;
int numberRecurringTransactions = 0;
for (TransactionEntity transaction : transactions) {
// Disregard non-recurring transactions
if (!transaction.isRecurring()) {
continue;
}
++numberRecurringTransactions;
if (first && transaction.isRecurring()) {
firstDate = transaction.getTimeof();
lastDate = transaction.getTimeof();
first = false;
continue;
}
lastDate = transaction.getTimeof();
}
Days days = Days.daysBetween(new DateTime(firstDate), new DateTime(lastDate));
return days.getDays() / numberRecurringTransactions;
}
|
diff --git a/servers/media/core/controllers/mgcp/src/main/java/org/mobicents/media/server/ctrl/mgcp/DeleteConnectionAction.java b/servers/media/core/controllers/mgcp/src/main/java/org/mobicents/media/server/ctrl/mgcp/DeleteConnectionAction.java
index 1272029d0..876274e66 100644
--- a/servers/media/core/controllers/mgcp/src/main/java/org/mobicents/media/server/ctrl/mgcp/DeleteConnectionAction.java
+++ b/servers/media/core/controllers/mgcp/src/main/java/org/mobicents/media/server/ctrl/mgcp/DeleteConnectionAction.java
@@ -1,138 +1,139 @@
/*
* Mobicents, Communications Middleware
*
* Copyright (c) 2008, Red Hat Middleware LLC or third-party
* contributors as
* indicated by the @author tags or express copyright attribution
* statements applied by the authors. All third-party contributions are
* distributed under license by Red Hat Middleware LLC.
*
* This copyrighted material is made available to anyone wishing to use, modify,
* copy, or redistribute it subject to the terms and conditions of the GNU
* Lesser General Public License, as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
* or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License
* for more details.
*
*
* You should have received a copy of the GNU Lesser General Public License
* along with this distribution; if not, write to:
* Free Software Foundation, Inc.
* 51 Franklin Street, Fifth Floor
*
* Boston, MA 02110-1301 USA
*/
package org.mobicents.media.server.ctrl.mgcp;
import jain.protocol.ip.mgcp.JainMgcpResponseEvent;
import jain.protocol.ip.mgcp.message.DeleteConnection;
import jain.protocol.ip.mgcp.message.DeleteConnectionResponse;
import jain.protocol.ip.mgcp.message.parms.CallIdentifier;
import jain.protocol.ip.mgcp.message.parms.ConnectionIdentifier;
import jain.protocol.ip.mgcp.message.parms.EndpointIdentifier;
import jain.protocol.ip.mgcp.message.parms.ReturnCode;
import java.util.Collection;
import java.util.concurrent.Callable;
import org.apache.log4j.Logger;
import org.mobicents.media.server.spi.Connection;
import org.mobicents.media.server.spi.Endpoint;
/**
*
* @author kulikov
*/
public class DeleteConnectionAction implements Callable {
private static Logger logger = Logger.getLogger(DeleteConnectionAction.class);
private DeleteConnection req;
private MgcpController controller;
private MgcpUtils utils = new MgcpUtils();
protected DeleteConnectionAction(MgcpController controller, DeleteConnection req) {
this.controller = controller;
this.req = req;
}
private JainMgcpResponseEvent endpointDeleteConnections(String localName) {
Endpoint endpoint = null;
try {
endpoint = controller.getNamingService().lookup(localName, true);
} catch (Exception e) {
return new DeleteConnectionResponse(controller, ReturnCode.Endpoint_Unknown);
}
endpoint.deleteAllConnections();
Collection<ConnectionActivity> activities = controller.getActivities(localName);
for (ConnectionActivity activity : activities) {
activity.close();
}
return new DeleteConnectionResponse(controller, ReturnCode.Transaction_Executed_Normally);
}
private JainMgcpResponseEvent callDeleteConnections(String callID) {
Call call = controller.getCall(callID);
if (call == null) {
return new DeleteConnectionResponse(controller, ReturnCode.Unknown_Call_ID);
}
Collection<ConnectionActivity> activities = call.getActivities();
for (ConnectionActivity activity : activities) {
Connection connection = activity.getMediaConnection();
connection.getEndpoint().deleteConnection(connection.getId());
activity.close();
}
return new DeleteConnectionResponse(controller, ReturnCode.Transaction_Executed_Normally);
}
private JainMgcpResponseEvent deleteConnection(String localName, String connectionID) {
Endpoint endpoint = null;
try {
endpoint = controller.getNamingService().lookup(localName, true);
} catch (Exception e) {
return new DeleteConnectionResponse(controller, ReturnCode.Endpoint_Unknown);
}
ConnectionActivity activity = controller.getActivity(localName, connectionID);
endpoint.deleteConnection(activity.connection.getId());
activity.close();
return new DeleteConnectionResponse(controller, ReturnCode.Transaction_Executed_Normally);
}
public JainMgcpResponseEvent call() throws Exception {
int txID = req.getTransactionHandle();
CallIdentifier callID = req.getCallIdentifier();
EndpointIdentifier endpointID = req.getEndpointIdentifier();
ConnectionIdentifier connectionID = req.getConnectionIdentifier();
logger.info("Request TX= " + txID +
", CallID = " + callID +
", Endpoint = " + endpointID +
", Connection = " + connectionID);
JainMgcpResponseEvent response = null;
if (endpointID != null && callID == null && connectionID == null) {
response = this.endpointDeleteConnections(endpointID.getLocalEndpointName());
} else if (endpointID != null && callID != null && connectionID == null) {
//TODO : Delete all connection of Endpoint that belong to given callId
response = this.endpointDeleteConnections(endpointID.getLocalEndpointName());
} else if (endpointID != null && callID != null && connectionID != null) {
response = this.deleteConnection(endpointID.getLocalEndpointName(), connectionID.toString());
} else {
- response = this.callDeleteConnections(callID.toString());
- }
+ //This is error condition
+ response = new DeleteConnectionResponse(controller, ReturnCode.Protocol_Error);
+ }
//Otherwise it wont be sent.
response.setTransactionHandle(txID);
logger.info("Response TX=" + txID + ", response=" + response.getReturnCode());
return response;
}
}
| true | true | public JainMgcpResponseEvent call() throws Exception {
int txID = req.getTransactionHandle();
CallIdentifier callID = req.getCallIdentifier();
EndpointIdentifier endpointID = req.getEndpointIdentifier();
ConnectionIdentifier connectionID = req.getConnectionIdentifier();
logger.info("Request TX= " + txID +
", CallID = " + callID +
", Endpoint = " + endpointID +
", Connection = " + connectionID);
JainMgcpResponseEvent response = null;
if (endpointID != null && callID == null && connectionID == null) {
response = this.endpointDeleteConnections(endpointID.getLocalEndpointName());
} else if (endpointID != null && callID != null && connectionID == null) {
//TODO : Delete all connection of Endpoint that belong to given callId
response = this.endpointDeleteConnections(endpointID.getLocalEndpointName());
} else if (endpointID != null && callID != null && connectionID != null) {
response = this.deleteConnection(endpointID.getLocalEndpointName(), connectionID.toString());
} else {
response = this.callDeleteConnections(callID.toString());
}
//Otherwise it wont be sent.
response.setTransactionHandle(txID);
logger.info("Response TX=" + txID + ", response=" + response.getReturnCode());
return response;
}
| public JainMgcpResponseEvent call() throws Exception {
int txID = req.getTransactionHandle();
CallIdentifier callID = req.getCallIdentifier();
EndpointIdentifier endpointID = req.getEndpointIdentifier();
ConnectionIdentifier connectionID = req.getConnectionIdentifier();
logger.info("Request TX= " + txID +
", CallID = " + callID +
", Endpoint = " + endpointID +
", Connection = " + connectionID);
JainMgcpResponseEvent response = null;
if (endpointID != null && callID == null && connectionID == null) {
response = this.endpointDeleteConnections(endpointID.getLocalEndpointName());
} else if (endpointID != null && callID != null && connectionID == null) {
//TODO : Delete all connection of Endpoint that belong to given callId
response = this.endpointDeleteConnections(endpointID.getLocalEndpointName());
} else if (endpointID != null && callID != null && connectionID != null) {
response = this.deleteConnection(endpointID.getLocalEndpointName(), connectionID.toString());
} else {
//This is error condition
response = new DeleteConnectionResponse(controller, ReturnCode.Protocol_Error);
}
//Otherwise it wont be sent.
response.setTransactionHandle(txID);
logger.info("Response TX=" + txID + ", response=" + response.getReturnCode());
return response;
}
|
diff --git a/libraries/javalib/javax/swing/JFormattedTextField.java b/libraries/javalib/javax/swing/JFormattedTextField.java
index eaf53555b..fdc9ffee3 100644
--- a/libraries/javalib/javax/swing/JFormattedTextField.java
+++ b/libraries/javalib/javax/swing/JFormattedTextField.java
@@ -1,248 +1,247 @@
/* JFormattedTextField.java --
Copyright (C) 2003, 2004 Free Software Foundation, Inc.
This file is part of GNU Classpath.
GNU Classpath 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, or (at your option)
any later version.
GNU Classpath 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 GNU Classpath; see the file COPYING. If not, write to the
Free Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
02111-1307 USA.
Linking this library statically or dynamically with other modules is
making a combined work based on this library. Thus, the terms and
conditions of the GNU General Public License cover the whole
combination.
As a special exception, the copyright holders of this library give you
permission to link this library with independent modules to produce an
executable, regardless of the license terms of these independent
modules, and to copy and distribute the resulting executable under
terms of your choice, provided that you also meet, for each linked
independent module, the terms and conditions of the license of that
module. An independent module is a module which is not derived from
or based on this library. If you modify this library, you may extend
this exception to your version of the library, but you are not
obligated to do so. If you do not wish to do so, delete this
exception statement from your version. */
package javax.swing;
import java.awt.event.FocusEvent;
import java.io.Serializable;
import java.text.Format;
import java.text.ParseException;
import javax.swing.text.Document;
import javax.swing.text.DocumentFilter;
import javax.swing.text.NavigationFilter;
/**
* @author Michael Koch
* @since 1.4
*/
public class JFormattedTextField extends JTextField
{
private static final long serialVersionUID = 5464657870110180632L;
public abstract static class AbstractFormatter implements Serializable
{
private static final long serialVersionUID = -5193212041738979680L;
public AbstractFormatter ()
{
//Do nothing here.
}
protected Object clone ()
throws CloneNotSupportedException
{
throw new InternalError ("not implemented");
}
protected Action[] getActions ()
{
throw new InternalError ("not implemented");
}
protected DocumentFilter getDocumentFilter ()
{
throw new InternalError ("not implemented");
}
protected JFormattedTextField getFormattedTextField ()
{
throw new InternalError ("not implemented");
}
protected NavigationFilter getNavigationFilter ()
{
throw new InternalError ("not implemented");
}
public void install (JFormattedTextField ftf)
{
throw new InternalError ("not implemented");
}
public void uninstall ()
{
throw new InternalError ("not implemented");
}
protected void invalidEdit ()
{
throw new InternalError ("not implemented");
}
protected void setEditValid (boolean valid)
{
throw new InternalError ("not implemented");
}
public abstract Object stringToValue (String text)
throws ParseException;
public abstract String valueToString (Object value)
throws ParseException;
}
public abstract static class AbstractFormatterFactory
{
public AbstractFormatterFactory ()
{
// Do nothing here.
}
public abstract AbstractFormatter getFormatter (JFormattedTextField tf);
}
public static final int COMMIT = 0;
public static final int COMMIT_OR_REVERT = 1;
public static final int REVERT = 2;
public static final int PERSIST = 3;
private Object value;
public JFormattedTextField ()
{
this((AbstractFormatterFactory) null);
}
public JFormattedTextField (Format format)
{
throw new InternalError ("not implemented");
}
public JFormattedTextField (AbstractFormatter formatter)
{
throw new InternalError ("not implemented");
}
public JFormattedTextField (AbstractFormatterFactory factory)
{
this(factory, null);
}
public JFormattedTextField (AbstractFormatterFactory factory, Object value)
{
throw new InternalError ("not implemented");
}
public JFormattedTextField (Object value)
{
this.value = value;
}
public void commitEdit ()
throws ParseException
{
throw new InternalError ("not implemented");
}
public Action[] getActions ()
{
throw new InternalError ("not implemented");
}
public int getFocusLostBehaviour ()
{
throw new InternalError ("not implemented");
}
public AbstractFormatter getFormatter ()
{
throw new InternalError ("not implemented");
}
public AbstractFormatterFactory getFormatterFactory ()
{
throw new InternalError ("not implemented");
}
public String getUIClassID ()
{
return "FormattedTextFieldUI";
}
public Object getValue ()
{
return value;
}
protected void invalidEdit ()
{
throw new InternalError ("not implemented");
}
public boolean isEditValid ()
{
throw new InternalError ("not implemented");
}
protected void processFocusEvent (FocusEvent evt)
{
throw new InternalError ("not implemented");
}
public void setDocument(Document newdoc)
{
- Document document = getDocument();
+ Document olddoc = getDocument();
- if (document == newdoc)
+ if (olddoc == newdoc)
return;
- setDocument(newdoc);
- firePropertyChange("document", document, newdoc);
+ super.setDocument(newdoc);
}
public void setLostFocusBehavior (int behavior)
{
throw new InternalError ("not implemented");
}
protected void setFormatter (AbstractFormatter formatter)
{
throw new InternalError ("not implemented");
}
public void setFormatterFactory (AbstractFormatterFactory factory)
{
throw new InternalError ("not implemented");
}
public void setValue (Object newValue)
{
value = newValue;
}
}
| false | true | public void setDocument(Document newdoc)
{
Document document = getDocument();
if (document == newdoc)
return;
setDocument(newdoc);
firePropertyChange("document", document, newdoc);
}
| public void setDocument(Document newdoc)
{
Document olddoc = getDocument();
if (olddoc == newdoc)
return;
super.setDocument(newdoc);
}
|
diff --git a/drools-planner-core/src/main/java/org/drools/planner/config/heuristic/selector/move/MoveSelectorConfig.java b/drools-planner-core/src/main/java/org/drools/planner/config/heuristic/selector/move/MoveSelectorConfig.java
index 75a14451..8d1306ae 100644
--- a/drools-planner-core/src/main/java/org/drools/planner/config/heuristic/selector/move/MoveSelectorConfig.java
+++ b/drools-planner-core/src/main/java/org/drools/planner/config/heuristic/selector/move/MoveSelectorConfig.java
@@ -1,193 +1,198 @@
/*
* Copyright 2012 JBoss Inc
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package org.drools.planner.config.heuristic.selector.move;
import java.util.ArrayList;
import java.util.List;
import com.thoughtworks.xstream.annotations.XStreamImplicit;
import com.thoughtworks.xstream.annotations.XStreamInclude;
import org.apache.commons.collections.CollectionUtils;
import org.drools.planner.config.EnvironmentMode;
import org.drools.planner.config.heuristic.selector.SelectorConfig;
import org.drools.planner.config.heuristic.selector.common.SelectionOrder;
import org.drools.planner.config.heuristic.selector.move.composite.UnionMoveSelectorConfig;
import org.drools.planner.config.heuristic.selector.move.factory.MoveIteratorFactoryConfig;
import org.drools.planner.config.heuristic.selector.move.factory.MoveListFactoryConfig;
import org.drools.planner.config.heuristic.selector.move.generic.ChangeMoveSelectorConfig;
import org.drools.planner.config.heuristic.selector.move.generic.PillarSwapMoveSelectorConfig;
import org.drools.planner.config.heuristic.selector.move.generic.SwapMoveSelectorConfig;
import org.drools.planner.config.heuristic.selector.move.generic.chained.SubChainChangeMoveSelectorConfig;
import org.drools.planner.config.heuristic.selector.move.generic.chained.SubChainSwapMoveSelectorConfig;
import org.drools.planner.config.util.ConfigUtils;
import org.drools.planner.core.domain.solution.SolutionDescriptor;
import org.drools.planner.core.heuristic.selector.common.SelectionCacheType;
import org.drools.planner.core.heuristic.selector.common.decorator.SelectionFilter;
import org.drools.planner.core.heuristic.selector.common.decorator.SelectionProbabilityWeightFactory;
import org.drools.planner.core.heuristic.selector.move.MoveSelector;
import org.drools.planner.core.heuristic.selector.move.decorator.CachingMoveSelector;
import org.drools.planner.core.heuristic.selector.move.decorator.FilteringMoveSelector;
import org.drools.planner.core.heuristic.selector.move.decorator.ProbabilityMoveSelector;
import org.drools.planner.core.heuristic.selector.move.decorator.ShufflingMoveSelector;
/**
* General superclass for {@link ChangeMoveSelectorConfig}, etc.
*/
@XStreamInclude({
UnionMoveSelectorConfig.class,
ChangeMoveSelectorConfig.class, SwapMoveSelectorConfig.class, PillarSwapMoveSelectorConfig.class,
SubChainChangeMoveSelectorConfig.class, SubChainSwapMoveSelectorConfig.class,
MoveListFactoryConfig.class, MoveIteratorFactoryConfig.class
})
public abstract class MoveSelectorConfig extends SelectorConfig {
protected SelectionCacheType cacheType = null;
protected SelectionOrder selectionOrder = null;
@XStreamImplicit(itemFieldName = "moveFilterClass")
protected List<Class<? extends SelectionFilter>> moveFilterClassList = null;
protected Class<? extends SelectionProbabilityWeightFactory> moveProbabilityWeightFactoryClass = null;
// TODO moveSorterClass
private Double fixedProbabilityWeight = null;
public SelectionCacheType getCacheType() {
return cacheType;
}
public void setCacheType(SelectionCacheType cacheType) {
this.cacheType = cacheType;
}
public SelectionOrder getSelectionOrder() {
return selectionOrder;
}
public void setSelectionOrder(SelectionOrder selectionOrder) {
this.selectionOrder = selectionOrder;
}
public List<Class<? extends SelectionFilter>> getMoveFilterClassList() {
return moveFilterClassList;
}
public void setMoveFilterClassList(List<Class<? extends SelectionFilter>> moveFilterClassList) {
this.moveFilterClassList = moveFilterClassList;
}
public Class<? extends SelectionProbabilityWeightFactory> getMoveProbabilityWeightFactoryClass() {
return moveProbabilityWeightFactoryClass;
}
public void setMoveProbabilityWeightFactoryClass(Class<? extends SelectionProbabilityWeightFactory> moveProbabilityWeightFactoryClass) {
this.moveProbabilityWeightFactoryClass = moveProbabilityWeightFactoryClass;
}
public Double getFixedProbabilityWeight() {
return fixedProbabilityWeight;
}
public void setFixedProbabilityWeight(Double fixedProbabilityWeight) {
this.fixedProbabilityWeight = fixedProbabilityWeight;
}
// ************************************************************************
// Builder methods
// ************************************************************************
/**
*
* @param environmentMode never null
* @param solutionDescriptor never null
* @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}),
* then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching
* and less would be pointless.
* @param inheritedSelectionOrder never null
* @return never null
*/
public MoveSelector buildMoveSelector(EnvironmentMode environmentMode, SolutionDescriptor solutionDescriptor,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) {
SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(cacheType, minimumCacheType);
minimumCacheType = SelectionCacheType.max(minimumCacheType, resolvedCacheType);
SelectionOrder resolvedSelectionOrder = SelectionOrder.resolve(selectionOrder, inheritedSelectionOrder);
// baseMoveSelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely
MoveSelector moveSelector = buildBaseMoveSelector(environmentMode, solutionDescriptor,
minimumCacheType, resolvedCacheType.isCached() ? SelectionOrder.ORIGINAL : resolvedSelectionOrder);
boolean alreadyCached = false;
if (!CollectionUtils.isEmpty(moveFilterClassList)) {
List<SelectionFilter> moveFilterList = new ArrayList<SelectionFilter>(moveFilterClassList.size());
for (Class<? extends SelectionFilter> moveFilterClass : moveFilterClassList) {
moveFilterList.add(ConfigUtils.newInstance(this, "moveFilterClass", moveFilterClass));
}
moveSelector = new FilteringMoveSelector(moveSelector, moveFilterList);
alreadyCached = false;
}
// TODO moveSorterClass
if (moveProbabilityWeightFactoryClass != null) {
if (resolvedSelectionOrder != SelectionOrder.RANDOM) {
throw new IllegalArgumentException("The entitySelectorConfig (" + this
+ ") with moveProbabilityWeightFactoryClass ("
+ moveProbabilityWeightFactoryClass + ") has a resolvedSelectionOrder ("
+ resolvedSelectionOrder + ") that is not " + SelectionOrder.RANDOM + ".");
}
SelectionProbabilityWeightFactory entityProbabilityWeightFactory = ConfigUtils.newInstance(this,
"moveProbabilityWeightFactoryClass", moveProbabilityWeightFactoryClass);
moveSelector = new ProbabilityMoveSelector(moveSelector,
resolvedCacheType, entityProbabilityWeightFactory);
alreadyCached = true;
}
if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) {
+ if (resolvedCacheType.isNotCached()) {
+ throw new IllegalArgumentException("The entitySelectorConfig (" + this
+ + ") with resolvedSelectionOrder (" + resolvedSelectionOrder
+ + ") has a resolvedCacheType (" + resolvedCacheType + ") that is not cached.");
+ }
moveSelector = new ShufflingMoveSelector(moveSelector, resolvedCacheType);
alreadyCached = true;
}
if (resolvedCacheType.isCached() && !alreadyCached) {
// TODO this might be pretty pointless for MoveListFactoryConfig, because MoveListFactory caches
moveSelector = new CachingMoveSelector(moveSelector, resolvedCacheType,
resolvedSelectionOrder == SelectionOrder.RANDOM);
}
return moveSelector;
}
/**
*
* @param environmentMode never null
* @param solutionDescriptor never null
* @param minimumCacheType never null, If caching is used (different from {@link SelectionCacheType#JUST_IN_TIME}),
* then it should be at least this {@link SelectionCacheType} because an ancestor already uses such caching
* and less would be pointless.
* @param resolvedSelectionOrder never null
* @return never null
*/
protected abstract MoveSelector buildBaseMoveSelector(
EnvironmentMode environmentMode, SolutionDescriptor solutionDescriptor,
SelectionCacheType minimumCacheType, SelectionOrder resolvedSelectionOrder);
protected void inherit(MoveSelectorConfig inheritedConfig) {
super.inherit(inheritedConfig);
cacheType = ConfigUtils.inheritOverwritableProperty(cacheType, inheritedConfig.getCacheType());
selectionOrder = ConfigUtils.inheritOverwritableProperty(selectionOrder, inheritedConfig.getSelectionOrder());
moveFilterClassList = ConfigUtils.inheritOverwritableProperty(
moveFilterClassList, inheritedConfig.getMoveFilterClassList());
moveProbabilityWeightFactoryClass = ConfigUtils.inheritOverwritableProperty(
moveProbabilityWeightFactoryClass, inheritedConfig.getMoveProbabilityWeightFactoryClass());
fixedProbabilityWeight = ConfigUtils.inheritOverwritableProperty(
fixedProbabilityWeight, inheritedConfig.getFixedProbabilityWeight());
}
}
| true | true | public MoveSelector buildMoveSelector(EnvironmentMode environmentMode, SolutionDescriptor solutionDescriptor,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) {
SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(cacheType, minimumCacheType);
minimumCacheType = SelectionCacheType.max(minimumCacheType, resolvedCacheType);
SelectionOrder resolvedSelectionOrder = SelectionOrder.resolve(selectionOrder, inheritedSelectionOrder);
// baseMoveSelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely
MoveSelector moveSelector = buildBaseMoveSelector(environmentMode, solutionDescriptor,
minimumCacheType, resolvedCacheType.isCached() ? SelectionOrder.ORIGINAL : resolvedSelectionOrder);
boolean alreadyCached = false;
if (!CollectionUtils.isEmpty(moveFilterClassList)) {
List<SelectionFilter> moveFilterList = new ArrayList<SelectionFilter>(moveFilterClassList.size());
for (Class<? extends SelectionFilter> moveFilterClass : moveFilterClassList) {
moveFilterList.add(ConfigUtils.newInstance(this, "moveFilterClass", moveFilterClass));
}
moveSelector = new FilteringMoveSelector(moveSelector, moveFilterList);
alreadyCached = false;
}
// TODO moveSorterClass
if (moveProbabilityWeightFactoryClass != null) {
if (resolvedSelectionOrder != SelectionOrder.RANDOM) {
throw new IllegalArgumentException("The entitySelectorConfig (" + this
+ ") with moveProbabilityWeightFactoryClass ("
+ moveProbabilityWeightFactoryClass + ") has a resolvedSelectionOrder ("
+ resolvedSelectionOrder + ") that is not " + SelectionOrder.RANDOM + ".");
}
SelectionProbabilityWeightFactory entityProbabilityWeightFactory = ConfigUtils.newInstance(this,
"moveProbabilityWeightFactoryClass", moveProbabilityWeightFactoryClass);
moveSelector = new ProbabilityMoveSelector(moveSelector,
resolvedCacheType, entityProbabilityWeightFactory);
alreadyCached = true;
}
if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) {
moveSelector = new ShufflingMoveSelector(moveSelector, resolvedCacheType);
alreadyCached = true;
}
if (resolvedCacheType.isCached() && !alreadyCached) {
// TODO this might be pretty pointless for MoveListFactoryConfig, because MoveListFactory caches
moveSelector = new CachingMoveSelector(moveSelector, resolvedCacheType,
resolvedSelectionOrder == SelectionOrder.RANDOM);
}
return moveSelector;
}
| public MoveSelector buildMoveSelector(EnvironmentMode environmentMode, SolutionDescriptor solutionDescriptor,
SelectionCacheType minimumCacheType, SelectionOrder inheritedSelectionOrder) {
SelectionCacheType resolvedCacheType = SelectionCacheType.resolve(cacheType, minimumCacheType);
minimumCacheType = SelectionCacheType.max(minimumCacheType, resolvedCacheType);
SelectionOrder resolvedSelectionOrder = SelectionOrder.resolve(selectionOrder, inheritedSelectionOrder);
// baseMoveSelector and lower should be SelectionOrder.ORIGINAL if they are going to get cached completely
MoveSelector moveSelector = buildBaseMoveSelector(environmentMode, solutionDescriptor,
minimumCacheType, resolvedCacheType.isCached() ? SelectionOrder.ORIGINAL : resolvedSelectionOrder);
boolean alreadyCached = false;
if (!CollectionUtils.isEmpty(moveFilterClassList)) {
List<SelectionFilter> moveFilterList = new ArrayList<SelectionFilter>(moveFilterClassList.size());
for (Class<? extends SelectionFilter> moveFilterClass : moveFilterClassList) {
moveFilterList.add(ConfigUtils.newInstance(this, "moveFilterClass", moveFilterClass));
}
moveSelector = new FilteringMoveSelector(moveSelector, moveFilterList);
alreadyCached = false;
}
// TODO moveSorterClass
if (moveProbabilityWeightFactoryClass != null) {
if (resolvedSelectionOrder != SelectionOrder.RANDOM) {
throw new IllegalArgumentException("The entitySelectorConfig (" + this
+ ") with moveProbabilityWeightFactoryClass ("
+ moveProbabilityWeightFactoryClass + ") has a resolvedSelectionOrder ("
+ resolvedSelectionOrder + ") that is not " + SelectionOrder.RANDOM + ".");
}
SelectionProbabilityWeightFactory entityProbabilityWeightFactory = ConfigUtils.newInstance(this,
"moveProbabilityWeightFactoryClass", moveProbabilityWeightFactoryClass);
moveSelector = new ProbabilityMoveSelector(moveSelector,
resolvedCacheType, entityProbabilityWeightFactory);
alreadyCached = true;
}
if (resolvedSelectionOrder == SelectionOrder.SHUFFLED) {
if (resolvedCacheType.isNotCached()) {
throw new IllegalArgumentException("The entitySelectorConfig (" + this
+ ") with resolvedSelectionOrder (" + resolvedSelectionOrder
+ ") has a resolvedCacheType (" + resolvedCacheType + ") that is not cached.");
}
moveSelector = new ShufflingMoveSelector(moveSelector, resolvedCacheType);
alreadyCached = true;
}
if (resolvedCacheType.isCached() && !alreadyCached) {
// TODO this might be pretty pointless for MoveListFactoryConfig, because MoveListFactory caches
moveSelector = new CachingMoveSelector(moveSelector, resolvedCacheType,
resolvedSelectionOrder == SelectionOrder.RANDOM);
}
return moveSelector;
}
|
diff --git a/src/net/sf/freecol/client/gui/panel/ReportLabourPanel.java b/src/net/sf/freecol/client/gui/panel/ReportLabourPanel.java
index a5ab8f8e2..a6818df90 100644
--- a/src/net/sf/freecol/client/gui/panel/ReportLabourPanel.java
+++ b/src/net/sf/freecol/client/gui/panel/ReportLabourPanel.java
@@ -1,359 +1,360 @@
package net.sf.freecol.client.gui.panel;
import java.awt.Color;
import java.awt.GridLayout;
import java.awt.event.ActionListener;
import java.util.ArrayList;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import javax.swing.JLabel;
import javax.swing.JPanel;
import net.sf.freecol.client.gui.Canvas;
import net.sf.freecol.client.gui.ImageLibrary;
import net.sf.freecol.client.gui.i18n.Messages;
import net.sf.freecol.common.model.Colony;
import net.sf.freecol.common.model.Europe;
import net.sf.freecol.common.model.Location;
import net.sf.freecol.common.model.Player;
import net.sf.freecol.common.model.Tile;
import net.sf.freecol.common.model.Unit;
import net.sf.freecol.common.model.WorkLocation;
import cz.autel.dmi.*;
/**
* This panel displays the Labour Report.
*/
public final class ReportLabourPanel extends ReportPanel implements ActionListener {
public static final String COPYRIGHT = "Copyright (C) 2003-2005 The FreeCol Team";
public static final String LICENSE = "http://www.gnu.org/licenses/gpl.html";
public static final String REVISION = "$Revision$";
// This is copied from net.sf.freecol.client.gui.ImageLibrary where it is private
private static final int FREE_COLONIST = 0,
EXPERT_FARMER = 1,
EXPERT_FISHERMAN = 2,
EXPERT_FUR_TRAPPER = 3,
EXPERT_SILVER_MINER = 4,
EXPERT_LUMBER_JACK = 5,
EXPERT_ORE_MINER = 6,
MASTER_SUGAR_PLANTER = 7,
MASTER_COTTON_PLANTER = 8,
MASTER_TOBACCO_PLANTER = 9,
FIREBRAND_PREACHER = 10,
ELDER_STATESMAN = 11,
MASTER_CARPENTER = 12,
MASTER_DISTILLER = 13,
MASTER_WEAVER = 14,
MASTER_TOBACCONIST = 15,
MASTER_FUR_TRADER = 16,
MASTER_BLACKSMITH = 17,
MASTER_GUNSMITH = 18,
SEASONED_SCOUT_NOT_MOUNTED = 19,
HARDY_PIONEER_NO_TOOLS = 20,
UNARMED_VETERAN_SOLDIER = 21,
JESUIT_MISSIONARY = 22,
MISSIONARY_FREE_COLONIST = 23,
SEASONED_SCOUT_MOUNTED = 24,
HARDY_PIONEER_WITH_TOOLS = 25,
FREE_COLONIST_WITH_TOOLS = 26,
INDENTURED_SERVANT = 27,
PETTY_CRIMINAL = 28,
INDIAN_CONVERT = 29,
BRAVE = 30,
UNARMED_COLONIAL_REGULAR = 31,
UNARMED_KINGS_REGULAR = 32,
SOLDIER = 33,
VETERAN_SOLDIER = 34,
COLONIAL_REGULAR = 35,
KINGS_REGULAR = 36,
UNARMED_DRAGOON = 37,
UNARMED_VETERAN_DRAGOON = 38,
UNARMED_COLONIAL_CAVALRY = 39,
UNARMED_KINGS_CAVALRY = 40,
DRAGOON = 41,
VETERAN_DRAGOON = 42,
COLONIAL_CAVALRY = 43,
KINGS_CAVALRY = 44,
ARMED_BRAVE = 45,
MOUNTED_BRAVE = 46,
INDIAN_DRAGOON = 47,
CARAVEL = 48,
FRIGATE = 49,
GALLEON = 50,
MAN_O_WAR = 51,
MERCHANTMAN = 52,
PRIVATEER = 53,
ARTILLERY = 54,
DAMAGED_ARTILLERY = 55,
TREASURE_TRAIN = 56,
WAGON_TRAIN = 57,
MILKMAID = 58,
JESUIT_MISSIONARY_NO_CROSS = 59,
UNIT_GRAPHICS_COUNT = 60;
private int[] unitCount;
private HashMap<String, Integer>[] unitLocations;
private ArrayList locationNames = new ArrayList();
/**
* The constructor that will add the items to this panel.
* @param parent The parent of this panel.
*/
public ReportLabourPanel(Canvas parent) {
super(parent, Messages.message("report.labour"));
}
/**
* Prepares this panel to be displayed.
*/
public void initialize() {
// Count Units
unitCount = new int[Unit.UNIT_COUNT];
unitLocations = new HashMap[Unit.UNIT_COUNT];
for (int index = 0; index < Unit.UNIT_COUNT; index++) {
unitLocations[index] = new HashMap();
}
Player player = parent.getClient().getMyPlayer();
Iterator units = player.getUnitIterator();
List colonies = player.getSettlements();
Collections.sort(colonies, parent.getClient().getClientOptions().getColonyComparator());
Iterator colonyIterator = colonies.iterator();
locationNames = new ArrayList();
locationNames.add(Messages.message("report.atSea"));
locationNames.add(Messages.message("report.onLand"));
- locationNames.add(player.getEurope().toString());
+ if (player.getEurope() != null)
+ locationNames.add(player.getEurope().toString());
while (colonyIterator.hasNext()) {
locationNames.add(((Colony) colonyIterator.next()).getName());
}
while (units.hasNext()) {
Unit unit = (Unit) units.next();
int type = unit.getType();
Location location = unit.getLocation();
String locationName = null;
if (location instanceof WorkLocation) {
locationName = ((WorkLocation) location).getColony().getName();
} else if (location instanceof Europe) {
locationName = player.getEurope().toString();
} else if (location instanceof Tile &&
((Tile) location).getSettlement() != null) {
locationName = ((Colony) ((Tile) location).getSettlement()).getName();
} else if (location instanceof Unit) {
locationName = Messages.message("report.atSea");
} else {
locationName = Messages.message("report.onLand");
}
if (locationName != null) {
if (unitLocations[type].containsKey(locationName)) {
int oldValue = ((Integer) unitLocations[type].get(locationName)).intValue();
unitLocations[type].put(locationName, new Integer(oldValue + 1));
} else {
unitLocations[type].put(locationName, new Integer(1));
}
}
unitCount[unit.getType()]++;
}
// Display Panel
reportPanel.removeAll();
int margin = 30;
int[] widths = new int[] {0, 5, 0, margin, 0, 5, 0, margin, 0, 5, 0};
int[] heights = new int[] {0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0};
reportPanel.setLayout(new HIGLayout(widths, heights));
HIGConstraints higConst = new HIGConstraints();
int row = 1;
reportPanel.add(buildUnitLabel(FREE_COLONIST, 1f), //ImageLibrary.FREE_COLONIST);
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.FREE_COLONIST),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(INDENTURED_SERVANT, 1f), //ImageLibrary.INDENTURED_SERVANT),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.INDENTURED_SERVANT),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(PETTY_CRIMINAL, 1f), //ImageLibrary.PETTY_CRIMINAL),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.PETTY_CRIMINAL),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(INDIAN_CONVERT, 1f), //ImageLibrary.INDIAN_CONVERT),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.INDIAN_CONVERT),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_FARMER, 1f), //ImageLibrary.EXPERT_FARMER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_FARMER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(EXPERT_FISHERMAN, 1f), //ImageLibrary.EXPERT_FISHERMAN),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.EXPERT_FISHERMAN),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_SUGAR_PLANTER, 1f), //ImageLibrary.MASTER_SUGAR_PLANTER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_SUGAR_PLANTER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_DISTILLER, 1f), //ImageLibrary.MASTER_DISTILLER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_DISTILLER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(EXPERT_LUMBER_JACK, 1f), //ImageLibrary.EXPERT_LUMBER_JACK),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.EXPERT_LUMBER_JACK),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_CARPENTER, 1f), //ImageLibrary.MASTER_CARPENTER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_CARPENTER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_TOBACCO_PLANTER, 1f), //ImageLibrary.MASTER_TOBACCO_PLANTER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_TOBACCO_PLANTER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_TOBACCONIST, 1f), //ImageLibrary.MASTER_TOBACCONIST),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_TOBACCONIST),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(EXPERT_FUR_TRAPPER, 1f), //ImageLibrary.EXPERT_FUR_TRAPPER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.EXPERT_FUR_TRAPPER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_FUR_TRADER, 1f), //ImageLibrary.MASTER_FUR_TRADER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_FUR_TRADER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_COTTON_PLANTER, 1f), //ImageLibrary.MASTER_COTTON_PLANTER),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_COTTON_PLANTER),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_WEAVER, 1f), //ImageLibrary.MASTER_WEAVER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_WEAVER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_ORE_MINER, 1f), //ImageLibrary.EXPERT_ORE_MINER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_ORE_MINER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_BLACKSMITH, 1f), //ImageLibrary.MASTER_BLACKSMITH),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_BLACKSMITH),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_GUNSMITH, 1f), //ImageLibrary.MASTER_GUNSMITH),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_GUNSMITH),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_SILVER_MINER, 1f), //ImageLibrary.EXPERT_SILVER_MINER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_SILVER_MINER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(HARDY_PIONEER_WITH_TOOLS, 1f), //ImageLibrary.HARDY_PIONEER_WITH_TOOLS),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.HARDY_PIONEER),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(VETERAN_SOLDIER, 1f), //ImageLibrary.VETERAN_SOLDIER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.VETERAN_SOLDIER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(SEASONED_SCOUT_NOT_MOUNTED, 1f), //ImageLibrary.SEASONED_SCOUT_NOT_MOUNTED),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.SEASONED_SCOUT),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(JESUIT_MISSIONARY, 1f), //ImageLibrary.JESUIT_MISSIONARY),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.JESUIT_MISSIONARY),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(ELDER_STATESMAN, 1f), //ImageLibrary.ELDER_STATESMAN),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.ELDER_STATESMAN),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(FIREBRAND_PREACHER, 1f), //ImageLibrary.FIREBRAND_PREACHER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.FIREBRAND_PREACHER),
higConst.rc(row, 7));
reportPanel.doLayout();
}
private JPanel buildUnitReport(int unit) {
JPanel textPanel = new JPanel();
textPanel.setOpaque(false);
HIGConstraints higConst = new HIGConstraints();
int[] widths = {0, 5, 0};
int[] heights = null;
int colonyColumn = 1;
int countColumn = 3;
int keys = 0;
if (unitLocations[unit] != null) {
keys = unitLocations[unit].size();
}
if (keys == 0) {
heights = new int[] {0};
} else {
heights = new int[keys + 2];
for (int index = 0; index < heights.length; index++) {
heights[index] = 0;
}
heights[1] = 5;
}
textPanel.setLayout(new HIGLayout(widths, heights));
// summary
int row = 1;
JLabel unitLabel = new JLabel(Unit.getName(unit));
textPanel.add(unitLabel, higConst.rc(row, colonyColumn));
if (unitCount[unit] == 0) {
unitLabel.setForeground(Color.GRAY);
} else {
textPanel.add(new JLabel(String.valueOf(unitCount[unit])),
higConst.rc(row, countColumn));
row = 3;
Iterator locationIterator = locationNames.iterator();
while (locationIterator.hasNext()) {
String name = (String) locationIterator.next();
if (unitLocations[unit].get(name) != null) {
JLabel colonyLabel = new JLabel(name);
colonyLabel.setForeground(Color.GRAY);
textPanel.add(colonyLabel, higConst.rc(row, colonyColumn));
JLabel countLabel = new JLabel(unitLocations[unit].get(name).toString());
countLabel.setForeground(Color.GRAY);
textPanel.add(countLabel, higConst.rc(row, countColumn));
row++;
}
}
}
return textPanel;
}
}
| true | true | public void initialize() {
// Count Units
unitCount = new int[Unit.UNIT_COUNT];
unitLocations = new HashMap[Unit.UNIT_COUNT];
for (int index = 0; index < Unit.UNIT_COUNT; index++) {
unitLocations[index] = new HashMap();
}
Player player = parent.getClient().getMyPlayer();
Iterator units = player.getUnitIterator();
List colonies = player.getSettlements();
Collections.sort(colonies, parent.getClient().getClientOptions().getColonyComparator());
Iterator colonyIterator = colonies.iterator();
locationNames = new ArrayList();
locationNames.add(Messages.message("report.atSea"));
locationNames.add(Messages.message("report.onLand"));
locationNames.add(player.getEurope().toString());
while (colonyIterator.hasNext()) {
locationNames.add(((Colony) colonyIterator.next()).getName());
}
while (units.hasNext()) {
Unit unit = (Unit) units.next();
int type = unit.getType();
Location location = unit.getLocation();
String locationName = null;
if (location instanceof WorkLocation) {
locationName = ((WorkLocation) location).getColony().getName();
} else if (location instanceof Europe) {
locationName = player.getEurope().toString();
} else if (location instanceof Tile &&
((Tile) location).getSettlement() != null) {
locationName = ((Colony) ((Tile) location).getSettlement()).getName();
} else if (location instanceof Unit) {
locationName = Messages.message("report.atSea");
} else {
locationName = Messages.message("report.onLand");
}
if (locationName != null) {
if (unitLocations[type].containsKey(locationName)) {
int oldValue = ((Integer) unitLocations[type].get(locationName)).intValue();
unitLocations[type].put(locationName, new Integer(oldValue + 1));
} else {
unitLocations[type].put(locationName, new Integer(1));
}
}
unitCount[unit.getType()]++;
}
// Display Panel
reportPanel.removeAll();
int margin = 30;
int[] widths = new int[] {0, 5, 0, margin, 0, 5, 0, margin, 0, 5, 0};
int[] heights = new int[] {0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0};
reportPanel.setLayout(new HIGLayout(widths, heights));
HIGConstraints higConst = new HIGConstraints();
int row = 1;
reportPanel.add(buildUnitLabel(FREE_COLONIST, 1f), //ImageLibrary.FREE_COLONIST);
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.FREE_COLONIST),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(INDENTURED_SERVANT, 1f), //ImageLibrary.INDENTURED_SERVANT),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.INDENTURED_SERVANT),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(PETTY_CRIMINAL, 1f), //ImageLibrary.PETTY_CRIMINAL),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.PETTY_CRIMINAL),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(INDIAN_CONVERT, 1f), //ImageLibrary.INDIAN_CONVERT),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.INDIAN_CONVERT),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_FARMER, 1f), //ImageLibrary.EXPERT_FARMER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_FARMER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(EXPERT_FISHERMAN, 1f), //ImageLibrary.EXPERT_FISHERMAN),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.EXPERT_FISHERMAN),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_SUGAR_PLANTER, 1f), //ImageLibrary.MASTER_SUGAR_PLANTER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_SUGAR_PLANTER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_DISTILLER, 1f), //ImageLibrary.MASTER_DISTILLER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_DISTILLER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(EXPERT_LUMBER_JACK, 1f), //ImageLibrary.EXPERT_LUMBER_JACK),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.EXPERT_LUMBER_JACK),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_CARPENTER, 1f), //ImageLibrary.MASTER_CARPENTER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_CARPENTER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_TOBACCO_PLANTER, 1f), //ImageLibrary.MASTER_TOBACCO_PLANTER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_TOBACCO_PLANTER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_TOBACCONIST, 1f), //ImageLibrary.MASTER_TOBACCONIST),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_TOBACCONIST),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(EXPERT_FUR_TRAPPER, 1f), //ImageLibrary.EXPERT_FUR_TRAPPER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.EXPERT_FUR_TRAPPER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_FUR_TRADER, 1f), //ImageLibrary.MASTER_FUR_TRADER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_FUR_TRADER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_COTTON_PLANTER, 1f), //ImageLibrary.MASTER_COTTON_PLANTER),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_COTTON_PLANTER),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_WEAVER, 1f), //ImageLibrary.MASTER_WEAVER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_WEAVER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_ORE_MINER, 1f), //ImageLibrary.EXPERT_ORE_MINER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_ORE_MINER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_BLACKSMITH, 1f), //ImageLibrary.MASTER_BLACKSMITH),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_BLACKSMITH),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_GUNSMITH, 1f), //ImageLibrary.MASTER_GUNSMITH),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_GUNSMITH),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_SILVER_MINER, 1f), //ImageLibrary.EXPERT_SILVER_MINER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_SILVER_MINER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(HARDY_PIONEER_WITH_TOOLS, 1f), //ImageLibrary.HARDY_PIONEER_WITH_TOOLS),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.HARDY_PIONEER),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(VETERAN_SOLDIER, 1f), //ImageLibrary.VETERAN_SOLDIER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.VETERAN_SOLDIER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(SEASONED_SCOUT_NOT_MOUNTED, 1f), //ImageLibrary.SEASONED_SCOUT_NOT_MOUNTED),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.SEASONED_SCOUT),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(JESUIT_MISSIONARY, 1f), //ImageLibrary.JESUIT_MISSIONARY),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.JESUIT_MISSIONARY),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(ELDER_STATESMAN, 1f), //ImageLibrary.ELDER_STATESMAN),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.ELDER_STATESMAN),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(FIREBRAND_PREACHER, 1f), //ImageLibrary.FIREBRAND_PREACHER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.FIREBRAND_PREACHER),
higConst.rc(row, 7));
reportPanel.doLayout();
}
| public void initialize() {
// Count Units
unitCount = new int[Unit.UNIT_COUNT];
unitLocations = new HashMap[Unit.UNIT_COUNT];
for (int index = 0; index < Unit.UNIT_COUNT; index++) {
unitLocations[index] = new HashMap();
}
Player player = parent.getClient().getMyPlayer();
Iterator units = player.getUnitIterator();
List colonies = player.getSettlements();
Collections.sort(colonies, parent.getClient().getClientOptions().getColonyComparator());
Iterator colonyIterator = colonies.iterator();
locationNames = new ArrayList();
locationNames.add(Messages.message("report.atSea"));
locationNames.add(Messages.message("report.onLand"));
if (player.getEurope() != null)
locationNames.add(player.getEurope().toString());
while (colonyIterator.hasNext()) {
locationNames.add(((Colony) colonyIterator.next()).getName());
}
while (units.hasNext()) {
Unit unit = (Unit) units.next();
int type = unit.getType();
Location location = unit.getLocation();
String locationName = null;
if (location instanceof WorkLocation) {
locationName = ((WorkLocation) location).getColony().getName();
} else if (location instanceof Europe) {
locationName = player.getEurope().toString();
} else if (location instanceof Tile &&
((Tile) location).getSettlement() != null) {
locationName = ((Colony) ((Tile) location).getSettlement()).getName();
} else if (location instanceof Unit) {
locationName = Messages.message("report.atSea");
} else {
locationName = Messages.message("report.onLand");
}
if (locationName != null) {
if (unitLocations[type].containsKey(locationName)) {
int oldValue = ((Integer) unitLocations[type].get(locationName)).intValue();
unitLocations[type].put(locationName, new Integer(oldValue + 1));
} else {
unitLocations[type].put(locationName, new Integer(1));
}
}
unitCount[unit.getType()]++;
}
// Display Panel
reportPanel.removeAll();
int margin = 30;
int[] widths = new int[] {0, 5, 0, margin, 0, 5, 0, margin, 0, 5, 0};
int[] heights = new int[] {0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0, 12, 0};
reportPanel.setLayout(new HIGLayout(widths, heights));
HIGConstraints higConst = new HIGConstraints();
int row = 1;
reportPanel.add(buildUnitLabel(FREE_COLONIST, 1f), //ImageLibrary.FREE_COLONIST);
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.FREE_COLONIST),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(INDENTURED_SERVANT, 1f), //ImageLibrary.INDENTURED_SERVANT),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.INDENTURED_SERVANT),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(PETTY_CRIMINAL, 1f), //ImageLibrary.PETTY_CRIMINAL),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.PETTY_CRIMINAL),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(INDIAN_CONVERT, 1f), //ImageLibrary.INDIAN_CONVERT),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.INDIAN_CONVERT),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_FARMER, 1f), //ImageLibrary.EXPERT_FARMER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_FARMER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(EXPERT_FISHERMAN, 1f), //ImageLibrary.EXPERT_FISHERMAN),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.EXPERT_FISHERMAN),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_SUGAR_PLANTER, 1f), //ImageLibrary.MASTER_SUGAR_PLANTER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_SUGAR_PLANTER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_DISTILLER, 1f), //ImageLibrary.MASTER_DISTILLER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_DISTILLER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(EXPERT_LUMBER_JACK, 1f), //ImageLibrary.EXPERT_LUMBER_JACK),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.EXPERT_LUMBER_JACK),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_CARPENTER, 1f), //ImageLibrary.MASTER_CARPENTER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_CARPENTER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_TOBACCO_PLANTER, 1f), //ImageLibrary.MASTER_TOBACCO_PLANTER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_TOBACCO_PLANTER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_TOBACCONIST, 1f), //ImageLibrary.MASTER_TOBACCONIST),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_TOBACCONIST),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(EXPERT_FUR_TRAPPER, 1f), //ImageLibrary.EXPERT_FUR_TRAPPER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.EXPERT_FUR_TRAPPER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(MASTER_FUR_TRADER, 1f), //ImageLibrary.MASTER_FUR_TRADER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.MASTER_FUR_TRADER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_COTTON_PLANTER, 1f), //ImageLibrary.MASTER_COTTON_PLANTER),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_COTTON_PLANTER),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_WEAVER, 1f), //ImageLibrary.MASTER_WEAVER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_WEAVER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_ORE_MINER, 1f), //ImageLibrary.EXPERT_ORE_MINER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_ORE_MINER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(MASTER_BLACKSMITH, 1f), //ImageLibrary.MASTER_BLACKSMITH),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.MASTER_BLACKSMITH),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(MASTER_GUNSMITH, 1f), //ImageLibrary.MASTER_GUNSMITH),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.MASTER_GUNSMITH),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(EXPERT_SILVER_MINER, 1f), //ImageLibrary.EXPERT_SILVER_MINER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.EXPERT_SILVER_MINER),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(HARDY_PIONEER_WITH_TOOLS, 1f), //ImageLibrary.HARDY_PIONEER_WITH_TOOLS),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.HARDY_PIONEER),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(VETERAN_SOLDIER, 1f), //ImageLibrary.VETERAN_SOLDIER),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.VETERAN_SOLDIER),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(SEASONED_SCOUT_NOT_MOUNTED, 1f), //ImageLibrary.SEASONED_SCOUT_NOT_MOUNTED),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.SEASONED_SCOUT),
higConst.rc(row, 7));
reportPanel.add(buildUnitLabel(JESUIT_MISSIONARY, 1f), //ImageLibrary.JESUIT_MISSIONARY),
higConst.rc(row, 9));
reportPanel.add(buildUnitReport(Unit.JESUIT_MISSIONARY),
higConst.rc(row, 11));
row += 2;
reportPanel.add(buildUnitLabel(ELDER_STATESMAN, 1f), //ImageLibrary.ELDER_STATESMAN),
higConst.rc(row, 1));
reportPanel.add(buildUnitReport(Unit.ELDER_STATESMAN),
higConst.rc(row, 3));
reportPanel.add(buildUnitLabel(FIREBRAND_PREACHER, 1f), //ImageLibrary.FIREBRAND_PREACHER),
higConst.rc(row, 5));
reportPanel.add(buildUnitReport(Unit.FIREBRAND_PREACHER),
higConst.rc(row, 7));
reportPanel.doLayout();
}
|
diff --git a/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/managers/CommandManager.java b/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/managers/CommandManager.java
index c4c02ee..354774a 100644
--- a/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/managers/CommandManager.java
+++ b/src/main/java/net/sacredlabyrinth/Phaed/PreciousStones/managers/CommandManager.java
@@ -1,2231 +1,2231 @@
package net.sacredlabyrinth.Phaed.PreciousStones.managers;
import net.sacredlabyrinth.Phaed.PreciousStones.*;
import net.sacredlabyrinth.Phaed.PreciousStones.entries.BlockTypeEntry;
import net.sacredlabyrinth.Phaed.PreciousStones.entries.FieldSign;
import net.sacredlabyrinth.Phaed.PreciousStones.entries.PlayerEntry;
import net.sacredlabyrinth.Phaed.PreciousStones.vectors.Field;
import net.sacredlabyrinth.Phaed.PreciousStones.vectors.Unbreakable;
import org.bukkit.Bukkit;
import org.bukkit.Material;
import org.bukkit.World;
import org.bukkit.block.Block;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
/**
* @author phaed
*/
public final class CommandManager implements CommandExecutor
{
private PreciousStones plugin;
/**
*
*/
public CommandManager()
{
plugin = PreciousStones.getInstance();
}
/**
* @param sender
* @param command
* @param label
* @param args
* @return
*/
public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
try
{
if (command.getName().equals("ps"))
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
boolean hasplayer = player != null;
if (hasplayer)
{
if (plugin.getSettingsManager().isBlacklistedWorld(player.getWorld()))
{
ChatBlock.send(player, "psDisabled");
return true;
}
}
if (args.length > 0)
{
String cmd = args[0];
args = Helper.removeFirst(args);
Block block = hasplayer ? player.getWorld().getBlockAt(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()) : null;
if (cmd.equals(ChatBlock.format("commandDebug")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebug(!plugin.getSettingsManager().isDebug());
if (plugin.getSettingsManager().isDebug())
{
ChatBlock.send(sender, "debugEnabled");
}
else
{
ChatBlock.send(sender, "debugDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOn")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(false);
ChatBlock.send(sender, "placingEnabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyEnabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOff")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (!isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(true);
ChatBlock.send(sender, "placingDisabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandAllow")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allow") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.no-allowing"))
{
if (field.hasFlag(FieldFlag.NO_ALLOWING))
{
ChatBlock.send(sender, "noSharing");
return true;
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
Player allowed = Bukkit.getServer().getPlayerExact(playerName);
// only those with permission can be allowed
if (!field.getSettings().getRequiredPermissionAllow().isEmpty())
{
if (!plugin.getPermissionsManager().has(allowed, field.getSettings().getRequiredPermissionAllow()))
{
ChatBlock.send(sender, "noPermsForAllow", playerName);
continue;
}
}
boolean done = plugin.getForceFieldManager().addAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "hasBeenAllowed", playerName);
}
else
{
ChatBlock.send(sender, "alreadyAllowed", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().allowAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "hasBeenAllowedIn", playerName, count);
}
else
{
ChatBlock.send(sender, "isAlreadyAllowedOnAll", playerName);
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.remove") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
if (field.containsPlayer(playerName))
{
ChatBlock.send(sender, "cannotRemovePlayerInField");
return true;
}
if (plugin.getForceFieldManager().conflictOfInterestExists(field, playerName))
{
ChatBlock.send(sender, "cannotDisallowWhenOverlap", playerName);
return true;
}
boolean done = plugin.getForceFieldManager().removeAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "removedFromField", playerName);
}
else
{
ChatBlock.send(sender, "playerNotFound", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemoveall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.removeall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().removeAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "removedFromFields", playerName, count);
}
else
{
ChatBlock.send(sender, "nothingToBeDone");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowed")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowed") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
List<String> allowed = field.getAllAllowed();
if (allowed.size() > 0)
{
ChatBlock.send(sender, "allowedList", Helper.toMessage(new ArrayList<String>(allowed), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersAllowedOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandCuboid")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.create.forcefield") && hasplayer)
{
if (args.length >= 1)
{
if ((args[0]).equals("commandCuboidOpen"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.CUBOID);
if (field != null)
{
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
plugin.getCuboidManager().openCuboid(player, field);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else if ((args[0]).equals("commandCuboidClose"))
{
plugin.getCuboidManager().closeCuboid(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandWho")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.who") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
HashSet<String> inhabitants = plugin.getForceFieldManager().getWho(player, field);
if (inhabitants.size() > 0)
{
ChatBlock.send(sender, "inhabitantsList", Helper.toMessage(new ArrayList<String>(inhabitants), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersFoundOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetname")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setname") && hasplayer)
{
String fieldName = null;
if (args.length >= 1)
{
fieldName = Helper.toMessage(args);
}
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
// if switching from an existing translocation
// end the previous one correctly by making sure
// to wipe out all applied blocks from the database
if (field.isNamed())
{
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
}
// check if one exists with that name already
if (plugin.getStorageManager().existsFieldWithName(fieldName, player.getName()))
{
ChatBlock.send(sender, "translocationExists");
return true;
}
// if this is a new translocation name, create its head record
// this will cement the size of the cuboid
if (!plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
plugin.getStorageManager().insertTranslocationHead(field, fieldName);
}
// updates the size of the field
plugin.getStorageManager().changeSizeTranslocatiorField(field, fieldName);
// always start off in applied (recording) mode
if (plugin.getStorageManager().existsTranslocationDataWithName(fieldName, field.getOwner()))
{
field.setDisabled(true, player);
field.dirtyFlags();
}
else
{
boolean disabled = field.setDisabled(false, player);
if (!disabled)
{
ChatBlock.send(player, "cannotEnable");
return true;
}
field.dirtyFlags();
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (fieldName == null)
{
boolean done = plugin.getForceFieldManager().setNameField(field, "");
if (done)
{
ChatBlock.send(sender, "fieldNameCleared");
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
else
{
boolean done = plugin.getForceFieldManager().setNameField(field, fieldName);
if (done)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
int count = plugin.getStorageManager().unappliedTranslocationCount(field);
if (count > 0)
{
ChatBlock.send(sender, "translocationHasBlocks", fieldName, count);
}
else
{
ChatBlock.send(sender, "translocationCreated", fieldName);
}
}
else
{
ChatBlock.send(sender, "translocationRenamed", fieldName);
}
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetradius")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setradius") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
FieldSettings fs = field.getSettings();
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
ChatBlock.send(player, "translocationCannotReshape");
return true;
}
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (!field.hasFlag(FieldFlag.CUBOID))
{
if (radius >= 0 && (radius <= fs.getRadius() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.setradius")))
{
plugin.getForceFieldManager().removeSourceField(field);
field.setRadius(radius);
plugin.getStorageManager().offerField(field);
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "radiusSet", radius);
}
else
{
ChatBlock.send(sender, "radiusMustBeLessThan", fs.getRadius());
}
}
else
{
ChatBlock.send(sender, "cuboidCannotChangeRadius");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetvelocity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setvelocity") && hasplayer)
{
if (args.length == 1 && Helper.isFloat(args[0]))
{
float velocity = Float.parseFloat(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
FieldSettings fs = field.getSettings();
if (fs.hasVeocityFlag())
{
if (velocity < 0 || velocity > 5)
{
ChatBlock.send(sender, "velocityMustBe");
return true;
}
field.setVelocity(velocity);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "velocitySetTo", velocity);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandDisable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.disable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.isDisabled())
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().clearTranslocation(field);
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotDisable");
return true;
}
field.setDisabled(true, player);
field.dirtyFlags();
ChatBlock.send(sender, "fieldDisabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyDisabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.enable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isDisabled())
{
// update translocation
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().applyTranslocation(field);
}
}
boolean disabled = field.setDisabled(false, player);
if (!disabled)
{
ChatBlock.send(sender, "cannotEnable");
return true;
}
field.dirtyFlags();
ChatBlock.send(sender, "fieldEnabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyEnabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDensity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.density") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int density = Integer.parseInt(args[0]);
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
data.setDensity(density);
plugin.getStorageManager().offerPlayer(player.getName());
ChatBlock.send(sender, "visualizationChanged", density);
return true;
}
else if (args.length == 0)
{
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
ChatBlock.send(sender, "visualizationSet", data.getDensity());
}
}
else if (cmd.equals(ChatBlock.format("commandToggle")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled"))
{
if (field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "flagsToggledWhileDisabled");
return true;
}
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (field.hasFlag(flagStr) || field.hasDisabledFlag(flagStr))
{
boolean unToggable = false;
if (field.hasFlag(FieldFlag.DYNMAP_NO_TOGGLE))
{
if (flagStr.equalsIgnoreCase("dynmap-area"))
{
unToggable = true;
}
if (flagStr.equalsIgnoreCase("dynmap-marker"))
{
unToggable = true;
}
}
try
{
if (FieldFlag.getByString(flagStr).isUnToggable())
{
unToggable = true;
}
}
catch (Exception ex)
{
ChatBlock.send(sender, "flagNotFound");
return true;
}
if (unToggable)
{
ChatBlock.send(sender, "flagCannottoggle");
return true;
}
boolean enabled = field.toggleFieldFlag(flagStr);
if (enabled)
{
ChatBlock.send(sender, "flagEnabled", flagStr);
}
else
{
ChatBlock.send(sender, "flagDisabled", flagStr);
}
plugin.getStorageManager().offerField(field);
}
else
{
ChatBlock.send(sender, "flagNotFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if ((cmd.equals(ChatBlock.format("commandVisualize")) || cmd.equals("visualise")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize"))
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Math.min(Integer.parseInt(args[0]), plugin.getServer().getViewDistance());
Set<Field> fieldsInArea;
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize"))
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL);
}
else
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL, player);
}
if (fieldsInArea != null && fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "visualizing");
int count = 0;
for (Field f : fieldsInArea)
{
if (count++ >= plugin.getSettingsManager().getVisualizeMaxFields())
{
continue;
}
plugin.getVisualizationManager().addVisualizationField(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, true);
return true;
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
ChatBlock.send(sender, "visualizing");
plugin.getVisualizationManager().addVisualizationField(player, field);
plugin.getVisualizationManager().displayVisualization(player, true);
}
else
{
ChatBlock.send(sender, "notInsideField");
}
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "visualizationNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandMark")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.mark") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.mark"))
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "markingFields", fieldsInArea.size());
for (Field f : fieldsInArea)
{
plugin.getVisualizationManager().addFieldMark(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
int count = 0;
for (Field f : fieldsInArea)
{
if (plugin.getForceFieldManager().isAllowed(f, player.getName()))
{
count++;
plugin.getVisualizationManager().addFieldMark(player, f);
}
}
if (count > 0)
{
ChatBlock.send(sender, "markingFields", count);
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "markingNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandInsert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.insert") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.hasFlag(flagStr) && !field.hasDisabledFlag(flagStr))
{
plugin.getForceFieldManager().removeSourceField(field);
if (field.insertFieldFlag(flagStr))
{
field.dirtyFlags();
ChatBlock.send(sender, "flagInserted");
}
else
{
ChatBlock.send(sender, "flagNotExists");
}
plugin.getForceFieldManager().addSourceField(field);
}
else
{
ChatBlock.send(sender, "flagExists");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandReset")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reset") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
field.RevertFlags();
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "flagsReverted");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetinterval")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setinterval") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int interval = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.GRIEF_REVERT);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (interval >= plugin.getSettingsManager().getGriefRevertMinInterval() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.interval"))
{
field.setRevertSecs(interval);
plugin.getGriefUndoManager().register(field);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "griefRevertIntervalSet", interval);
}
else
{
ChatBlock.send(sender, "minInterval", plugin.getSettingsManager().getGriefRevertMinInterval());
}
}
else
{
ChatBlock.send(sender, "notPointingAtGriefRevert");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSnitch")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.snitch") && hasplayer)
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
plugin.getCommunicationManager().showSnitchList(player, field);
}
else
{
ChatBlock.send(sender, "notPointingAtSnitch");
}
return true;
}
else if (args.length == 1)
{
- if (args[0].equals("commandSnitchClear"))
+ if (args[0].equals(ChatBlock.format("commandSnitchClear")))
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
boolean cleaned = plugin.getForceFieldManager().cleanSnitchList(field);
if (cleaned)
{
ChatBlock.send(sender, "clearedSnitch");
}
else
{
ChatBlock.send(sender, "snitchEmpty");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandTranslocation")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.use") && hasplayer)
{
if (args.length == 0)
{
ChatBlock.send(sender, "translocationMenu1");
ChatBlock.send(sender, "translocationMenu2");
ChatBlock.send(sender, "translocationMenu3");
ChatBlock.send(sender, "translocationMenu4");
ChatBlock.send(sender, "translocationMenu5");
ChatBlock.send(sender, "translocationMenu6");
ChatBlock.send(sender, "translocationMenu7");
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationList")))
{
plugin.getCommunicationManager().notifyStoredTranslocations(player);
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.delete"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (args.length == 0)
{
plugin.getStorageManager().deleteTranslocation(args[1], player.getName());
ChatBlock.send(sender, "translocationDeleted", args[0]);
}
else
{
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
int count = plugin.getStorageManager().deleteBlockTypeFromTranslocation(field.getName(), player.getName(), entry);
if (count > 0)
{
ChatBlock.send(sender, "translocationDeletedBlocks", count, Helper.friendlyBlockType(Material.getMaterial(entry.getTypeId()).toString()), field.getName());
}
else
{
ChatBlock.send(sender, "noBlocksMatched", arg);
}
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.remove"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledFirst");
return true;
}
if (args.length > 0)
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().removeBlocks(field, player, entries);
}
}
else
{
ChatBlock.send(sender, "usageTranslocationRemove");
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationUnlink")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.unlink"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToUnlink");
return true;
}
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
else
{
ChatBlock.send(sender, "translocationNothingToUnlink");
return true;
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationImport")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.import"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToImport");
return true;
}
if (args.length == 0)
{
plugin.getTranslocationManager().importBlocks(field, player, null);
}
else
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
if (!field.getSettings().canTranslocate(entry))
{
ChatBlock.send(sender, "blockIsBlacklisted", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().importBlocks(field, player, entries);
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandMore")) && hasplayer)
{
ChatBlock cb = plugin.getCommunicationManager().getChatBlock(player);
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
cb.sendBlock(player, plugin.getSettingsManager().getLinesPerPage());
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
ChatBlock.send(sender, "moreNextPage");
}
ChatBlock.sendBlank(player);
return true;
}
ChatBlock.send(sender, "moreNothingMore");
return true;
}
else if (cmd.equals(ChatBlock.format("commandCounts")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.counts") && hasplayer)
{
if (!plugin.getCommunicationManager().showFieldCounts(player, player.getName()))
{
ChatBlock.send(sender, "playerHasNoFields");
}
return true;
}
if (args.length == 1 && plugin.getPermissionsManager().has(player, "preciousstones.admin.counts"))
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
if (!plugin.getCommunicationManager().showCounts(sender, type))
{
ChatBlock.send(sender, "notValidFieldType");
}
}
}
else if (Helper.isString(args[0]) && hasplayer)
{
String target = args[0];
if (!plugin.getCommunicationManager().showFieldCounts(player, target))
{
ChatBlock.send(sender, "playerHasNoFields");
}
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandLocations")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.locations") && hasplayer)
{
plugin.getCommunicationManager().showFieldLocations(sender, -1, sender.getName());
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.locations"))
{
if (args.length == 1 && Helper.isString(args[0]))
{
String targetName = args[0];
plugin.getCommunicationManager().showFieldLocations(sender, -1, targetName);
}
if (args.length == 2 && Helper.isString(args[0]) && Helper.isInteger(args[1]))
{
String targetName = args[0];
int type = Integer.parseInt(args[1]);
plugin.getCommunicationManager().showFieldLocations(sender, type, targetName);
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandInfo")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.info") && hasplayer)
{
Field pointing = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
List<Field> fields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (pointing != null && !fields.contains(pointing))
{
fields.add(pointing);
}
if (fields.size() == 1)
{
plugin.getCommunicationManager().showFieldDetails(player, fields.get(0));
}
else
{
plugin.getCommunicationManager().showFieldDetails(player, fields);
}
if (fields.isEmpty())
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.delete"))
{
if (args.length == 0 && hasplayer)
{
List<Field> sourceFields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (sourceFields.size() > 0)
{
int count = plugin.getForceFieldManager().deleteFields(sourceFields);
if (count > 0)
{
ChatBlock.send(sender, "protectionRemoved");
if (plugin.getSettingsManager().isLogBypassDelete())
{
PreciousStones.log("protectionRemovedFrom", count);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (args.length == 1)
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deleteFieldsOfType(type);
int ubs = plugin.getUnbreakableManager().deleteUnbreakablesOfType(type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedUnbreakables", ubs, Material.getMaterial(type.getTypeId()));
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
int fields = plugin.getForceFieldManager().deleteBelonging(args[0]);
int ubs = plugin.getUnbreakableManager().deleteBelonging(args[0]);
if (fields > 0)
{
ChatBlock.send(sender, "deletedCountFields", args[0], fields);
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedCountUnbreakables", args[0], ubs);
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "playerHasNoPstones");
}
}
return true;
}
else if (args.length == 2)
{
if (Helper.isTypeEntry(args[1]))
{
String name = args[0];
BlockTypeEntry type = Helper.toTypeEntry(args[1]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deletePlayerFieldsOfType(name, type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
ChatBlock.send(sender, "notValidBlockId", args[1]);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandBlacklisting")) && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (args.length == 0 || args.length > 1 || args[0].contains("/"))
{
ChatBlock.send(sender, "commandBlacklistUsage");
return true;
}
String blacklistedCommand = args[0];
if (field != null)
{
if (field.hasFlag(FieldFlag.COMMAND_BLACKLISTING))
{
if (blacklistedCommand.equalsIgnoreCase("clear"))
{
field.clearBlacklistedCommands();
ChatBlock.send(sender, "commandBlacklistCleared");
}
else
{
field.addBlacklistedCommand(blacklistedCommand);
ChatBlock.send(sender, "commandBlacklistAdded");
}
}
else
{
ChatBlock.send(sender, "noBlacklistingFieldFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetLimit")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setlimit") && hasplayer)
{
if (args.length == 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
String period = args[0];
if (!SignHelper.isValidPeriod(period))
{
ChatBlock.send(sender, "limitMalformed");
ChatBlock.send(sender, "limitMalformed2");
ChatBlock.send(sender, "limitMalformed3");
return true;
}
if (!field.hasFlag(FieldFlag.RENTABLE) && !field.hasFlag(FieldFlag.SHAREABLE))
{
ChatBlock.send(sender, "limitBadField");
return true;
}
field.setLimitSeconds(SignHelper.periodToSeconds(period));
ChatBlock.send(sender, "limitSet");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetowner")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.setowner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
// transfer the count over to the new owner
plugin.getStorageManager().changeTranslocationOwner(field, owner);
plugin.getStorageManager().offerPlayer(field.getOwner());
plugin.getStorageManager().offerPlayer(owner);
// change the owner
field.setOwner(owner);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "ownerSetTo", owner);
return true;
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandChangeowner")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.change-owner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
if (field.isOwner(player.getName()))
{
if (field.hasFlag(FieldFlag.CAN_CHANGE_OWNER))
{
if (field.isBought())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
plugin.getForceFieldManager().changeOwner(field, owner);
ChatBlock.send(sender, "fieldCanBeTaken", owner);
return true;
}
else
{
ChatBlock.send(sender, "fieldCannotChangeOwner");
}
}
else
{
ChatBlock.send(sender, "ownerCanOnlyChangeOwner");
}
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandList")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.list") && hasplayer)
{
if (args.length == 1)
{
if (Helper.isInteger(args[0]))
{
int chunk_radius = Integer.parseInt(args[0]);
List<Unbreakable> unbreakables = plugin.getUnbreakableManager().getUnbreakablesInArea(player, chunk_radius);
Set<Field> fields = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), chunk_radius, FieldFlag.ALL);
for (Unbreakable u : unbreakables)
{
ChatBlock.send(sender, "{aqua}{unbreakable}", u.toString());
}
for (Field f : fields)
{
ChatBlock.send(sender, "{aqua}{field}", f.toString());
}
if (unbreakables.isEmpty() && fields.isEmpty())
{
ChatBlock.send(sender, "noPstonesFound");
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandReload")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reload"))
{
plugin.getSettingsManager().load();
plugin.getLanguageManager().load();
ChatBlock.send(sender, "configReloaded");
return true;
}
else if (cmd.equals(ChatBlock.format("commandBuy")))
{
if (plugin.getSettingsManager().isCommandsToRentBuy())
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.BUYABLE);
if (field != null)
{
FieldSign s = field.getAttachedFieldSign();
if (s.isBuyable())
{
if (field.hasPendingPurchase())
{
ChatBlock.send(player, "fieldSignAlreadyBought");
}
else if (field.buy(player, s))
{
s.setBoughtColor(player);
PreciousStones.getInstance().getForceFieldManager().addAllowed(field, player.getName());
ChatBlock.send(player, "fieldSignBoughtAndAllowed");
}
return true;
}
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRent")))
{
if (plugin.getSettingsManager().isCommandsToRentBuy())
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.SHAREABLE);
if (field == null)
{
field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.RENTABLE);
}
if (field != null)
{
FieldSign s = field.getAttachedFieldSign();
if (s.isRentable())
{
if (field.isRented())
{
if (!field.isRenter(player.getName()))
{
ChatBlock.send(player, "fieldSignAlreadyRented");
plugin.getCommunicationManager().showRenterInfo(player, field);
return true;
}
else
{
if (player.isSneaking())
{
field.abandonRent(player);
ChatBlock.send(player, "fieldSignRentAbandoned");
return true;
}
}
}
}
if (field.rent(player, s))
{
if (s.isRentable())
{
s.setRentedColor();
}
else if (s.isShareable())
{
s.setSharedColor();
}
return true;
}
}
}
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.rent"))
{
if (args.length > 0)
{
String sub = args[0];
if (sub.equalsIgnoreCase(ChatBlock.format("commandRentClear")))
{
Field field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.RENTABLE);
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.SHAREABLE);
}
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.BUYABLE);
}
if (field != null)
{
if (field.clearRents())
{
ChatBlock.send(sender, "rentsCleared");
}
else
{
ChatBlock.send(sender, "rentsClearedNone");
}
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
if (sub.equalsIgnoreCase(ChatBlock.format("commandRentRemove")))
{
Field field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.RENTABLE);
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.SHAREABLE);
}
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.BUYABLE);
}
if (field != null)
{
if (field.removeRents())
{
ChatBlock.send(sender, "rentsRemoved");
}
else
{
ChatBlock.send(sender, "rentsRemovedNone");
}
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandFields")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.fields"))
{
plugin.getCommunicationManager().showConfiguredFields(sender);
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.enableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().enableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagEnabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDisableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.disableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().disableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagDisabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandClean")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.clean"))
{
if (args.length == 1)
{
String worldName = args[0];
World world = Bukkit.getServer().getWorld(worldName);
if (world != null)
{
int cleanedFF = plugin.getForceFieldManager().cleanOrphans(world);
int cleanedU = plugin.getUnbreakableManager().cleanOrphans(world);
if (cleanedFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
else
{
ChatBlock.send(sender, "worldNotFound");
}
}
else
{
List<World> worlds = plugin.getServer().getWorlds();
int cleanedFF = 0;
int cleanedU = 0;
for (World world : worlds)
{
cleanedFF += plugin.getForceFieldManager().cleanOrphans(world);
cleanedU += plugin.getUnbreakableManager().cleanOrphans(world);
}
if (cleanedFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandRevert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.revert"))
{
if (args.length == 1)
{
String worldName = args[0];
World world = Bukkit.getServer().getWorld(worldName);
if (world != null)
{
int cleanedFF = plugin.getForceFieldManager().revertOrphans(world);
int cleanedU = plugin.getUnbreakableManager().revertOrphans(world);
if (cleanedFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
else
{
ChatBlock.send(sender, "worldNotFound");
}
}
else
{
List<World> worlds = plugin.getServer().getWorlds();
int cleanedFF = 0;
int cleanedU = 0;
for (World world : worlds)
{
cleanedFF += plugin.getForceFieldManager().revertOrphans(world);
cleanedU += plugin.getUnbreakableManager().revertOrphans(world);
}
if (cleanedFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandBypass")) && plugin.getPermissionsManager().has(player, "preciousstones.bypass.toggle"))
{
PlayerEntry entry = plugin.getPlayerManager().getPlayerEntry(player.getName());
if (args.length == 1)
{
String mode = args[0];
if (mode.equals(ChatBlock.format("commandOn")))
{
entry.setBypassDisabled(false);
ChatBlock.send(player, "bypassEnabled");
}
else if (mode.equals(ChatBlock.format("commandOff")))
{
entry.setBypassDisabled(true);
ChatBlock.send(player, "bypassDisabled");
}
}
else
{
if (entry.isBypassDisabled())
{
entry.setBypassDisabled(false);
ChatBlock.send(player, "bypassEnabled");
}
else
{
entry.setBypassDisabled(true);
ChatBlock.send(player, "bypassDisabled");
}
}
plugin.getStorageManager().offerPlayer(player.getName());
return true;
}
else if (cmd.equals(ChatBlock.format("commandHide")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.hide"))
{
if (args.length == 1)
{
if (args[0].equals(ChatBlock.format("commandAll")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.hideall"))
{
int count = plugin.getForceFieldManager().hideBelonging(player.getName());
if (count > 0)
{
ChatBlock.send(sender, "hideHideAll", count);
}
}
}
else
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.HIDABLE))
{
if (!field.isHidden())
{
if (!field.matchesBlockType())
{
ChatBlock.send(sender, "cannotHideOrphan");
return true;
}
field.hide();
ChatBlock.send(sender, "hideHide");
}
else
{
ChatBlock.send(sender, "hideHiddenAlready");
}
}
else
{
ChatBlock.send(sender, "hideCannot");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandUnhide")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.hide"))
{
if (args.length == 1)
{
if (args[0].equals(ChatBlock.format("commandAll")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.hideall"))
{
int count = plugin.getForceFieldManager().unhideBelonging(player.getName());
if (count > 0)
{
ChatBlock.send(sender, "hideUnhideAll", count);
}
}
}
else
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.HIDABLE))
{
if (field.isHidden())
{
field.unHide();
ChatBlock.send(sender, "hideUnhide");
}
else
{
ChatBlock.send(sender, "hideUnHiddenAlready");
}
}
else
{
ChatBlock.send(sender, "hideCannot");
}
}
else
{
ChatBlock.send(sender, "hideNoneFound");
}
}
return true;
}
ChatBlock.send(sender, "notValidCommand");
return true;
}
// show the player menu
plugin.getCommunicationManager().showMenu(player);
return true;
}
}
catch (Exception ex)
{
System.out.print("Error: " + ex.getMessage());
for (StackTraceElement el : ex.getStackTrace())
{
System.out.print(el.toString());
}
}
return false;
}
}
| true | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
try
{
if (command.getName().equals("ps"))
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
boolean hasplayer = player != null;
if (hasplayer)
{
if (plugin.getSettingsManager().isBlacklistedWorld(player.getWorld()))
{
ChatBlock.send(player, "psDisabled");
return true;
}
}
if (args.length > 0)
{
String cmd = args[0];
args = Helper.removeFirst(args);
Block block = hasplayer ? player.getWorld().getBlockAt(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()) : null;
if (cmd.equals(ChatBlock.format("commandDebug")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebug(!plugin.getSettingsManager().isDebug());
if (plugin.getSettingsManager().isDebug())
{
ChatBlock.send(sender, "debugEnabled");
}
else
{
ChatBlock.send(sender, "debugDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOn")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(false);
ChatBlock.send(sender, "placingEnabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyEnabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOff")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (!isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(true);
ChatBlock.send(sender, "placingDisabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandAllow")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allow") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.no-allowing"))
{
if (field.hasFlag(FieldFlag.NO_ALLOWING))
{
ChatBlock.send(sender, "noSharing");
return true;
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
Player allowed = Bukkit.getServer().getPlayerExact(playerName);
// only those with permission can be allowed
if (!field.getSettings().getRequiredPermissionAllow().isEmpty())
{
if (!plugin.getPermissionsManager().has(allowed, field.getSettings().getRequiredPermissionAllow()))
{
ChatBlock.send(sender, "noPermsForAllow", playerName);
continue;
}
}
boolean done = plugin.getForceFieldManager().addAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "hasBeenAllowed", playerName);
}
else
{
ChatBlock.send(sender, "alreadyAllowed", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().allowAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "hasBeenAllowedIn", playerName, count);
}
else
{
ChatBlock.send(sender, "isAlreadyAllowedOnAll", playerName);
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.remove") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
if (field.containsPlayer(playerName))
{
ChatBlock.send(sender, "cannotRemovePlayerInField");
return true;
}
if (plugin.getForceFieldManager().conflictOfInterestExists(field, playerName))
{
ChatBlock.send(sender, "cannotDisallowWhenOverlap", playerName);
return true;
}
boolean done = plugin.getForceFieldManager().removeAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "removedFromField", playerName);
}
else
{
ChatBlock.send(sender, "playerNotFound", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemoveall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.removeall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().removeAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "removedFromFields", playerName, count);
}
else
{
ChatBlock.send(sender, "nothingToBeDone");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowed")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowed") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
List<String> allowed = field.getAllAllowed();
if (allowed.size() > 0)
{
ChatBlock.send(sender, "allowedList", Helper.toMessage(new ArrayList<String>(allowed), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersAllowedOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandCuboid")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.create.forcefield") && hasplayer)
{
if (args.length >= 1)
{
if ((args[0]).equals("commandCuboidOpen"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.CUBOID);
if (field != null)
{
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
plugin.getCuboidManager().openCuboid(player, field);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else if ((args[0]).equals("commandCuboidClose"))
{
plugin.getCuboidManager().closeCuboid(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandWho")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.who") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
HashSet<String> inhabitants = plugin.getForceFieldManager().getWho(player, field);
if (inhabitants.size() > 0)
{
ChatBlock.send(sender, "inhabitantsList", Helper.toMessage(new ArrayList<String>(inhabitants), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersFoundOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetname")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setname") && hasplayer)
{
String fieldName = null;
if (args.length >= 1)
{
fieldName = Helper.toMessage(args);
}
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
// if switching from an existing translocation
// end the previous one correctly by making sure
// to wipe out all applied blocks from the database
if (field.isNamed())
{
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
}
// check if one exists with that name already
if (plugin.getStorageManager().existsFieldWithName(fieldName, player.getName()))
{
ChatBlock.send(sender, "translocationExists");
return true;
}
// if this is a new translocation name, create its head record
// this will cement the size of the cuboid
if (!plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
plugin.getStorageManager().insertTranslocationHead(field, fieldName);
}
// updates the size of the field
plugin.getStorageManager().changeSizeTranslocatiorField(field, fieldName);
// always start off in applied (recording) mode
if (plugin.getStorageManager().existsTranslocationDataWithName(fieldName, field.getOwner()))
{
field.setDisabled(true, player);
field.dirtyFlags();
}
else
{
boolean disabled = field.setDisabled(false, player);
if (!disabled)
{
ChatBlock.send(player, "cannotEnable");
return true;
}
field.dirtyFlags();
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (fieldName == null)
{
boolean done = plugin.getForceFieldManager().setNameField(field, "");
if (done)
{
ChatBlock.send(sender, "fieldNameCleared");
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
else
{
boolean done = plugin.getForceFieldManager().setNameField(field, fieldName);
if (done)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
int count = plugin.getStorageManager().unappliedTranslocationCount(field);
if (count > 0)
{
ChatBlock.send(sender, "translocationHasBlocks", fieldName, count);
}
else
{
ChatBlock.send(sender, "translocationCreated", fieldName);
}
}
else
{
ChatBlock.send(sender, "translocationRenamed", fieldName);
}
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetradius")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setradius") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
FieldSettings fs = field.getSettings();
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
ChatBlock.send(player, "translocationCannotReshape");
return true;
}
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (!field.hasFlag(FieldFlag.CUBOID))
{
if (radius >= 0 && (radius <= fs.getRadius() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.setradius")))
{
plugin.getForceFieldManager().removeSourceField(field);
field.setRadius(radius);
plugin.getStorageManager().offerField(field);
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "radiusSet", radius);
}
else
{
ChatBlock.send(sender, "radiusMustBeLessThan", fs.getRadius());
}
}
else
{
ChatBlock.send(sender, "cuboidCannotChangeRadius");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetvelocity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setvelocity") && hasplayer)
{
if (args.length == 1 && Helper.isFloat(args[0]))
{
float velocity = Float.parseFloat(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
FieldSettings fs = field.getSettings();
if (fs.hasVeocityFlag())
{
if (velocity < 0 || velocity > 5)
{
ChatBlock.send(sender, "velocityMustBe");
return true;
}
field.setVelocity(velocity);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "velocitySetTo", velocity);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandDisable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.disable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.isDisabled())
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().clearTranslocation(field);
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotDisable");
return true;
}
field.setDisabled(true, player);
field.dirtyFlags();
ChatBlock.send(sender, "fieldDisabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyDisabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.enable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isDisabled())
{
// update translocation
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().applyTranslocation(field);
}
}
boolean disabled = field.setDisabled(false, player);
if (!disabled)
{
ChatBlock.send(sender, "cannotEnable");
return true;
}
field.dirtyFlags();
ChatBlock.send(sender, "fieldEnabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyEnabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDensity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.density") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int density = Integer.parseInt(args[0]);
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
data.setDensity(density);
plugin.getStorageManager().offerPlayer(player.getName());
ChatBlock.send(sender, "visualizationChanged", density);
return true;
}
else if (args.length == 0)
{
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
ChatBlock.send(sender, "visualizationSet", data.getDensity());
}
}
else if (cmd.equals(ChatBlock.format("commandToggle")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled"))
{
if (field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "flagsToggledWhileDisabled");
return true;
}
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (field.hasFlag(flagStr) || field.hasDisabledFlag(flagStr))
{
boolean unToggable = false;
if (field.hasFlag(FieldFlag.DYNMAP_NO_TOGGLE))
{
if (flagStr.equalsIgnoreCase("dynmap-area"))
{
unToggable = true;
}
if (flagStr.equalsIgnoreCase("dynmap-marker"))
{
unToggable = true;
}
}
try
{
if (FieldFlag.getByString(flagStr).isUnToggable())
{
unToggable = true;
}
}
catch (Exception ex)
{
ChatBlock.send(sender, "flagNotFound");
return true;
}
if (unToggable)
{
ChatBlock.send(sender, "flagCannottoggle");
return true;
}
boolean enabled = field.toggleFieldFlag(flagStr);
if (enabled)
{
ChatBlock.send(sender, "flagEnabled", flagStr);
}
else
{
ChatBlock.send(sender, "flagDisabled", flagStr);
}
plugin.getStorageManager().offerField(field);
}
else
{
ChatBlock.send(sender, "flagNotFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if ((cmd.equals(ChatBlock.format("commandVisualize")) || cmd.equals("visualise")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize"))
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Math.min(Integer.parseInt(args[0]), plugin.getServer().getViewDistance());
Set<Field> fieldsInArea;
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize"))
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL);
}
else
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL, player);
}
if (fieldsInArea != null && fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "visualizing");
int count = 0;
for (Field f : fieldsInArea)
{
if (count++ >= plugin.getSettingsManager().getVisualizeMaxFields())
{
continue;
}
plugin.getVisualizationManager().addVisualizationField(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, true);
return true;
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
ChatBlock.send(sender, "visualizing");
plugin.getVisualizationManager().addVisualizationField(player, field);
plugin.getVisualizationManager().displayVisualization(player, true);
}
else
{
ChatBlock.send(sender, "notInsideField");
}
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "visualizationNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandMark")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.mark") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.mark"))
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "markingFields", fieldsInArea.size());
for (Field f : fieldsInArea)
{
plugin.getVisualizationManager().addFieldMark(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
int count = 0;
for (Field f : fieldsInArea)
{
if (plugin.getForceFieldManager().isAllowed(f, player.getName()))
{
count++;
plugin.getVisualizationManager().addFieldMark(player, f);
}
}
if (count > 0)
{
ChatBlock.send(sender, "markingFields", count);
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "markingNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandInsert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.insert") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.hasFlag(flagStr) && !field.hasDisabledFlag(flagStr))
{
plugin.getForceFieldManager().removeSourceField(field);
if (field.insertFieldFlag(flagStr))
{
field.dirtyFlags();
ChatBlock.send(sender, "flagInserted");
}
else
{
ChatBlock.send(sender, "flagNotExists");
}
plugin.getForceFieldManager().addSourceField(field);
}
else
{
ChatBlock.send(sender, "flagExists");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandReset")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reset") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
field.RevertFlags();
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "flagsReverted");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetinterval")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setinterval") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int interval = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.GRIEF_REVERT);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (interval >= plugin.getSettingsManager().getGriefRevertMinInterval() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.interval"))
{
field.setRevertSecs(interval);
plugin.getGriefUndoManager().register(field);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "griefRevertIntervalSet", interval);
}
else
{
ChatBlock.send(sender, "minInterval", plugin.getSettingsManager().getGriefRevertMinInterval());
}
}
else
{
ChatBlock.send(sender, "notPointingAtGriefRevert");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSnitch")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.snitch") && hasplayer)
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
plugin.getCommunicationManager().showSnitchList(player, field);
}
else
{
ChatBlock.send(sender, "notPointingAtSnitch");
}
return true;
}
else if (args.length == 1)
{
if (args[0].equals("commandSnitchClear"))
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
boolean cleaned = plugin.getForceFieldManager().cleanSnitchList(field);
if (cleaned)
{
ChatBlock.send(sender, "clearedSnitch");
}
else
{
ChatBlock.send(sender, "snitchEmpty");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandTranslocation")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.use") && hasplayer)
{
if (args.length == 0)
{
ChatBlock.send(sender, "translocationMenu1");
ChatBlock.send(sender, "translocationMenu2");
ChatBlock.send(sender, "translocationMenu3");
ChatBlock.send(sender, "translocationMenu4");
ChatBlock.send(sender, "translocationMenu5");
ChatBlock.send(sender, "translocationMenu6");
ChatBlock.send(sender, "translocationMenu7");
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationList")))
{
plugin.getCommunicationManager().notifyStoredTranslocations(player);
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.delete"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (args.length == 0)
{
plugin.getStorageManager().deleteTranslocation(args[1], player.getName());
ChatBlock.send(sender, "translocationDeleted", args[0]);
}
else
{
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
int count = plugin.getStorageManager().deleteBlockTypeFromTranslocation(field.getName(), player.getName(), entry);
if (count > 0)
{
ChatBlock.send(sender, "translocationDeletedBlocks", count, Helper.friendlyBlockType(Material.getMaterial(entry.getTypeId()).toString()), field.getName());
}
else
{
ChatBlock.send(sender, "noBlocksMatched", arg);
}
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.remove"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledFirst");
return true;
}
if (args.length > 0)
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().removeBlocks(field, player, entries);
}
}
else
{
ChatBlock.send(sender, "usageTranslocationRemove");
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationUnlink")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.unlink"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToUnlink");
return true;
}
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
else
{
ChatBlock.send(sender, "translocationNothingToUnlink");
return true;
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationImport")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.import"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToImport");
return true;
}
if (args.length == 0)
{
plugin.getTranslocationManager().importBlocks(field, player, null);
}
else
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
if (!field.getSettings().canTranslocate(entry))
{
ChatBlock.send(sender, "blockIsBlacklisted", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().importBlocks(field, player, entries);
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandMore")) && hasplayer)
{
ChatBlock cb = plugin.getCommunicationManager().getChatBlock(player);
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
cb.sendBlock(player, plugin.getSettingsManager().getLinesPerPage());
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
ChatBlock.send(sender, "moreNextPage");
}
ChatBlock.sendBlank(player);
return true;
}
ChatBlock.send(sender, "moreNothingMore");
return true;
}
else if (cmd.equals(ChatBlock.format("commandCounts")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.counts") && hasplayer)
{
if (!plugin.getCommunicationManager().showFieldCounts(player, player.getName()))
{
ChatBlock.send(sender, "playerHasNoFields");
}
return true;
}
if (args.length == 1 && plugin.getPermissionsManager().has(player, "preciousstones.admin.counts"))
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
if (!plugin.getCommunicationManager().showCounts(sender, type))
{
ChatBlock.send(sender, "notValidFieldType");
}
}
}
else if (Helper.isString(args[0]) && hasplayer)
{
String target = args[0];
if (!plugin.getCommunicationManager().showFieldCounts(player, target))
{
ChatBlock.send(sender, "playerHasNoFields");
}
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandLocations")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.locations") && hasplayer)
{
plugin.getCommunicationManager().showFieldLocations(sender, -1, sender.getName());
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.locations"))
{
if (args.length == 1 && Helper.isString(args[0]))
{
String targetName = args[0];
plugin.getCommunicationManager().showFieldLocations(sender, -1, targetName);
}
if (args.length == 2 && Helper.isString(args[0]) && Helper.isInteger(args[1]))
{
String targetName = args[0];
int type = Integer.parseInt(args[1]);
plugin.getCommunicationManager().showFieldLocations(sender, type, targetName);
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandInfo")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.info") && hasplayer)
{
Field pointing = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
List<Field> fields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (pointing != null && !fields.contains(pointing))
{
fields.add(pointing);
}
if (fields.size() == 1)
{
plugin.getCommunicationManager().showFieldDetails(player, fields.get(0));
}
else
{
plugin.getCommunicationManager().showFieldDetails(player, fields);
}
if (fields.isEmpty())
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.delete"))
{
if (args.length == 0 && hasplayer)
{
List<Field> sourceFields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (sourceFields.size() > 0)
{
int count = plugin.getForceFieldManager().deleteFields(sourceFields);
if (count > 0)
{
ChatBlock.send(sender, "protectionRemoved");
if (plugin.getSettingsManager().isLogBypassDelete())
{
PreciousStones.log("protectionRemovedFrom", count);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (args.length == 1)
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deleteFieldsOfType(type);
int ubs = plugin.getUnbreakableManager().deleteUnbreakablesOfType(type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedUnbreakables", ubs, Material.getMaterial(type.getTypeId()));
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
int fields = plugin.getForceFieldManager().deleteBelonging(args[0]);
int ubs = plugin.getUnbreakableManager().deleteBelonging(args[0]);
if (fields > 0)
{
ChatBlock.send(sender, "deletedCountFields", args[0], fields);
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedCountUnbreakables", args[0], ubs);
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "playerHasNoPstones");
}
}
return true;
}
else if (args.length == 2)
{
if (Helper.isTypeEntry(args[1]))
{
String name = args[0];
BlockTypeEntry type = Helper.toTypeEntry(args[1]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deletePlayerFieldsOfType(name, type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
ChatBlock.send(sender, "notValidBlockId", args[1]);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandBlacklisting")) && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (args.length == 0 || args.length > 1 || args[0].contains("/"))
{
ChatBlock.send(sender, "commandBlacklistUsage");
return true;
}
String blacklistedCommand = args[0];
if (field != null)
{
if (field.hasFlag(FieldFlag.COMMAND_BLACKLISTING))
{
if (blacklistedCommand.equalsIgnoreCase("clear"))
{
field.clearBlacklistedCommands();
ChatBlock.send(sender, "commandBlacklistCleared");
}
else
{
field.addBlacklistedCommand(blacklistedCommand);
ChatBlock.send(sender, "commandBlacklistAdded");
}
}
else
{
ChatBlock.send(sender, "noBlacklistingFieldFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetLimit")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setlimit") && hasplayer)
{
if (args.length == 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
String period = args[0];
if (!SignHelper.isValidPeriod(period))
{
ChatBlock.send(sender, "limitMalformed");
ChatBlock.send(sender, "limitMalformed2");
ChatBlock.send(sender, "limitMalformed3");
return true;
}
if (!field.hasFlag(FieldFlag.RENTABLE) && !field.hasFlag(FieldFlag.SHAREABLE))
{
ChatBlock.send(sender, "limitBadField");
return true;
}
field.setLimitSeconds(SignHelper.periodToSeconds(period));
ChatBlock.send(sender, "limitSet");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetowner")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.setowner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
// transfer the count over to the new owner
plugin.getStorageManager().changeTranslocationOwner(field, owner);
plugin.getStorageManager().offerPlayer(field.getOwner());
plugin.getStorageManager().offerPlayer(owner);
// change the owner
field.setOwner(owner);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "ownerSetTo", owner);
return true;
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandChangeowner")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.change-owner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
if (field.isOwner(player.getName()))
{
if (field.hasFlag(FieldFlag.CAN_CHANGE_OWNER))
{
if (field.isBought())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
plugin.getForceFieldManager().changeOwner(field, owner);
ChatBlock.send(sender, "fieldCanBeTaken", owner);
return true;
}
else
{
ChatBlock.send(sender, "fieldCannotChangeOwner");
}
}
else
{
ChatBlock.send(sender, "ownerCanOnlyChangeOwner");
}
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandList")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.list") && hasplayer)
{
if (args.length == 1)
{
if (Helper.isInteger(args[0]))
{
int chunk_radius = Integer.parseInt(args[0]);
List<Unbreakable> unbreakables = plugin.getUnbreakableManager().getUnbreakablesInArea(player, chunk_radius);
Set<Field> fields = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), chunk_radius, FieldFlag.ALL);
for (Unbreakable u : unbreakables)
{
ChatBlock.send(sender, "{aqua}{unbreakable}", u.toString());
}
for (Field f : fields)
{
ChatBlock.send(sender, "{aqua}{field}", f.toString());
}
if (unbreakables.isEmpty() && fields.isEmpty())
{
ChatBlock.send(sender, "noPstonesFound");
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandReload")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reload"))
{
plugin.getSettingsManager().load();
plugin.getLanguageManager().load();
ChatBlock.send(sender, "configReloaded");
return true;
}
else if (cmd.equals(ChatBlock.format("commandBuy")))
{
if (plugin.getSettingsManager().isCommandsToRentBuy())
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.BUYABLE);
if (field != null)
{
FieldSign s = field.getAttachedFieldSign();
if (s.isBuyable())
{
if (field.hasPendingPurchase())
{
ChatBlock.send(player, "fieldSignAlreadyBought");
}
else if (field.buy(player, s))
{
s.setBoughtColor(player);
PreciousStones.getInstance().getForceFieldManager().addAllowed(field, player.getName());
ChatBlock.send(player, "fieldSignBoughtAndAllowed");
}
return true;
}
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRent")))
{
if (plugin.getSettingsManager().isCommandsToRentBuy())
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.SHAREABLE);
if (field == null)
{
field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.RENTABLE);
}
if (field != null)
{
FieldSign s = field.getAttachedFieldSign();
if (s.isRentable())
{
if (field.isRented())
{
if (!field.isRenter(player.getName()))
{
ChatBlock.send(player, "fieldSignAlreadyRented");
plugin.getCommunicationManager().showRenterInfo(player, field);
return true;
}
else
{
if (player.isSneaking())
{
field.abandonRent(player);
ChatBlock.send(player, "fieldSignRentAbandoned");
return true;
}
}
}
}
if (field.rent(player, s))
{
if (s.isRentable())
{
s.setRentedColor();
}
else if (s.isShareable())
{
s.setSharedColor();
}
return true;
}
}
}
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.rent"))
{
if (args.length > 0)
{
String sub = args[0];
if (sub.equalsIgnoreCase(ChatBlock.format("commandRentClear")))
{
Field field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.RENTABLE);
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.SHAREABLE);
}
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.BUYABLE);
}
if (field != null)
{
if (field.clearRents())
{
ChatBlock.send(sender, "rentsCleared");
}
else
{
ChatBlock.send(sender, "rentsClearedNone");
}
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
if (sub.equalsIgnoreCase(ChatBlock.format("commandRentRemove")))
{
Field field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.RENTABLE);
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.SHAREABLE);
}
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.BUYABLE);
}
if (field != null)
{
if (field.removeRents())
{
ChatBlock.send(sender, "rentsRemoved");
}
else
{
ChatBlock.send(sender, "rentsRemovedNone");
}
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandFields")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.fields"))
{
plugin.getCommunicationManager().showConfiguredFields(sender);
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.enableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().enableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagEnabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDisableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.disableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().disableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagDisabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandClean")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.clean"))
{
if (args.length == 1)
{
String worldName = args[0];
World world = Bukkit.getServer().getWorld(worldName);
if (world != null)
{
int cleanedFF = plugin.getForceFieldManager().cleanOrphans(world);
int cleanedU = plugin.getUnbreakableManager().cleanOrphans(world);
if (cleanedFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
else
{
ChatBlock.send(sender, "worldNotFound");
}
}
else
{
List<World> worlds = plugin.getServer().getWorlds();
int cleanedFF = 0;
int cleanedU = 0;
for (World world : worlds)
{
cleanedFF += plugin.getForceFieldManager().cleanOrphans(world);
cleanedU += plugin.getUnbreakableManager().cleanOrphans(world);
}
if (cleanedFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandRevert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.revert"))
{
if (args.length == 1)
{
String worldName = args[0];
World world = Bukkit.getServer().getWorld(worldName);
if (world != null)
{
int cleanedFF = plugin.getForceFieldManager().revertOrphans(world);
int cleanedU = plugin.getUnbreakableManager().revertOrphans(world);
if (cleanedFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
else
{
ChatBlock.send(sender, "worldNotFound");
}
}
else
{
List<World> worlds = plugin.getServer().getWorlds();
int cleanedFF = 0;
int cleanedU = 0;
for (World world : worlds)
{
cleanedFF += plugin.getForceFieldManager().revertOrphans(world);
cleanedU += plugin.getUnbreakableManager().revertOrphans(world);
}
if (cleanedFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandBypass")) && plugin.getPermissionsManager().has(player, "preciousstones.bypass.toggle"))
{
PlayerEntry entry = plugin.getPlayerManager().getPlayerEntry(player.getName());
if (args.length == 1)
{
String mode = args[0];
if (mode.equals(ChatBlock.format("commandOn")))
{
entry.setBypassDisabled(false);
ChatBlock.send(player, "bypassEnabled");
}
else if (mode.equals(ChatBlock.format("commandOff")))
{
entry.setBypassDisabled(true);
ChatBlock.send(player, "bypassDisabled");
}
}
else
{
if (entry.isBypassDisabled())
{
entry.setBypassDisabled(false);
ChatBlock.send(player, "bypassEnabled");
}
else
{
entry.setBypassDisabled(true);
ChatBlock.send(player, "bypassDisabled");
}
}
plugin.getStorageManager().offerPlayer(player.getName());
return true;
}
else if (cmd.equals(ChatBlock.format("commandHide")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.hide"))
{
if (args.length == 1)
{
if (args[0].equals(ChatBlock.format("commandAll")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.hideall"))
{
int count = plugin.getForceFieldManager().hideBelonging(player.getName());
if (count > 0)
{
ChatBlock.send(sender, "hideHideAll", count);
}
}
}
else
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.HIDABLE))
{
if (!field.isHidden())
{
if (!field.matchesBlockType())
{
ChatBlock.send(sender, "cannotHideOrphan");
return true;
}
field.hide();
ChatBlock.send(sender, "hideHide");
}
else
{
ChatBlock.send(sender, "hideHiddenAlready");
}
}
else
{
ChatBlock.send(sender, "hideCannot");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandUnhide")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.hide"))
{
if (args.length == 1)
{
if (args[0].equals(ChatBlock.format("commandAll")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.hideall"))
{
int count = plugin.getForceFieldManager().unhideBelonging(player.getName());
if (count > 0)
{
ChatBlock.send(sender, "hideUnhideAll", count);
}
}
}
else
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.HIDABLE))
{
if (field.isHidden())
{
field.unHide();
ChatBlock.send(sender, "hideUnhide");
}
else
{
ChatBlock.send(sender, "hideUnHiddenAlready");
}
}
else
{
ChatBlock.send(sender, "hideCannot");
}
}
else
{
ChatBlock.send(sender, "hideNoneFound");
}
}
return true;
}
ChatBlock.send(sender, "notValidCommand");
return true;
}
// show the player menu
plugin.getCommunicationManager().showMenu(player);
return true;
}
}
catch (Exception ex)
{
System.out.print("Error: " + ex.getMessage());
for (StackTraceElement el : ex.getStackTrace())
{
System.out.print(el.toString());
}
}
return false;
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args)
{
try
{
if (command.getName().equals("ps"))
{
Player player = null;
if (sender instanceof Player)
{
player = (Player) sender;
}
boolean hasplayer = player != null;
if (hasplayer)
{
if (plugin.getSettingsManager().isBlacklistedWorld(player.getWorld()))
{
ChatBlock.send(player, "psDisabled");
return true;
}
}
if (args.length > 0)
{
String cmd = args[0];
args = Helper.removeFirst(args);
Block block = hasplayer ? player.getWorld().getBlockAt(player.getLocation().getBlockX(), player.getLocation().getBlockY(), player.getLocation().getBlockZ()) : null;
if (cmd.equals(ChatBlock.format("commandDebug")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.debug"))
{
plugin.getSettingsManager().setDebug(!plugin.getSettingsManager().isDebug());
if (plugin.getSettingsManager().isDebug())
{
ChatBlock.send(sender, "debugEnabled");
}
else
{
ChatBlock.send(sender, "debugDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOn")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(false);
ChatBlock.send(sender, "placingEnabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyEnabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandOff")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.onoff") && hasplayer)
{
boolean isDisabled = hasplayer && plugin.getPlayerManager().getPlayerEntry(player.getName()).isDisabled();
if (!isDisabled)
{
plugin.getPlayerManager().getPlayerEntry(player.getName()).setDisabled(true);
ChatBlock.send(sender, "placingDisabled");
}
else
{
ChatBlock.send(sender, "placingAlreadyDisabled");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandAllow")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allow") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.no-allowing"))
{
if (field.hasFlag(FieldFlag.NO_ALLOWING))
{
ChatBlock.send(sender, "noSharing");
return true;
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
Player allowed = Bukkit.getServer().getPlayerExact(playerName);
// only those with permission can be allowed
if (!field.getSettings().getRequiredPermissionAllow().isEmpty())
{
if (!plugin.getPermissionsManager().has(allowed, field.getSettings().getRequiredPermissionAllow()))
{
ChatBlock.send(sender, "noPermsForAllow", playerName);
continue;
}
}
boolean done = plugin.getForceFieldManager().addAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "hasBeenAllowed", playerName);
}
else
{
ChatBlock.send(sender, "alreadyAllowed", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().allowAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "hasBeenAllowedIn", playerName, count);
}
else
{
ChatBlock.send(sender, "isAlreadyAllowedOnAll", playerName);
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.remove") && hasplayer)
{
if (args.length >= 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
for (String playerName : args)
{
if (field.containsPlayer(playerName))
{
ChatBlock.send(sender, "cannotRemovePlayerInField");
return true;
}
if (plugin.getForceFieldManager().conflictOfInterestExists(field, playerName))
{
ChatBlock.send(sender, "cannotDisallowWhenOverlap", playerName);
return true;
}
boolean done = plugin.getForceFieldManager().removeAllowed(field, playerName);
if (done)
{
ChatBlock.send(sender, "removedFromField", playerName);
}
else
{
ChatBlock.send(sender, "playerNotFound", playerName);
}
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRemoveall")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.removeall") && hasplayer)
{
if (args.length >= 1)
{
for (String playerName : args)
{
int count = plugin.getForceFieldManager().removeAll(player, playerName);
if (count > 0)
{
ChatBlock.send(sender, "removedFromFields", playerName, count);
}
else
{
ChatBlock.send(sender, "nothingToBeDone");
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandAllowed")) && plugin.getPermissionsManager().has(player, "preciousstones.whitelist.allowed") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
List<String> allowed = field.getAllAllowed();
if (allowed.size() > 0)
{
ChatBlock.send(sender, "allowedList", Helper.toMessage(new ArrayList<String>(allowed), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersAllowedOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandCuboid")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.create.forcefield") && hasplayer)
{
if (args.length >= 1)
{
if ((args[0]).equals("commandCuboidOpen"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.CUBOID);
if (field != null)
{
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
plugin.getCuboidManager().openCuboid(player, field);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else if ((args[0]).equals("commandCuboidClose"))
{
plugin.getCuboidManager().closeCuboid(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandWho")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.who") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
HashSet<String> inhabitants = plugin.getForceFieldManager().getWho(player, field);
if (inhabitants.size() > 0)
{
ChatBlock.send(sender, "inhabitantsList", Helper.toMessage(new ArrayList<String>(inhabitants), ", "));
}
else
{
ChatBlock.send(sender, "noPlayersFoundOnField");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetname")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setname") && hasplayer)
{
String fieldName = null;
if (args.length >= 1)
{
fieldName = Helper.toMessage(args);
}
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
// if switching from an existing translocation
// end the previous one correctly by making sure
// to wipe out all applied blocks from the database
if (field.isNamed())
{
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
}
// check if one exists with that name already
if (plugin.getStorageManager().existsFieldWithName(fieldName, player.getName()))
{
ChatBlock.send(sender, "translocationExists");
return true;
}
// if this is a new translocation name, create its head record
// this will cement the size of the cuboid
if (!plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
plugin.getStorageManager().insertTranslocationHead(field, fieldName);
}
// updates the size of the field
plugin.getStorageManager().changeSizeTranslocatiorField(field, fieldName);
// always start off in applied (recording) mode
if (plugin.getStorageManager().existsTranslocationDataWithName(fieldName, field.getOwner()))
{
field.setDisabled(true, player);
field.dirtyFlags();
}
else
{
boolean disabled = field.setDisabled(false, player);
if (!disabled)
{
ChatBlock.send(player, "cannotEnable");
return true;
}
field.dirtyFlags();
}
}
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (fieldName == null)
{
boolean done = plugin.getForceFieldManager().setNameField(field, "");
if (done)
{
ChatBlock.send(sender, "fieldNameCleared");
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
else
{
boolean done = plugin.getForceFieldManager().setNameField(field, fieldName);
if (done)
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
int count = plugin.getStorageManager().unappliedTranslocationCount(field);
if (count > 0)
{
ChatBlock.send(sender, "translocationHasBlocks", fieldName, count);
}
else
{
ChatBlock.send(sender, "translocationCreated", fieldName);
}
}
else
{
ChatBlock.send(sender, "translocationRenamed", fieldName);
}
}
else
{
ChatBlock.send(sender, "noNameableFieldFound");
}
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetradius")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setradius") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
FieldSettings fs = field.getSettings();
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
if (plugin.getStorageManager().existsTranslocatior(field.getName(), field.getOwner()))
{
ChatBlock.send(player, "translocationCannotReshape");
return true;
}
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (!field.hasFlag(FieldFlag.CUBOID))
{
if (radius >= 0 && (radius <= fs.getRadius() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.setradius")))
{
plugin.getForceFieldManager().removeSourceField(field);
field.setRadius(radius);
plugin.getStorageManager().offerField(field);
plugin.getForceFieldManager().addSourceField(field);
ChatBlock.send(sender, "radiusSet", radius);
}
else
{
ChatBlock.send(sender, "radiusMustBeLessThan", fs.getRadius());
}
}
else
{
ChatBlock.send(sender, "cuboidCannotChangeRadius");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetvelocity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setvelocity") && hasplayer)
{
if (args.length == 1 && Helper.isFloat(args[0]))
{
float velocity = Float.parseFloat(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
FieldSettings fs = field.getSettings();
if (fs.hasVeocityFlag())
{
if (velocity < 0 || velocity > 5)
{
ChatBlock.send(sender, "velocityMustBe");
return true;
}
field.setVelocity(velocity);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "velocitySetTo", velocity);
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandDisable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.disable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.isDisabled())
{
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().clearTranslocation(field);
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotDisable");
return true;
}
field.setDisabled(true, player);
field.dirtyFlags();
ChatBlock.send(sender, "fieldDisabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyDisabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnable")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.enable") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.isDisabled())
{
// update translocation
if (field.hasFlag(FieldFlag.TRANSLOCATION))
{
if (field.isNamed())
{
plugin.getTranslocationManager().applyTranslocation(field);
}
}
boolean disabled = field.setDisabled(false, player);
if (!disabled)
{
ChatBlock.send(sender, "cannotEnable");
return true;
}
field.dirtyFlags();
ChatBlock.send(sender, "fieldEnabled");
}
else
{
ChatBlock.send(sender, "fieldAlreadyEnabled");
}
return true;
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDensity")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.density") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int density = Integer.parseInt(args[0]);
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
data.setDensity(density);
plugin.getStorageManager().offerPlayer(player.getName());
ChatBlock.send(sender, "visualizationChanged", density);
return true;
}
else if (args.length == 0)
{
PlayerEntry data = plugin.getPlayerManager().getPlayerEntry(player.getName());
ChatBlock.send(sender, "visualizationSet", data.getDensity());
}
}
else if (cmd.equals(ChatBlock.format("commandToggle")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.toggle") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!plugin.getPermissionsManager().has(player, "preciousstones.bypass.on-disabled"))
{
if (field.hasFlag(FieldFlag.TOGGLE_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "flagsToggledWhileDisabled");
return true;
}
}
}
if (field.isRented())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
if (field.hasFlag(flagStr) || field.hasDisabledFlag(flagStr))
{
boolean unToggable = false;
if (field.hasFlag(FieldFlag.DYNMAP_NO_TOGGLE))
{
if (flagStr.equalsIgnoreCase("dynmap-area"))
{
unToggable = true;
}
if (flagStr.equalsIgnoreCase("dynmap-marker"))
{
unToggable = true;
}
}
try
{
if (FieldFlag.getByString(flagStr).isUnToggable())
{
unToggable = true;
}
}
catch (Exception ex)
{
ChatBlock.send(sender, "flagNotFound");
return true;
}
if (unToggable)
{
ChatBlock.send(sender, "flagCannottoggle");
return true;
}
boolean enabled = field.toggleFieldFlag(flagStr);
if (enabled)
{
ChatBlock.send(sender, "flagEnabled", flagStr);
}
else
{
ChatBlock.send(sender, "flagDisabled", flagStr);
}
plugin.getStorageManager().offerField(field);
}
else
{
ChatBlock.send(sender, "flagNotFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if ((cmd.equals(ChatBlock.format("commandVisualize")) || cmd.equals("visualise")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.benefit.visualize"))
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int radius = Math.min(Integer.parseInt(args[0]), plugin.getServer().getViewDistance());
Set<Field> fieldsInArea;
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.visualize"))
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL);
}
else
{
fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), radius / 16, FieldFlag.ALL, player);
}
if (fieldsInArea != null && fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "visualizing");
int count = 0;
for (Field f : fieldsInArea)
{
if (count++ >= plugin.getSettingsManager().getVisualizeMaxFields())
{
continue;
}
plugin.getVisualizationManager().addVisualizationField(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, true);
return true;
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
ChatBlock.send(sender, "visualizing");
plugin.getVisualizationManager().addVisualizationField(player, field);
plugin.getVisualizationManager().displayVisualization(player, true);
}
else
{
ChatBlock.send(sender, "notInsideField");
}
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "visualizationNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandMark")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.mark") && hasplayer)
{
if (!plugin.getCuboidManager().hasOpenCuboid(player))
{
if (!plugin.getVisualizationManager().pendingVisualization(player))
{
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.mark"))
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
ChatBlock.send(sender, "markingFields", fieldsInArea.size());
for (Field f : fieldsInArea)
{
plugin.getVisualizationManager().addFieldMark(player, f);
}
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
Set<Field> fieldsInArea = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), plugin.getServer().getViewDistance(), FieldFlag.ALL);
if (fieldsInArea.size() > 0)
{
int count = 0;
for (Field f : fieldsInArea)
{
if (plugin.getForceFieldManager().isAllowed(f, player.getName()))
{
count++;
plugin.getVisualizationManager().addFieldMark(player, f);
}
}
if (count > 0)
{
ChatBlock.send(sender, "markingFields", count);
plugin.getVisualizationManager().displayVisualization(player, false);
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
else
{
ChatBlock.send(sender, "noFieldsInArea");
}
}
}
else
{
ChatBlock.send(sender, "visualizationTakingPlace");
}
}
else
{
ChatBlock.send(sender, "markingNotWhileCuboid");
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandInsert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.insert") && hasplayer)
{
if (args.length == 1)
{
String flagStr = args[0];
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (!field.hasFlag(flagStr) && !field.hasDisabledFlag(flagStr))
{
plugin.getForceFieldManager().removeSourceField(field);
if (field.insertFieldFlag(flagStr))
{
field.dirtyFlags();
ChatBlock.send(sender, "flagInserted");
}
else
{
ChatBlock.send(sender, "flagNotExists");
}
plugin.getForceFieldManager().addSourceField(field);
}
else
{
ChatBlock.send(sender, "flagExists");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandReset")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reset") && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
if (field != null)
{
field.RevertFlags();
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "flagsReverted");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetinterval")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setinterval") && hasplayer)
{
if (args.length == 1 && Helper.isInteger(args[0]))
{
int interval = Integer.parseInt(args[0]);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.GRIEF_REVERT);
if (field != null)
{
if (field.hasFlag(FieldFlag.MODIFY_ON_DISABLED))
{
if (!field.isDisabled())
{
ChatBlock.send(sender, "onlyModWhileDisabled");
return true;
}
}
if (interval >= plugin.getSettingsManager().getGriefRevertMinInterval() || plugin.getPermissionsManager().has(player, "preciousstones.bypass.interval"))
{
field.setRevertSecs(interval);
plugin.getGriefUndoManager().register(field);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "griefRevertIntervalSet", interval);
}
else
{
ChatBlock.send(sender, "minInterval", plugin.getSettingsManager().getGriefRevertMinInterval());
}
}
else
{
ChatBlock.send(sender, "notPointingAtGriefRevert");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSnitch")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.snitch") && hasplayer)
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
plugin.getCommunicationManager().showSnitchList(player, field);
}
else
{
ChatBlock.send(sender, "notPointingAtSnitch");
}
return true;
}
else if (args.length == 1)
{
if (args[0].equals(ChatBlock.format("commandSnitchClear")))
{
Field field = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.SNITCH);
if (field != null)
{
boolean cleaned = plugin.getForceFieldManager().cleanSnitchList(field);
if (cleaned)
{
ChatBlock.send(sender, "clearedSnitch");
}
else
{
ChatBlock.send(sender, "snitchEmpty");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandTranslocation")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.use") && hasplayer)
{
if (args.length == 0)
{
ChatBlock.send(sender, "translocationMenu1");
ChatBlock.send(sender, "translocationMenu2");
ChatBlock.send(sender, "translocationMenu3");
ChatBlock.send(sender, "translocationMenu4");
ChatBlock.send(sender, "translocationMenu5");
ChatBlock.send(sender, "translocationMenu6");
ChatBlock.send(sender, "translocationMenu7");
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationList")))
{
plugin.getCommunicationManager().notifyStoredTranslocations(player);
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.delete"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (args.length == 0)
{
plugin.getStorageManager().deleteTranslocation(args[1], player.getName());
ChatBlock.send(sender, "translocationDeleted", args[0]);
}
else
{
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
int count = plugin.getStorageManager().deleteBlockTypeFromTranslocation(field.getName(), player.getName(), entry);
if (count > 0)
{
ChatBlock.send(sender, "translocationDeletedBlocks", count, Helper.friendlyBlockType(Material.getMaterial(entry.getTypeId()).toString()), field.getName());
}
else
{
ChatBlock.send(sender, "noBlocksMatched", arg);
}
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationRemove")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.remove"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledFirst");
return true;
}
if (args.length > 0)
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().removeBlocks(field, player, entries);
}
}
else
{
ChatBlock.send(sender, "usageTranslocationRemove");
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationUnlink")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.unlink"))
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToUnlink");
return true;
}
int count = plugin.getStorageManager().appliedTranslocationCount(field);
if (count > 0)
{
plugin.getStorageManager().deleteAppliedTranslocation(field);
if (!plugin.getStorageManager().existsTranslocationDataWithName(field.getName(), field.getOwner()))
{
plugin.getStorageManager().deleteTranslocationHead(field.getName(), field.getOwner());
}
ChatBlock.send(player, "translocationUnlinked", field.getName(), count);
}
else
{
ChatBlock.send(sender, "translocationNothingToUnlink");
return true;
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
if (args[0].equals(ChatBlock.format("commandTranslocationImport")) && plugin.getPermissionsManager().has(player, "preciousstones.translocation.import"))
{
args = Helper.removeFirst(args);
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.TRANSLOCATION);
if (field != null)
{
if (field.isTranslocating())
{
ChatBlock.send(sender, "translocationTakingPlace");
return true;
}
if (!field.isNamed())
{
ChatBlock.send(sender, "translocationNamedFirst");
return true;
}
if (field.isDisabled())
{
ChatBlock.send(sender, "translocationEnabledToImport");
return true;
}
if (args.length == 0)
{
plugin.getTranslocationManager().importBlocks(field, player, null);
}
else
{
List<BlockTypeEntry> entries = new ArrayList<BlockTypeEntry>();
for (String arg : args)
{
BlockTypeEntry entry = Helper.toTypeEntry(arg);
if (entry == null || !entry.isValid())
{
ChatBlock.send(sender, "notValidBlockId", arg);
continue;
}
if (!field.getSettings().canTranslocate(entry))
{
ChatBlock.send(sender, "blockIsBlacklisted", arg);
continue;
}
entries.add(entry);
}
if (!entries.isEmpty())
{
plugin.getTranslocationManager().importBlocks(field, player, entries);
}
}
}
else
{
ChatBlock.send(sender, "notPointingAtTranslocation");
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandMore")) && hasplayer)
{
ChatBlock cb = plugin.getCommunicationManager().getChatBlock(player);
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
cb.sendBlock(player, plugin.getSettingsManager().getLinesPerPage());
if (cb.size() > 0)
{
ChatBlock.sendBlank(player);
ChatBlock.send(sender, "moreNextPage");
}
ChatBlock.sendBlank(player);
return true;
}
ChatBlock.send(sender, "moreNothingMore");
return true;
}
else if (cmd.equals(ChatBlock.format("commandCounts")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.counts") && hasplayer)
{
if (!plugin.getCommunicationManager().showFieldCounts(player, player.getName()))
{
ChatBlock.send(sender, "playerHasNoFields");
}
return true;
}
if (args.length == 1 && plugin.getPermissionsManager().has(player, "preciousstones.admin.counts"))
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
if (!plugin.getCommunicationManager().showCounts(sender, type))
{
ChatBlock.send(sender, "notValidFieldType");
}
}
}
else if (Helper.isString(args[0]) && hasplayer)
{
String target = args[0];
if (!plugin.getCommunicationManager().showFieldCounts(player, target))
{
ChatBlock.send(sender, "playerHasNoFields");
}
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandLocations")))
{
if (args.length == 0 && plugin.getPermissionsManager().has(player, "preciousstones.benefit.locations") && hasplayer)
{
plugin.getCommunicationManager().showFieldLocations(sender, -1, sender.getName());
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.locations"))
{
if (args.length == 1 && Helper.isString(args[0]))
{
String targetName = args[0];
plugin.getCommunicationManager().showFieldLocations(sender, -1, targetName);
}
if (args.length == 2 && Helper.isString(args[0]) && Helper.isInteger(args[1]))
{
String targetName = args[0];
int type = Integer.parseInt(args[1]);
plugin.getCommunicationManager().showFieldLocations(sender, type, targetName);
}
return true;
}
return false;
}
else if (cmd.equals(ChatBlock.format("commandInfo")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.info") && hasplayer)
{
Field pointing = plugin.getForceFieldManager().getOneAllowedField(block, player, FieldFlag.ALL);
List<Field> fields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (pointing != null && !fields.contains(pointing))
{
fields.add(pointing);
}
if (fields.size() == 1)
{
plugin.getCommunicationManager().showFieldDetails(player, fields.get(0));
}
else
{
plugin.getCommunicationManager().showFieldDetails(player, fields);
}
if (fields.isEmpty())
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDelete")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.delete"))
{
if (args.length == 0 && hasplayer)
{
List<Field> sourceFields = plugin.getForceFieldManager().getSourceFields(block.getLocation(), FieldFlag.ALL);
if (sourceFields.size() > 0)
{
int count = plugin.getForceFieldManager().deleteFields(sourceFields);
if (count > 0)
{
ChatBlock.send(sender, "protectionRemoved");
if (plugin.getSettingsManager().isLogBypassDelete())
{
PreciousStones.log("protectionRemovedFrom", count);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (args.length == 1)
{
if (Helper.isTypeEntry(args[0]))
{
BlockTypeEntry type = Helper.toTypeEntry(args[0]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deleteFieldsOfType(type);
int ubs = plugin.getUnbreakableManager().deleteUnbreakablesOfType(type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedUnbreakables", ubs, Material.getMaterial(type.getTypeId()));
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
int fields = plugin.getForceFieldManager().deleteBelonging(args[0]);
int ubs = plugin.getUnbreakableManager().deleteBelonging(args[0]);
if (fields > 0)
{
ChatBlock.send(sender, "deletedCountFields", args[0], fields);
}
if (ubs > 0)
{
ChatBlock.send(sender, "deletedCountUnbreakables", args[0], ubs);
}
if (ubs == 0 && fields == 0)
{
ChatBlock.send(sender, "playerHasNoPstones");
}
}
return true;
}
else if (args.length == 2)
{
if (Helper.isTypeEntry(args[1]))
{
String name = args[0];
BlockTypeEntry type = Helper.toTypeEntry(args[1]);
if (type != null)
{
int fields = plugin.getForceFieldManager().deletePlayerFieldsOfType(name, type);
if (fields > 0)
{
ChatBlock.send(sender, "deletedFields", fields, Material.getMaterial(type.getTypeId()));
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(sender);
}
}
else
{
ChatBlock.send(sender, "notValidBlockId", args[1]);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandBlacklisting")) && hasplayer)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (args.length == 0 || args.length > 1 || args[0].contains("/"))
{
ChatBlock.send(sender, "commandBlacklistUsage");
return true;
}
String blacklistedCommand = args[0];
if (field != null)
{
if (field.hasFlag(FieldFlag.COMMAND_BLACKLISTING))
{
if (blacklistedCommand.equalsIgnoreCase("clear"))
{
field.clearBlacklistedCommands();
ChatBlock.send(sender, "commandBlacklistCleared");
}
else
{
field.addBlacklistedCommand(blacklistedCommand);
ChatBlock.send(sender, "commandBlacklistAdded");
}
}
else
{
ChatBlock.send(sender, "noBlacklistingFieldFound");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandSetLimit")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.setlimit") && hasplayer)
{
if (args.length == 1)
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
String period = args[0];
if (!SignHelper.isValidPeriod(period))
{
ChatBlock.send(sender, "limitMalformed");
ChatBlock.send(sender, "limitMalformed2");
ChatBlock.send(sender, "limitMalformed3");
return true;
}
if (!field.hasFlag(FieldFlag.RENTABLE) && !field.hasFlag(FieldFlag.SHAREABLE))
{
ChatBlock.send(sender, "limitBadField");
return true;
}
field.setLimitSeconds(SignHelper.periodToSeconds(period));
ChatBlock.send(sender, "limitSet");
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandSetowner")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.setowner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
// transfer the count over to the new owner
plugin.getStorageManager().changeTranslocationOwner(field, owner);
plugin.getStorageManager().offerPlayer(field.getOwner());
plugin.getStorageManager().offerPlayer(owner);
// change the owner
field.setOwner(owner);
plugin.getStorageManager().offerField(field);
ChatBlock.send(sender, "ownerSetTo", owner);
return true;
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandChangeowner")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.change-owner") && hasplayer)
{
if (args.length == 1)
{
String owner = args[0];
if (owner.contains(":"))
{
ChatBlock.send(sender, "cannotAssignAsOwners");
return true;
}
TargetBlock aiming = new TargetBlock(player, 1000, 0.2, plugin.getSettingsManager().getThroughFieldsSet());
Block targetBlock = aiming.getTargetBlock();
if (targetBlock != null)
{
Field field = plugin.getForceFieldManager().getField(targetBlock);
if (field != null)
{
if (field.isOwner(player.getName()))
{
if (field.hasFlag(FieldFlag.CAN_CHANGE_OWNER))
{
if (field.isBought())
{
ChatBlock.send(player, "fieldSignCannotChange");
return true;
}
plugin.getForceFieldManager().changeOwner(field, owner);
ChatBlock.send(sender, "fieldCanBeTaken", owner);
return true;
}
else
{
ChatBlock.send(sender, "fieldCannotChangeOwner");
}
}
else
{
ChatBlock.send(sender, "ownerCanOnlyChangeOwner");
}
}
}
ChatBlock.send(sender, "notPointingAtPstone");
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandList")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.list") && hasplayer)
{
if (args.length == 1)
{
if (Helper.isInteger(args[0]))
{
int chunk_radius = Integer.parseInt(args[0]);
List<Unbreakable> unbreakables = plugin.getUnbreakableManager().getUnbreakablesInArea(player, chunk_radius);
Set<Field> fields = plugin.getForceFieldManager().getFieldsInCustomArea(player.getLocation(), chunk_radius, FieldFlag.ALL);
for (Unbreakable u : unbreakables)
{
ChatBlock.send(sender, "{aqua}{unbreakable}", u.toString());
}
for (Field f : fields)
{
ChatBlock.send(sender, "{aqua}{field}", f.toString());
}
if (unbreakables.isEmpty() && fields.isEmpty())
{
ChatBlock.send(sender, "noPstonesFound");
}
return true;
}
}
}
else if (cmd.equals(ChatBlock.format("commandReload")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.reload"))
{
plugin.getSettingsManager().load();
plugin.getLanguageManager().load();
ChatBlock.send(sender, "configReloaded");
return true;
}
else if (cmd.equals(ChatBlock.format("commandBuy")))
{
if (plugin.getSettingsManager().isCommandsToRentBuy())
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.BUYABLE);
if (field != null)
{
FieldSign s = field.getAttachedFieldSign();
if (s.isBuyable())
{
if (field.hasPendingPurchase())
{
ChatBlock.send(player, "fieldSignAlreadyBought");
}
else if (field.buy(player, s))
{
s.setBoughtColor(player);
PreciousStones.getInstance().getForceFieldManager().addAllowed(field, player.getName());
ChatBlock.send(player, "fieldSignBoughtAndAllowed");
}
return true;
}
}
}
return true;
}
}
else if (cmd.equals(ChatBlock.format("commandRent")))
{
if (plugin.getSettingsManager().isCommandsToRentBuy())
{
if (args.length == 0)
{
Field field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.SHAREABLE);
if (field == null)
{
field = plugin.getForceFieldManager().getOneNonOwnedField(block, player, FieldFlag.RENTABLE);
}
if (field != null)
{
FieldSign s = field.getAttachedFieldSign();
if (s.isRentable())
{
if (field.isRented())
{
if (!field.isRenter(player.getName()))
{
ChatBlock.send(player, "fieldSignAlreadyRented");
plugin.getCommunicationManager().showRenterInfo(player, field);
return true;
}
else
{
if (player.isSneaking())
{
field.abandonRent(player);
ChatBlock.send(player, "fieldSignRentAbandoned");
return true;
}
}
}
}
if (field.rent(player, s))
{
if (s.isRentable())
{
s.setRentedColor();
}
else if (s.isShareable())
{
s.setSharedColor();
}
return true;
}
}
}
return true;
}
if (plugin.getPermissionsManager().has(player, "preciousstones.admin.rent"))
{
if (args.length > 0)
{
String sub = args[0];
if (sub.equalsIgnoreCase(ChatBlock.format("commandRentClear")))
{
Field field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.RENTABLE);
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.SHAREABLE);
}
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.BUYABLE);
}
if (field != null)
{
if (field.clearRents())
{
ChatBlock.send(sender, "rentsCleared");
}
else
{
ChatBlock.send(sender, "rentsClearedNone");
}
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
if (sub.equalsIgnoreCase(ChatBlock.format("commandRentRemove")))
{
Field field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.RENTABLE);
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.SHAREABLE);
}
if (field != null)
{
field = plugin.getForceFieldManager().getOneField(block, player, FieldFlag.BUYABLE);
}
if (field != null)
{
if (field.removeRents())
{
ChatBlock.send(sender, "rentsRemoved");
}
else
{
ChatBlock.send(sender, "rentsRemovedNone");
}
}
else
{
ChatBlock.send(sender, "noPstonesFound");
}
}
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandFields")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.fields"))
{
plugin.getCommunicationManager().showConfiguredFields(sender);
return true;
}
else if (cmd.equals(ChatBlock.format("commandEnableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.enableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().enableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagEnabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandDisableall")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.disableall"))
{
if (args.length == 1)
{
String flagStr = args[0];
ChatBlock.send(player, "fieldsDown");
int count = plugin.getStorageManager().disableAllFlags(flagStr);
if (count == 0)
{
ChatBlock.send(player, "noFieldsFoundWithFlag");
}
else
{
ChatBlock.send(player, "flagDisabledOn", count);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandClean")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.clean"))
{
if (args.length == 1)
{
String worldName = args[0];
World world = Bukkit.getServer().getWorld(worldName);
if (world != null)
{
int cleanedFF = plugin.getForceFieldManager().cleanOrphans(world);
int cleanedU = plugin.getUnbreakableManager().cleanOrphans(world);
if (cleanedFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
else
{
ChatBlock.send(sender, "worldNotFound");
}
}
else
{
List<World> worlds = plugin.getServer().getWorlds();
int cleanedFF = 0;
int cleanedU = 0;
for (World world : worlds)
{
cleanedFF += plugin.getForceFieldManager().cleanOrphans(world);
cleanedU += plugin.getUnbreakableManager().cleanOrphans(world);
}
if (cleanedFF > 0)
{
ChatBlock.send(sender, "cleanedOrphanedFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "cleanedOrphanedUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandRevert")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.revert"))
{
if (args.length == 1)
{
String worldName = args[0];
World world = Bukkit.getServer().getWorld(worldName);
if (world != null)
{
int cleanedFF = plugin.getForceFieldManager().revertOrphans(world);
int cleanedU = plugin.getUnbreakableManager().revertOrphans(world);
if (cleanedFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
else
{
ChatBlock.send(sender, "worldNotFound");
}
}
else
{
List<World> worlds = plugin.getServer().getWorlds();
int cleanedFF = 0;
int cleanedU = 0;
for (World world : worlds)
{
cleanedFF += plugin.getForceFieldManager().revertOrphans(world);
cleanedU += plugin.getUnbreakableManager().revertOrphans(world);
}
if (cleanedFF > 0)
{
ChatBlock.send(sender, "revertedOrphanFields", cleanedFF);
}
if (cleanedU > 0)
{
ChatBlock.send(sender, "revertedOrphanUnbreakables", cleanedU);
}
if (cleanedFF == 0 && cleanedU == 0)
{
ChatBlock.send(sender, "noOrphansFound");
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandBypass")) && plugin.getPermissionsManager().has(player, "preciousstones.bypass.toggle"))
{
PlayerEntry entry = plugin.getPlayerManager().getPlayerEntry(player.getName());
if (args.length == 1)
{
String mode = args[0];
if (mode.equals(ChatBlock.format("commandOn")))
{
entry.setBypassDisabled(false);
ChatBlock.send(player, "bypassEnabled");
}
else if (mode.equals(ChatBlock.format("commandOff")))
{
entry.setBypassDisabled(true);
ChatBlock.send(player, "bypassDisabled");
}
}
else
{
if (entry.isBypassDisabled())
{
entry.setBypassDisabled(false);
ChatBlock.send(player, "bypassEnabled");
}
else
{
entry.setBypassDisabled(true);
ChatBlock.send(player, "bypassDisabled");
}
}
plugin.getStorageManager().offerPlayer(player.getName());
return true;
}
else if (cmd.equals(ChatBlock.format("commandHide")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.hide"))
{
if (args.length == 1)
{
if (args[0].equals(ChatBlock.format("commandAll")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.hideall"))
{
int count = plugin.getForceFieldManager().hideBelonging(player.getName());
if (count > 0)
{
ChatBlock.send(sender, "hideHideAll", count);
}
}
}
else
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.HIDABLE))
{
if (!field.isHidden())
{
if (!field.matchesBlockType())
{
ChatBlock.send(sender, "cannotHideOrphan");
return true;
}
field.hide();
ChatBlock.send(sender, "hideHide");
}
else
{
ChatBlock.send(sender, "hideHiddenAlready");
}
}
else
{
ChatBlock.send(sender, "hideCannot");
}
}
else
{
plugin.getCommunicationManager().showNotFound(player);
}
}
return true;
}
else if (cmd.equals(ChatBlock.format("commandUnhide")) && plugin.getPermissionsManager().has(player, "preciousstones.benefit.hide"))
{
if (args.length == 1)
{
if (args[0].equals(ChatBlock.format("commandAll")) && plugin.getPermissionsManager().has(player, "preciousstones.admin.hideall"))
{
int count = plugin.getForceFieldManager().unhideBelonging(player.getName());
if (count > 0)
{
ChatBlock.send(sender, "hideUnhideAll", count);
}
}
}
else
{
Field field = plugin.getForceFieldManager().getOneOwnedField(block, player, FieldFlag.ALL);
if (field != null)
{
if (field.hasFlag(FieldFlag.HIDABLE))
{
if (field.isHidden())
{
field.unHide();
ChatBlock.send(sender, "hideUnhide");
}
else
{
ChatBlock.send(sender, "hideUnHiddenAlready");
}
}
else
{
ChatBlock.send(sender, "hideCannot");
}
}
else
{
ChatBlock.send(sender, "hideNoneFound");
}
}
return true;
}
ChatBlock.send(sender, "notValidCommand");
return true;
}
// show the player menu
plugin.getCommunicationManager().showMenu(player);
return true;
}
}
catch (Exception ex)
{
System.out.print("Error: " + ex.getMessage());
for (StackTraceElement el : ex.getStackTrace())
{
System.out.print(el.toString());
}
}
return false;
}
|
diff --git a/trunk/java/src/com/tightvnc/rfbplayer/RfbPlayer.java b/trunk/java/src/com/tightvnc/rfbplayer/RfbPlayer.java
index 0a7838c1..7d643484 100644
--- a/trunk/java/src/com/tightvnc/rfbplayer/RfbPlayer.java
+++ b/trunk/java/src/com/tightvnc/rfbplayer/RfbPlayer.java
@@ -1,382 +1,383 @@
//
// Copyright (C) 2001,2002 HorizonLive.com, Inc. All Rights Reserved.
// Copyright (C) 1999 AT&T Laboratories Cambridge. All Rights Reserved.
//
// This 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 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 General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with this software; if not, write to the Free Software
// Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA 02111-1307,
// USA.
//
import java.awt.*;
import java.awt.event.*;
import java.io.*;
import java.net.*;
public class RfbPlayer extends java.applet.Applet
implements java.lang.Runnable, WindowListener {
boolean inAnApplet = true;
boolean inSeparateFrame = false;
//
// main() is called when run as a java program from the command line.
// It simply runs the applet inside a newly-created frame.
//
public static void main(String[] argv) {
RfbPlayer p = new RfbPlayer();
p.mainArgs = argv;
p.inAnApplet = false;
p.inSeparateFrame = true;
p.init();
p.start();
}
String[] mainArgs;
RfbProto rfb;
Thread rfbThread;
Frame vncFrame;
Container vncContainer;
ScrollPane desktopScrollPane;
GridBagLayout gridbag;
ButtonPanel buttonPanel;
VncCanvas vc;
String sessionURL;
URL url;
long initialTimeOffset;
double playbackSpeed;
boolean autoPlay;
boolean showControls;
int deferScreenUpdates;
//
// init()
//
public void init() {
readParameters();
if (inSeparateFrame) {
vncFrame = new Frame("RFB Session Player");
if (!inAnApplet) {
vncFrame.add("Center", this);
}
vncContainer = vncFrame;
} else {
vncContainer = this;
}
if (inSeparateFrame)
vncFrame.addWindowListener(this);
rfbThread = new Thread(this);
rfbThread.start();
}
public void update(Graphics g) {
}
//
// run() - executed by the rfbThread to read RFB data.
//
public void run() {
gridbag = new GridBagLayout();
vncContainer.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.NORTHWEST;
if (showControls) {
buttonPanel = new ButtonPanel(this);
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
gridbag.setConstraints(buttonPanel, gbc);
vncContainer.add(buttonPanel);
}
if (inSeparateFrame) {
vncFrame.pack();
vncFrame.show();
} else {
validate();
}
try {
if (inAnApplet) {
url = new URL(getCodeBase(), sessionURL);
} else {
url = new URL(sessionURL);
}
rfb = new RfbProto(url);
vc = new VncCanvas(this);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
if (inSeparateFrame) {
// Create a panel which itself is resizeable and can hold
// non-resizeable VncCanvas component at the top left corner.
Panel canvasPanel = new Panel();
canvasPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
canvasPanel.add(vc);
// Create a ScrollPane which will hold a panel with VncCanvas
// inside.
desktopScrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
gbc.fill = GridBagConstraints.BOTH;
gridbag.setConstraints(desktopScrollPane, gbc);
desktopScrollPane.add(canvasPanel);
// Finally, add our ScrollPane to the Frame window.
vncFrame.add(desktopScrollPane);
vncFrame.setTitle(rfb.desktopName);
vncFrame.pack();
vc.resizeDesktopFrame();
} else {
// Just add the VncCanvas component to the Applet.
gridbag.setConstraints(vc, gbc);
add(vc);
validate();
}
while (true) {
try {
setPaused(!autoPlay);
rfb.fbs.setSpeed(playbackSpeed);
if (initialTimeOffset > rfb.fbs.getTimeOffset())
setPos(initialTimeOffset); // don't seek backwards here
vc.processNormalProtocol();
} catch (EOFException e) {
if (e.getMessage() != null && e.getMessage().equals("[REWIND]")) {
// A special type of EOFException allowing us to seek backwards.
initialTimeOffset = rfb.fbs.getSeekOffset();
autoPlay = !rfb.fbs.isPaused();
rfb.newSession(url);
} else {
// Return to the beginning after the playback is finished.
initialTimeOffset = 0;
autoPlay = false;
rfb.newSession(url);
+ vc.updateFramebufferSize();
}
}
}
} catch (FileNotFoundException e) {
fatalError(e.toString());
} catch (Exception e) {
e.printStackTrace();
fatalError(e.toString());
}
}
public void setPaused(boolean paused) {
if (showControls)
buttonPanel.setPaused(paused);
if (paused) {
rfb.fbs.pausePlayback();
} else {
rfb.fbs.resumePlayback();
}
}
public double getSpeed() {
return playbackSpeed;
}
public void setSpeed(double speed) {
playbackSpeed = speed;
rfb.fbs.setSpeed(speed);
}
public void setPos(long pos) {
rfb.fbs.setTimeOffset(pos);
}
public void updatePos() {
if (showControls)
buttonPanel.setPos(rfb.fbs.getTimeOffset());
}
//
// readParameters() - read parameters from the html source or from the
// command line. On the command line, the arguments are just a sequence of
// param_name/param_value pairs where the names and values correspond to
// those expected in the html applet tag source.
//
public void readParameters() {
sessionURL = readParameter("URL", true);
initialTimeOffset = readLongParameter("Position", 0);
if (initialTimeOffset < 0)
initialTimeOffset = 0;
playbackSpeed = readDoubleParameter("Speed", 1.0);
if (playbackSpeed <= 0.0)
playbackSpeed = 1.0;
autoPlay = false;
String str = readParameter("Autoplay", false);
if (str != null && str.equalsIgnoreCase("Yes"))
autoPlay = true;
showControls = true;
str = readParameter("Show Controls", false);
if (str != null && str.equalsIgnoreCase("No"))
showControls = false;
if (inAnApplet) {
str = readParameter("Open New Window", false);
if (str != null && str.equalsIgnoreCase("Yes"))
inSeparateFrame = true;
}
// Fine tuning options.
deferScreenUpdates = (int)readLongParameter("Defer screen updates", 20);
if (deferScreenUpdates < 0)
deferScreenUpdates = 0; // Just in case.
}
public String readParameter(String name, boolean required) {
if (inAnApplet) {
String s = getParameter(name);
if ((s == null) && required) {
fatalError(name + " parameter not specified");
}
return s;
}
for (int i = 0; i < mainArgs.length; i += 2) {
if (mainArgs[i].equalsIgnoreCase(name)) {
try {
return mainArgs[i+1];
} catch (Exception e) {
if (required) {
fatalError(name + " parameter not specified");
}
return null;
}
}
}
if (required) {
fatalError(name + " parameter not specified");
}
return null;
}
long readLongParameter(String name, long defaultValue) {
String str = readParameter(name, false);
long result = defaultValue;
if (str != null) {
try {
result = Long.parseLong(str);
} catch (NumberFormatException e) { }
}
return result;
}
double readDoubleParameter(String name, double defaultValue) {
String str = readParameter(name, false);
double result = defaultValue;
if (str != null) {
try {
result = Double.valueOf(str).doubleValue();
} catch (NumberFormatException e) { }
}
return result;
}
//
// fatalError() - print out a fatal error message.
//
public void fatalError(String str) {
System.out.println(str);
if (inAnApplet) {
vncContainer.removeAll();
if (rfb != null) {
rfb = null;
}
Label errLabel = new Label(str);
errLabel.setFont(new Font("Helvetica", Font.PLAIN, 12));
vncContainer.setLayout(new FlowLayout(FlowLayout.LEFT, 30, 30));
vncContainer.add(errLabel);
if (inSeparateFrame) {
vncFrame.pack();
} else {
validate();
}
Thread.currentThread().stop();
} else {
System.exit(1);
}
}
//
// This method is called before the applet is destroyed.
//
public void destroy() {
vncContainer.removeAll();
if (rfb != null) {
rfb = null;
}
if (inSeparateFrame) {
vncFrame.dispose();
}
}
//
// Close application properly on window close event.
//
public void windowClosing(WindowEvent evt) {
vncContainer.removeAll();
if (rfb != null)
rfb = null;
vncFrame.dispose();
if (!inAnApplet) {
System.exit(0);
}
}
//
// Ignore window events we're not interested in.
//
public void windowActivated (WindowEvent evt) {}
public void windowDeactivated (WindowEvent evt) {}
public void windowOpened(WindowEvent evt) {}
public void windowClosed(WindowEvent evt) {}
public void windowIconified(WindowEvent evt) {}
public void windowDeiconified(WindowEvent evt) {}
}
| true | true | public void run() {
gridbag = new GridBagLayout();
vncContainer.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.NORTHWEST;
if (showControls) {
buttonPanel = new ButtonPanel(this);
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
gridbag.setConstraints(buttonPanel, gbc);
vncContainer.add(buttonPanel);
}
if (inSeparateFrame) {
vncFrame.pack();
vncFrame.show();
} else {
validate();
}
try {
if (inAnApplet) {
url = new URL(getCodeBase(), sessionURL);
} else {
url = new URL(sessionURL);
}
rfb = new RfbProto(url);
vc = new VncCanvas(this);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
if (inSeparateFrame) {
// Create a panel which itself is resizeable and can hold
// non-resizeable VncCanvas component at the top left corner.
Panel canvasPanel = new Panel();
canvasPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
canvasPanel.add(vc);
// Create a ScrollPane which will hold a panel with VncCanvas
// inside.
desktopScrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
gbc.fill = GridBagConstraints.BOTH;
gridbag.setConstraints(desktopScrollPane, gbc);
desktopScrollPane.add(canvasPanel);
// Finally, add our ScrollPane to the Frame window.
vncFrame.add(desktopScrollPane);
vncFrame.setTitle(rfb.desktopName);
vncFrame.pack();
vc.resizeDesktopFrame();
} else {
// Just add the VncCanvas component to the Applet.
gridbag.setConstraints(vc, gbc);
add(vc);
validate();
}
while (true) {
try {
setPaused(!autoPlay);
rfb.fbs.setSpeed(playbackSpeed);
if (initialTimeOffset > rfb.fbs.getTimeOffset())
setPos(initialTimeOffset); // don't seek backwards here
vc.processNormalProtocol();
} catch (EOFException e) {
if (e.getMessage() != null && e.getMessage().equals("[REWIND]")) {
// A special type of EOFException allowing us to seek backwards.
initialTimeOffset = rfb.fbs.getSeekOffset();
autoPlay = !rfb.fbs.isPaused();
rfb.newSession(url);
} else {
// Return to the beginning after the playback is finished.
initialTimeOffset = 0;
autoPlay = false;
rfb.newSession(url);
}
}
}
} catch (FileNotFoundException e) {
fatalError(e.toString());
} catch (Exception e) {
e.printStackTrace();
fatalError(e.toString());
}
}
| public void run() {
gridbag = new GridBagLayout();
vncContainer.setLayout(gridbag);
GridBagConstraints gbc = new GridBagConstraints();
gbc.gridwidth = GridBagConstraints.REMAINDER;
gbc.anchor = GridBagConstraints.NORTHWEST;
if (showControls) {
buttonPanel = new ButtonPanel(this);
buttonPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
gridbag.setConstraints(buttonPanel, gbc);
vncContainer.add(buttonPanel);
}
if (inSeparateFrame) {
vncFrame.pack();
vncFrame.show();
} else {
validate();
}
try {
if (inAnApplet) {
url = new URL(getCodeBase(), sessionURL);
} else {
url = new URL(sessionURL);
}
rfb = new RfbProto(url);
vc = new VncCanvas(this);
gbc.weightx = 1.0;
gbc.weighty = 1.0;
if (inSeparateFrame) {
// Create a panel which itself is resizeable and can hold
// non-resizeable VncCanvas component at the top left corner.
Panel canvasPanel = new Panel();
canvasPanel.setLayout(new FlowLayout(FlowLayout.LEFT, 0, 0));
canvasPanel.add(vc);
// Create a ScrollPane which will hold a panel with VncCanvas
// inside.
desktopScrollPane = new ScrollPane(ScrollPane.SCROLLBARS_AS_NEEDED);
gbc.fill = GridBagConstraints.BOTH;
gridbag.setConstraints(desktopScrollPane, gbc);
desktopScrollPane.add(canvasPanel);
// Finally, add our ScrollPane to the Frame window.
vncFrame.add(desktopScrollPane);
vncFrame.setTitle(rfb.desktopName);
vncFrame.pack();
vc.resizeDesktopFrame();
} else {
// Just add the VncCanvas component to the Applet.
gridbag.setConstraints(vc, gbc);
add(vc);
validate();
}
while (true) {
try {
setPaused(!autoPlay);
rfb.fbs.setSpeed(playbackSpeed);
if (initialTimeOffset > rfb.fbs.getTimeOffset())
setPos(initialTimeOffset); // don't seek backwards here
vc.processNormalProtocol();
} catch (EOFException e) {
if (e.getMessage() != null && e.getMessage().equals("[REWIND]")) {
// A special type of EOFException allowing us to seek backwards.
initialTimeOffset = rfb.fbs.getSeekOffset();
autoPlay = !rfb.fbs.isPaused();
rfb.newSession(url);
} else {
// Return to the beginning after the playback is finished.
initialTimeOffset = 0;
autoPlay = false;
rfb.newSession(url);
vc.updateFramebufferSize();
}
}
}
} catch (FileNotFoundException e) {
fatalError(e.toString());
} catch (Exception e) {
e.printStackTrace();
fatalError(e.toString());
}
}
|
diff --git a/src/kg/apc/jmeter/charting/GraphPanelChart.java b/src/kg/apc/jmeter/charting/GraphPanelChart.java
index 7170ea66..c584d70f 100644
--- a/src/kg/apc/jmeter/charting/GraphPanelChart.java
+++ b/src/kg/apc/jmeter/charting/GraphPanelChart.java
@@ -1,1357 +1,1361 @@
package kg.apc.jmeter.charting;
import java.awt.AlphaComposite;
import java.awt.BasicStroke;
import java.awt.Color;
import java.awt.Composite;
import java.awt.Font;
import java.awt.FontMetrics;
import java.awt.GradientPaint;
import java.awt.Graphics;
import java.awt.Graphics2D;
import java.awt.Image;
import java.awt.Rectangle;
import java.awt.RenderingHints;
import java.awt.Stroke;
import java.awt.datatransfer.Clipboard;
import java.awt.datatransfer.ClipboardOwner;
import java.awt.datatransfer.DataFlavor;
import java.awt.datatransfer.Transferable;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.geom.AffineTransform;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.text.DecimalFormatSymbols;
import java.util.AbstractMap;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map.Entry;
import javax.imageio.ImageIO;
import javax.swing.BorderFactory;
import javax.swing.JComponent;
import javax.swing.JFileChooser;
import javax.swing.JMenuItem;
import javax.swing.JOptionPane;
import javax.swing.JPopupMenu;
import javax.swing.border.BevelBorder;
import javax.swing.filechooser.FileNameExtensionFilter;
import kg.apc.jmeter.vizualizers.ColorsDispatcher;
import org.apache.jmeter.util.JMeterUtils;
import org.apache.jorphan.gui.NumberRenderer;
import org.apache.jorphan.logging.LoggingManager;
import org.apache.log.Logger;
/**
*
* @author apc
*/
public class GraphPanelChart
extends JComponent
implements ClipboardOwner
{
JPopupMenu popup = new JPopupMenu();
private static final String AD_TEXT = "http://apc.kg";
private static final String NO_SAMPLES = "Waiting for samples...";
private static final int spacing = 5;
/*
* Special type of graph were minY is forced to 0 and maxY is forced to 100
* to display percentage charts (eg cpu monitoring)
*/
public static final int CHART_PERCENTAGE = 0;
public static final int CHART_DEFAULT = -1;
private static final Logger log = LoggingManager.getLoggerForClass();
private Rectangle legendRect;
private Rectangle xAxisRect;
private Rectangle yAxisRect;
private Rectangle chartRect;
private static final Rectangle zeroRect = new Rectangle();
private AbstractMap<String, AbstractGraphRow> rows;
private double maxYVal;
private double minYVal;
private long maxXVal;
private long minXVal;
private long currentXVal;
private static final int gridLinesCount = 10;
private NumberRenderer yAxisLabelRenderer;
private NumberRenderer xAxisLabelRenderer;
private boolean drawCurrentX = false;
private int forcedMinX = -1;
private int chartType = CHART_DEFAULT;
// The stroke used to paint Graph's dashed lines
private Stroke dashStroke = new BasicStroke(
1.0f, // Width
BasicStroke.CAP_SQUARE, // End cap
BasicStroke.JOIN_MITER, // Join style
10.0f, // Miter limit
new float[]
{
1.0f, 4.0f
}, // Dash pattern
0.0f); // Dash phase
// The stroke to paint thick Graph rows
private Stroke thickStroke = new BasicStroke(
AbstractGraphRow.LINE_THICKNESS_BIG,
BasicStroke.CAP_BUTT,
BasicStroke.JOIN_BEVEL);
// Message display in graphs. Used for perfmon error messages
private String errorMessage = null;
// Chart's gradient background end color
private Color gradientColor = new Color(229, 236, 246);
// Chart's Axis Color. For good results, use gradient color - (30, 30, 30)
private Color axisColor = new Color(199, 206, 216);
//the composite used to draw bars
AlphaComposite barComposite = AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.5f);
//save file path. We remember last folder used.
private static String savePath = null;
//limit the maximum number of points when drawing a line, by averaging values
//if necessary. If -1 is assigned, no limit.
private int maxPoints = -1;
private boolean preventXAxisOverScaling = false;
private boolean reSetColors = false;
public void setReSetColors(boolean reSetColors)
{
this.reSetColors = reSetColors;
}
private boolean useRelativeTime = false;
public void setUseRelativeTime(boolean isRelative)
{
this.useRelativeTime = isRelative;
}
private String xAxisLabel = "X axis label";
private String yAxisLabel = "Y axis label";
private int precisionLabel = -1;
private int factorInUse = 1;
private boolean displayPrecision = false;
public void setDisplayPrecision(boolean displayPrecision)
{
this.displayPrecision = displayPrecision;
}
public void setxAxisLabel(String xAxisLabel)
{
this.xAxisLabel = xAxisLabel;
}
public void setyAxisLabel(String yAxisLabel)
{
this.yAxisLabel = yAxisLabel;
}
public void setPrecisionLabel(int precision)
{
this.precisionLabel = precision;
}
private String getXAxisLabel()
{
String label;
if(!displayPrecision)
{
label = xAxisLabel;
} else {
if(maxPoints <= 0)
{
label = xAxisLabel + " (granularity: " + precisionLabel + " ms)";
} else {
label = xAxisLabel + " (granularity: " + precisionLabel*factorInUse + " ms)";
}
}
return label;
}
private boolean isPreview = false;
public void setIsPreview(boolean isPreview)
{
this.isPreview = isPreview;
if(!isPreview)
{
this.setComponentPopupMenu(popup);
} else {
this.setComponentPopupMenu(null);
}
}
// Default draw options - these are default values if no property is entered in user.properties
// List of possible properties (TODO: The explaination must be written in readme file)
// jmeterPlugin.drawGradient=(true/false)
// jmeterPlugin.neverDrawFinalZeroingLines=(true/false)
// jmeterPlugin.optimizeYAxis=(true/false)
// jmeterPlugin.neverDrawCurrentX=(true/false)
// note to Andrey: Feel free to decide the default value!
private static boolean drawGradient = true;
private static boolean neverDrawFinalZeroingLines = false;
private static boolean optimizeYAxis = true;
private static boolean neverDrawCurrentX = false;
private static String csvSeparator = null;
//some of these preference can be overidden by the preference tab:
private boolean settingsDrawGradient;
private boolean settingsDrawFinalZeroingLines;
private boolean settingsDrawCurrentX;
private int settingsHideNonRepValLimit = -1;
// If user entered configuration items in user.properties, overide default values.
static
{
String cfgDrawGradient = JMeterUtils.getProperty("jmeterPlugin.drawGradient");
if (cfgDrawGradient != null)
{
GraphPanelChart.drawGradient = "true".equalsIgnoreCase(cfgDrawGradient);
}
String cfgNeverDrawFinalZeroingLines = JMeterUtils.getProperty("jmeterPlugin.neverDrawFinalZeroingLines");
if (cfgNeverDrawFinalZeroingLines != null)
{
GraphPanelChart.neverDrawFinalZeroingLines = "true".equalsIgnoreCase(cfgNeverDrawFinalZeroingLines);
}
String cfgOptimizeYAxis = JMeterUtils.getProperty("jmeterPlugin.optimizeYAxis");
if (cfgOptimizeYAxis != null)
{
GraphPanelChart.optimizeYAxis = "true".equalsIgnoreCase(cfgOptimizeYAxis);
}
String cfgNeverDrawFinalCurrentX = JMeterUtils.getProperty("jmeterPlugin.neverDrawCurrentX");
if (cfgNeverDrawFinalCurrentX != null)
{
GraphPanelChart.neverDrawCurrentX = "true".equalsIgnoreCase(cfgNeverDrawFinalCurrentX);
}
String cfgCsvSeparator = JMeterUtils.getProperty("jmeterPlugin.csvSeparator");
if (cfgCsvSeparator != null)
{
GraphPanelChart.csvSeparator = cfgCsvSeparator;
} else
{
if(new DecimalFormatSymbols().getDecimalSeparator() == '.')
{
GraphPanelChart.csvSeparator = ",";
} else
{
GraphPanelChart.csvSeparator = ";";
}
}
}
//row zooming
private HashMap<String, Integer> rowsZoomFactor = new HashMap<String, Integer>();
private boolean expendRows = false;
public void setExpendRows(boolean expendRows)
{
this.expendRows = expendRows;
}
/**
* Creates new chart object with default parameters
*/
public GraphPanelChart(boolean allowCsvExport)
{
setBackground(Color.white);
setBorder(BorderFactory.createBevelBorder(BevelBorder.LOWERED, Color.lightGray, Color.darkGray));
yAxisLabelRenderer = new NumberRenderer("#.#");
xAxisLabelRenderer = new NumberRenderer("#.#");
legendRect = new Rectangle();
yAxisRect = new Rectangle();
xAxisRect = new Rectangle();
chartRect = new Rectangle();
setDefaultDimensions();
registerPopup(allowCsvExport);
settingsDrawCurrentX = !neverDrawCurrentX;
settingsDrawGradient = drawGradient;
settingsDrawFinalZeroingLines = false;
}
public GraphPanelChart()
{
this(true);
}
public void setSettingsHideNonRepValLimit(int limit)
{
this.settingsHideNonRepValLimit = limit;
}
public void setPreventXAxisOverScaling(boolean preventXAxisOverScaling)
{
this.preventXAxisOverScaling = preventXAxisOverScaling;
}
public void setSettingsDrawCurrentX(boolean settingsDrawCurrentX)
{
this.settingsDrawCurrentX = settingsDrawCurrentX;
}
public void setSettingsDrawFinalZeroingLines(boolean settingsDrawFinalZeroingLines)
{
this.settingsDrawFinalZeroingLines = settingsDrawFinalZeroingLines;
}
public void setSettingsDrawGradient(boolean settingsDrawGradient)
{
this.settingsDrawGradient = settingsDrawGradient;
}
public boolean isSettingsDrawCurrentX()
{
return settingsDrawCurrentX;
}
public boolean isSettingsDrawGradient()
{
return settingsDrawGradient;
}
public static boolean isGlobalDrawFinalZeroingLines()
{
return !neverDrawFinalZeroingLines;
}
public boolean isModelContainsRow(AbstractGraphRow row)
{
return rows.containsKey(row.getLabel());
}
public void setChartType(int type)
{
chartType = type;
}
private void drawFinalLines(AbstractGraphRow row, Graphics g, int prevX, int prevY, final double dxForDVal, Stroke oldStroke, Color color)
{
// draw final lines
if (row.isDrawLine() && settingsDrawFinalZeroingLines)
{
if (row.isDrawThickLines())
{
((Graphics2D) g).setStroke(thickStroke);
}
g.setColor(color);
g.drawLine(prevX, prevY, (int) (prevX + dxForDVal), chartRect.y + chartRect.height);
if (row.isDrawThickLines())
{
((Graphics2D) g).setStroke(oldStroke);
}
}
}
private boolean drawMessages(Graphics2D g)
{
if (errorMessage != null)
{
g.setColor(Color.RED);
g.drawString(errorMessage, getWidth() / 2 - g.getFontMetrics(g.getFont()).stringWidth(errorMessage) / 2, getHeight() / 2);
return true;
}
if (rows.isEmpty())
{
g.setColor(Color.BLACK);
g.drawString(NO_SAMPLES, getWidth() / 2 - g.getFontMetrics(g.getFont()).stringWidth(NO_SAMPLES) / 2, getHeight() / 2);
return true;
}
return false;
}
private void getMinMaxDataValues()
{
maxXVal = 0L;
maxYVal = 0L;
minXVal = Long.MAX_VALUE;
minYVal = Double.MAX_VALUE;
Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator();
Entry<String, AbstractGraphRow> row = null;
AbstractGraphRow rowValue;
int barValue = 0;
while (it.hasNext())
{
row = it.next();
rowValue = row.getValue();
if (!rowValue.isDrawOnChart())
{
continue;
}
rowValue.setExcludeOutOfRangeValues(preventXAxisOverScaling);
double[] rowMinMaxY = rowValue.getMinMaxY(maxPoints);
if (rowMinMaxY[1] > maxYVal)
{
maxYVal = rowMinMaxY[1];
}
if (rowMinMaxY[0] < minYVal)
{
//we draw only positives values
minYVal = rowMinMaxY[0] >= 0 ? rowMinMaxY[0] : 0;
}
if (rowValue.getMaxX() > maxXVal)
{
maxXVal = rowValue.getMaxX();
}
if (rowValue.getMinX() < minXVal)
{
minXVal = rowValue.getMinX();
}
if(rowValue.isDrawBar()) {
barValue = rowValue.getGranulationValue();
}
}
if (barValue > 0)
{
maxXVal += barValue;
//find nice X steps
double barPerSquare = (double) (maxXVal - minXVal) / (barValue * gridLinesCount);
double step = Math.floor(barPerSquare)+1;
maxXVal = (long) (minXVal + step * barValue * gridLinesCount);
}
//maxYVal *= 1 + (double) 1 / (double) gridLinesCount;
if (forcedMinX >= 0L)
{
minXVal = forcedMinX;
}
//prevent X axis not initialized in case of no row displayed
//we use last known row
if ((minXVal == Long.MAX_VALUE && maxXVal == 0L && row != null) ||
(forcedMinX >= 0L && maxXVal == 0L && row != null))
{
maxXVal = row.getValue().getMaxX();
if(forcedMinX >= 0L)
{
minXVal = forcedMinX;
} else
{
minXVal = row.getValue().getMinX();
}
minYVal = 0;
maxYVal = 10;
}
else if (optimizeYAxis)
{
computeChartSteps();
}
else
{
minYVal = 0;
}
}
/**
* compute minY and step value to have better readable charts
*/
private void computeChartSteps()
{
//if special type
if (chartType == GraphPanelChart.CHART_PERCENTAGE)
{
minYVal = 0;
maxYVal = 100;
return;
}
//try to find the best range...
//first, avoid special cases where maxY equal or close to minY
if (maxYVal - minYVal < 0.1)
{
maxYVal = minYVal + 1;
}
//real step
double step = (maxYVal - minYVal) / gridLinesCount;
int pow = -1;
double factor = -1;
boolean found = false;
double testStep;
double testFactor;
//find a step close to the real one
while (!found)
{
pow++;
//for small range (<10), don't use .5 factor.
//we try to find integer steps as it is more easy to read
if (pow > 0)
{
testFactor = 0.5;
}
else
{
testFactor = 1;
}
for (double f = 0; f <= 5; f = f + testFactor)
{
testStep = Math.pow(10, pow) * f;
if (testStep >= step)
{
factor = f;
found = true;
break;
}
}
}
//first proposal
double foundStep = Math.pow(10, pow) * factor;
//we shift to the closest lower minval to align with the step
minYVal = minYVal - minYVal % foundStep;
//check if step is still good with minY trimmed. If not, use next factor.
if (minYVal + foundStep * gridLinesCount < maxYVal)
{
foundStep = Math.pow(10, pow) * (factor + (pow > 0 ? 0.5 : 1));
}
//last visual optimization: find the optimal minYVal
double trim = 10;
while ((minYVal - minYVal % trim) + foundStep * gridLinesCount >= maxYVal && minYVal > 0)
{
minYVal = minYVal - minYVal % trim;
trim = trim * 10;
}
//final calculation
maxYVal = minYVal + foundStep * gridLinesCount;
}
private void setDefaultDimensions()
{
chartRect.setBounds(spacing, spacing, getWidth() - spacing * 2, getHeight() - spacing * 2);
legendRect.setBounds(zeroRect);
xAxisRect.setBounds(zeroRect);
yAxisRect.setBounds(zeroRect);
}
private void calculateYAxisDimensions(FontMetrics fm)
{
// TODO: middle value labels often wider than max
yAxisLabelRenderer.setValue(maxYVal);
int axisWidth = fm.stringWidth(yAxisLabelRenderer.getText()) + spacing * 3 + fm.getHeight();
yAxisRect.setBounds(chartRect.x, chartRect.y, axisWidth, chartRect.height);
if(!isPreview)
{
chartRect.setBounds(chartRect.x + axisWidth, chartRect.y, chartRect.width - axisWidth, chartRect.height);
}
}
private void calculateXAxisDimensions(FontMetrics fm)
{
// FIXME: first value on X axis may take negative X coord,
// we need to handle this and make Y axis wider
int axisHeight;
if(!isPreview)
{
axisHeight = 2 * fm.getHeight() + spacing;//labels plus name
} else
{
axisHeight = spacing;
}
xAxisLabelRenderer.setValue(maxXVal);
int axisEndSpace = fm.stringWidth(xAxisLabelRenderer.getText()) / 2;
xAxisRect.setBounds(chartRect.x, chartRect.y + chartRect.height - axisHeight, chartRect.width, axisHeight);
if(!isPreview)
{
chartRect.setBounds(chartRect.x, chartRect.y, chartRect.width - axisEndSpace, chartRect.height - axisHeight);
}
yAxisRect.setBounds(yAxisRect.x, yAxisRect.y, yAxisRect.width, chartRect.height);
}
@Override
public void paintComponent(Graphics g)
{
super.paintComponent(g);
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2d = image.createGraphics();
g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
drawPanel(g2d);
g.drawImage(image, 0, 0, this);
}
private void drawPanel(Graphics2D g)
{
g.setColor(Color.white);
if (settingsDrawGradient)
{
GradientPaint gdp = new GradientPaint(0, 0, Color.white, 0, getHeight(), gradientColor);
g.setPaint(gdp);
}
g.fillRect(0, 0, getWidth(), getHeight());
paintAd(g);
if (drawMessages(g))
{
return;
}
setDefaultDimensions();
getMinMaxDataValues();
//row zooming
if(expendRows)
{
Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator();
while(it.hasNext())
{
Entry<String, AbstractGraphRow> row = it.next();
double[] minMax = row.getValue().getMinMaxY(maxPoints);
if(minMax[1] > 0)
{
int zoomFactor = 1;
while(minMax[1]*zoomFactor <= maxYVal)
{
rowsZoomFactor.put(row.getKey(), zoomFactor);
zoomFactor = zoomFactor * 10;
}
} else {
rowsZoomFactor.put(row.getKey(), 1);
}
}
}
try
{
paintLegend(g);
calculateYAxisDimensions(g.getFontMetrics(g.getFont()));
calculateXAxisDimensions(g.getFontMetrics(g.getFont()));
paintYAxis(g);
paintXAxis(g);
paintChart(g);
}
catch (Exception e)
{
log.error("Error in paintComponent", e);
}
}
private void paintLegend(Graphics g)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
int rectH = fm.getHeight();
int rectW = rectH;
Iterator<Entry<String, AbstractGraphRow>> it = rows.entrySet().iterator();
Entry<String, AbstractGraphRow> row;
int currentX = chartRect.x;
int currentY = chartRect.y;
int legendHeight = it.hasNext() ? rectH + spacing : 0;
ColorsDispatcher colors = null;
if(reSetColors)
{
colors = new ColorsDispatcher();
}
while (it.hasNext())
{
row = it.next();
Color color = reSetColors ? colors.getNextColor() : row.getValue().getColor();
if (!row.getValue().isShowInLegend() || !row.getValue().isDrawOnChart())
{
continue;
}
String rowLabel = row.getKey();
if(expendRows && rowsZoomFactor.get(row.getKey()) != null)
{
int zoomFactor = rowsZoomFactor.get(row.getKey());
if(zoomFactor != 1)
{
rowLabel = rowLabel + " (x" + zoomFactor + ")";
}
}
// wrap row if overflowed
if (currentX + rectW + spacing / 2 + fm.stringWidth(rowLabel) > getWidth())
{
currentY += rectH + spacing / 2;
legendHeight += rectH + spacing / 2;
currentX = chartRect.x;
}
// draw legend color box
g.setColor(color);
Composite oldComposite = null;
if (row.getValue().isDrawBar())
{
oldComposite = ((Graphics2D) g).getComposite();
((Graphics2D) g).setComposite(barComposite);
}
g.fillRect(currentX, currentY, rectW, rectH);
if (row.getValue().isDrawBar())
{
((Graphics2D) g).setComposite(oldComposite);
}
g.setColor(Color.black);
g.drawRect(currentX, currentY, rectW, rectH);
// draw legend item label
currentX += rectW + spacing / 2;
g.drawString(rowLabel, currentX, (int) (currentY + rectH * 0.9));
currentX += fm.stringWidth(rowLabel) + spacing;
}
legendRect.setBounds(chartRect.x, chartRect.y, chartRect.width, legendHeight);
chartRect.setBounds(chartRect.x, chartRect.y + legendHeight + spacing, chartRect.width, chartRect.height - legendHeight - spacing);
}
private void paintYAxis(Graphics g)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
String valueLabel;
int labelXPos;
int gridLineY;
// shift 2nd and more lines
int shift = 0;
// for strokes swapping
Stroke oldStroke = ((Graphics2D) g).getStroke();
//draw markers
g.setColor(axisColor);
for (int n = 0; n <= gridLinesCount; n++)
{
gridLineY = chartRect.y + (int) ((gridLinesCount - n) * (double) chartRect.height / gridLinesCount);
g.drawLine(chartRect.x - 3, gridLineY, chartRect.x + 3, gridLineY);
}
for (int n = 0; n <= gridLinesCount; n++)
{
//draw 2nd and more axis dashed and shifted
if (n != 0)
{
((Graphics2D) g).setStroke(dashStroke);
shift = 7;
}
gridLineY = chartRect.y + (int) ((gridLinesCount - n) * (double) chartRect.height / gridLinesCount);
// draw grid line with tick
g.setColor(axisColor);
g.drawLine(chartRect.x + shift, gridLineY, chartRect.x + chartRect.width, gridLineY);
g.setColor(Color.black);
// draw label
if(!isPreview)
{
yAxisLabelRenderer.setValue((minYVal * gridLinesCount + n * (maxYVal - minYVal)) / gridLinesCount);
valueLabel = yAxisLabelRenderer.getText();
labelXPos = yAxisRect.x + yAxisRect.width - fm.stringWidth(valueLabel) - spacing - spacing / 2;
g.drawString(valueLabel, labelXPos, gridLineY + fm.getAscent() / 2);
}
}
if(!isPreview)
{
Font oldFont = g.getFont();
g.setFont(g.getFont().deriveFont(Font.ITALIC));
// Create a rotation transformation for the font.
AffineTransform fontAT = new AffineTransform();
int delta = g.getFontMetrics(g.getFont()).stringWidth(yAxisLabel);
fontAT.rotate(-Math.PI/2d);
g.setFont(g.getFont().deriveFont(fontAT));
g.drawString(yAxisLabel, yAxisRect.x+15, yAxisRect.y + yAxisRect.height / 2 + delta / 2);
g.setFont(oldFont);
}
//restore stroke
((Graphics2D) g).setStroke(oldStroke);
}
private void paintXAxis(Graphics g)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
String valueLabel;
int labelXPos;
int gridLineX;
// shift 2nd and more lines
int shift = 0;
// for strokes swapping
Stroke oldStroke = ((Graphics2D) g).getStroke();
g.setColor(axisColor);
//draw markers
for (int n = 0; n <= gridLinesCount; n++)
{
gridLineX = chartRect.x + (int) (n * ((double) chartRect.width / gridLinesCount));
g.drawLine(gridLineX, chartRect.y + chartRect.height - 3, gridLineX, chartRect.y + chartRect.height + 3);
}
for (int n = 0; n <= gridLinesCount; n++)
{
//draw 2nd and more axis dashed and shifted
if (n != 0)
{
((Graphics2D) g).setStroke(dashStroke);
shift = 7;
}
gridLineX = chartRect.x + (int) (n * ((double) chartRect.width / gridLinesCount));
// draw grid line with tick
g.setColor(axisColor);
g.drawLine(gridLineX, chartRect.y + chartRect.height - shift, gridLineX, chartRect.y);
g.setColor(Color.black);
// draw label
xAxisLabelRenderer.setValue(minXVal + n * (double) (maxXVal - minXVal) / gridLinesCount);
valueLabel = xAxisLabelRenderer.getText();
labelXPos = gridLineX - fm.stringWidth(valueLabel) / 2;
g.drawString(valueLabel, labelXPos, xAxisRect.y + fm.getAscent() + spacing);
}
Font oldFont = g.getFont();
g.setFont(g.getFont().deriveFont(Font.ITALIC));
//axis label
g.drawString(getXAxisLabel(), chartRect.x + chartRect.width / 2 - g.getFontMetrics(g.getFont()).stringWidth(getXAxisLabel()) / 2, xAxisRect.y + 2 * fm.getAscent() + spacing + 3);
g.setFont(oldFont);
//restore stroke
((Graphics2D) g).setStroke(oldStroke);
if (drawCurrentX && settingsDrawCurrentX)
{
gridLineX = chartRect.x + (int) ((currentXVal - minXVal) * (double) chartRect.width / (maxXVal - minXVal));
g.setColor(Color.GRAY);
g.drawLine(gridLineX, chartRect.y, gridLineX, chartRect.y + chartRect.height);
g.setColor(Color.black);
}
}
private void paintChart(Graphics g)
{
g.setColor(Color.yellow);
Iterator<Entry<String, AbstractGraphRow>> it;
ColorsDispatcher dispatcher = null;
if(reSetColors)
{
dispatcher = new ColorsDispatcher();
}
//first we get the aggregate point factor if maxpoint is > 0;
factorInUse = 1;
if (maxPoints > 0)
{
it = rows.entrySet().iterator();
while (it.hasNext())
{
Entry<String, AbstractGraphRow> row = it.next();
int rowFactor = (int)Math.floor(row.getValue().size() / maxPoints) + 1;
if(rowFactor > factorInUse) factorInUse = rowFactor;
}
}
//paint rows
it = rows.entrySet().iterator();
while (it.hasNext())
{
Entry<String, AbstractGraphRow> row = it.next();
if (row.getValue().isDrawOnChart())
{
Color color = reSetColors ? dispatcher.getNextColor() : row.getValue().getColor();
paintRow(g, row.getValue(), row.getKey(), color);
}
}
}
/*
* Check if the point (x,y) is contained in the chart area
* We check only minX, maxX, and maxY to avoid flickering.
* We take max(chartRect.y, y) as redering value
* This is done to prevent line out of range if new point is added
* during chart paint.
*/
private boolean isChartPointValid(int x, int y)
{
boolean ret = true;
//check x
if (x < chartRect.x || x > chartRect.x + chartRect.width)
{
ret = false;
}
else //check y
if (y > chartRect.y + chartRect.height || y < chartRect.y)
{
ret = false;
}
return ret;
}
public void setMaxPoints(int maxPoints)
{
this.maxPoints = maxPoints;
}
private void paintRow(Graphics g, AbstractGraphRow row, String rowLabel, Color color)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
Iterator<Entry<Long, AbstractGraphPanelChartElement>> it = row.iterator();
Entry<Long, AbstractGraphPanelChartElement> element;
int radius = row.getMarkerSize();
int x, y;
int prevX = settingsDrawFinalZeroingLines ? chartRect.x : -1;
int prevY = chartRect.y + chartRect.height;
final double dxForDVal = (maxXVal <= minXVal) ? 0 : (double) chartRect.width / (maxXVal - minXVal);
final double dyForDVal = (maxYVal <= minYVal) ? 0 : (double) chartRect.height / (maxYVal - minYVal);
Stroke oldStroke = null;
if (row.isDrawThickLines())
{
oldStroke = ((Graphics2D) g).getStroke();
}
while (it.hasNext())
{
if (!row.isDrawOnChart())
{
continue;
}
double calcPointX = 0;
double calcPointY = 0;
if (factorInUse == 1)
{
element = it.next();
AbstractGraphPanelChartElement elt = (AbstractGraphPanelChartElement) element.getValue();
//not compatible with factor != 1, ie cannot be used if limit nb of point is selected.
if (settingsHideNonRepValLimit > 0)
{
while (!elt.isPointRepresentative(settingsHideNonRepValLimit) && it.hasNext())
{
element = it.next();
elt = (AbstractGraphPanelChartElement) element.getValue();
}
if (!elt.isPointRepresentative(settingsHideNonRepValLimit))
{
break;
}
}
calcPointX = element.getKey().doubleValue();
calcPointY = elt.getValue();
} else
{
int nbPointProcessed = 0;
for (int i = 0; i < factorInUse; i++)
{
if (it.hasNext())
{
element = it.next();
calcPointX = calcPointX + element.getKey().doubleValue();
calcPointY = calcPointY + ((AbstractGraphPanelChartElement) element.getValue()).getValue();
nbPointProcessed++;
}
}
calcPointX = calcPointX / (double)nbPointProcessed;
calcPointY = calcPointY / (double)factorInUse;
}
if(expendRows)
{
calcPointY = calcPointY * rowsZoomFactor.get(rowLabel);
}
x = chartRect.x + (int) ((calcPointX - minXVal) * dxForDVal);
int yHeight = (int) ((calcPointY - minYVal) * dyForDVal);
y = chartRect.y + chartRect.height - yHeight;
//fix flickering
if( y < chartRect.y)
{
y = chartRect.y;
}
if (row.isDrawThickLines())
{
((Graphics2D) g).setStroke(thickStroke);
}
// draw lines
- if (row.isDrawLine())
- {
- if (prevX >= 0)
- {
- g.setColor(color);
- if (isChartPointValid(x, y))
- {
- g.drawLine(prevX, prevY, x, y);
- }
- }
- prevX = x;
- prevY = y;
- }
+ if (row.isDrawLine())
+ {
+ boolean valid = isChartPointValid(x, y);
+ if (prevX >= 0)
+ {
+ g.setColor(color);
+ if (valid)
+ {
+ g.drawLine(prevX, prevY, x, y);
+ }
+ }
+ if(valid)
+ {
+ prevX = x;
+ prevY = y;
+ }
+ }
// draw bars
if (row.isDrawBar())
{
g.setColor(color);
if (isChartPointValid(x+1, y)) //as we draw bars, xMax values must be rejected
{
int x2 = chartRect.x + (int) ((calcPointX + row.getGranulationValue() - minXVal) * dxForDVal) - x -1;
Composite oldComposite = ((Graphics2D) g).getComposite();
((Graphics2D) g).setComposite(barComposite);
g.fillRect(x, y-1, x2 , yHeight+1);
((Graphics2D) g).setComposite(oldComposite);
}
}
if (row.isDrawThickLines())
{
((Graphics2D) g).setStroke(oldStroke);
}
if (row.isDrawValueLabel())
{
g.setColor(Color.DARK_GRAY);
Font oldFont = g.getFont();
g.setFont(g.getFont().deriveFont(Font.BOLD));
yAxisLabelRenderer.setValue(calcPointY);
int labelSize = g.getFontMetrics(g.getFont()).stringWidth(yAxisLabelRenderer.getText());
//if close to end
if (x + row.getMarkerSize() + spacing + labelSize > chartRect.x + chartRect.width)
{
g.drawString(yAxisLabelRenderer.getText(),
x - row.getMarkerSize() - spacing - labelSize,
y + fm.getAscent() / 2);
} else
{
g.drawString(yAxisLabelRenderer.getText(),
x + row.getMarkerSize() + spacing,
y + fm.getAscent() / 2);
}
g.setFont(oldFont);
}
// draw markers
if (radius != AbstractGraphRow.MARKER_SIZE_NONE)
{
g.setColor(color);
if (isChartPointValid(x, y))
{
g.fillOval(x - radius, y - radius, (radius) * 2, (radius) * 2);
//g.setColor(Color.black);
//g.drawOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
}
drawFinalLines(row, g, prevX, prevY, dxForDVal, oldStroke, color);
}
/**
*
* @param aRows
*/
public void setRows(AbstractMap<String, AbstractGraphRow> aRows)
{
rows = aRows;
}
/**
* @param yAxisLabelRenderer the yAxisLabelRenderer to set
*/
public void setyAxisLabelRenderer(NumberRenderer yAxisLabelRenderer)
{
this.yAxisLabelRenderer = yAxisLabelRenderer;
}
/**
* @param xAxisLabelRenderer the xAxisLabelRenderer to set
*/
public void setxAxisLabelRenderer(NumberRenderer xAxisLabelRenderer)
{
this.xAxisLabelRenderer = xAxisLabelRenderer;
}
/**
* @param drawFinalZeroingLines the drawFinalZeroingLines to set
*/
public void setDrawFinalZeroingLines(boolean drawFinalZeroingLines)
{
settingsDrawFinalZeroingLines = drawFinalZeroingLines && !neverDrawFinalZeroingLines;
}
/**
* @param drawCurrentX the drawCurrentX to set
*/
public void setDrawCurrentX(boolean drawCurrentX)
{
this.drawCurrentX = drawCurrentX;
}
/**
* @param currentX the currentX to set
*/
public void setCurrentX(long currentX)
{
this.currentXVal = currentX;
}
/**
*
* @param i
*/
public void setForcedMinX(int i)
{
forcedMinX = i;
}
//Paint the add the same color of the axis but with transparency
private void paintAd(Graphics2D g)
{
Font oldFont = g.getFont();
g.setFont(g.getFont().deriveFont(10F));
g.setColor(axisColor);
Composite oldComposite = g.getComposite();
g.setComposite(AlphaComposite.getInstance(AlphaComposite.SRC_OVER, 0.7f));
g.drawString(AD_TEXT,
getWidth() - g.getFontMetrics().stringWidth(AD_TEXT) - spacing,
g.getFontMetrics().getHeight() - spacing + 1);
g.setComposite(oldComposite);
g.setFont(oldFont);
}
/*
* Clear error messages
*/
public void clearErrorMessage()
{
errorMessage = null;
}
/*
* Set error message if not null and not empty
* @param msg the error message to set
*/
public void setErrorMessage(String msg)
{
if (msg != null && msg.trim().length() > 0)
{
errorMessage = msg;
}
}
// Adding a popup menu to copy image in clipboard
@Override
public void lostOwnership(Clipboard clipboard, Transferable contents)
{
// do nothing
}
private Image getImage()
{
return (Image) getBufferedImage();
}
private BufferedImage getBufferedImage()
{
BufferedImage image = new BufferedImage(this.getWidth(), this.getHeight(), BufferedImage.TYPE_INT_ARGB);
Graphics2D g2 = image.createGraphics();
g2.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);
this.drawPanel(g2);
return image;
}
/**
* Thanks to stephane.hoblingre
*/
private void registerPopup(boolean allowCsvExport)
{
this.setComponentPopupMenu(popup);
JMenuItem itemCopy = new JMenuItem("Copy Image to Clipboard");
JMenuItem itemSave = new JMenuItem("Save Image as...");
JMenuItem itemExport = new JMenuItem("Export to CSV...");
itemCopy.addActionListener(new CopyAction());
itemSave.addActionListener(new SaveAction());
itemExport.addActionListener(new CsvExportAction());
popup.add(itemCopy);
popup.add(itemSave);
if(allowCsvExport)
{
popup.addSeparator();
popup.add(itemExport);
}
}
private class CopyAction
implements ActionListener
{
@Override
public void actionPerformed(final ActionEvent e)
{
Clipboard clipboard = getToolkit().getSystemClipboard();
Transferable transferable = new Transferable()
{
@Override
public Object getTransferData(DataFlavor flavor)
{
if (isDataFlavorSupported(flavor))
{
return getImage();
}
return null;
}
@Override
public DataFlavor[] getTransferDataFlavors()
{
return new DataFlavor[]
{
DataFlavor.imageFlavor
};
}
@Override
public boolean isDataFlavorSupported(DataFlavor flavor)
{
return DataFlavor.imageFlavor.equals(flavor);
}
};
clipboard.setContents(transferable, GraphPanelChart.this);
}
}
private class SaveAction
implements ActionListener
{
@Override
public void actionPerformed(final ActionEvent e)
{
JFileChooser chooser = savePath != null ? new JFileChooser(new File(savePath)) : new JFileChooser(new File("."));
chooser.setFileFilter(new FileNameExtensionFilter("PNG Images", "png"));
int returnVal = chooser.showSaveDialog(GraphPanelChart.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (!file.getAbsolutePath().toUpperCase().endsWith(".PNG"))
{
file = new File(file.getAbsolutePath() + ".png");
}
savePath = file.getParent();
boolean doSave = true;
if (file.exists())
{
int choice = JOptionPane.showConfirmDialog(GraphPanelChart.this, "Do you want to overwrite " + file.getAbsolutePath() + "?", "Save Image as", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
doSave = (choice == JOptionPane.YES_OPTION);
}
if (doSave)
{
try
{
FileOutputStream fos = new FileOutputStream(file);
ImageIO.write(getBufferedImage(), "png", fos);
fos.flush();
fos.close();
}
catch (IOException ex)
{
JOptionPane.showConfirmDialog(GraphPanelChart.this, "Impossible to write the image to the file:\n" + ex.getMessage(), "Save Image as", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
private class CsvExportAction
implements ActionListener
{
@Override
public void actionPerformed(final ActionEvent e)
{
JFileChooser chooser = savePath != null ? new JFileChooser(new File(savePath)) : new JFileChooser(new File("."));
chooser.setFileFilter(new FileNameExtensionFilter("CSV Files", "csv"));
int returnVal = chooser.showSaveDialog(GraphPanelChart.this);
if (returnVal == JFileChooser.APPROVE_OPTION)
{
File file = chooser.getSelectedFile();
if (!file.getAbsolutePath().toUpperCase().endsWith(".CSV"))
{
file = new File(file.getAbsolutePath() + ".csv");
}
savePath = file.getParent();
boolean doSave = true;
if (file.exists())
{
int choice = JOptionPane.showConfirmDialog(GraphPanelChart.this, "Do you want to overwrite " + file.getAbsolutePath() + "?", "Export to CSV File", JOptionPane.YES_NO_OPTION, JOptionPane.QUESTION_MESSAGE);
doSave = (choice == JOptionPane.YES_OPTION);
}
if (doSave)
{
GraphModelToCsvExporter exporter = new GraphModelToCsvExporter(rows, file, csvSeparator, xAxisLabel);
try
{
exporter.writeCsvFile();
} catch (IOException ex)
{
JOptionPane.showConfirmDialog(GraphPanelChart.this, "Impossible to write the CSV file:\n" + ex.getMessage(), "Export to CSV File", JOptionPane.DEFAULT_OPTION, JOptionPane.ERROR_MESSAGE);
}
}
}
}
}
}
| true | true | private void paintRow(Graphics g, AbstractGraphRow row, String rowLabel, Color color)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
Iterator<Entry<Long, AbstractGraphPanelChartElement>> it = row.iterator();
Entry<Long, AbstractGraphPanelChartElement> element;
int radius = row.getMarkerSize();
int x, y;
int prevX = settingsDrawFinalZeroingLines ? chartRect.x : -1;
int prevY = chartRect.y + chartRect.height;
final double dxForDVal = (maxXVal <= minXVal) ? 0 : (double) chartRect.width / (maxXVal - minXVal);
final double dyForDVal = (maxYVal <= minYVal) ? 0 : (double) chartRect.height / (maxYVal - minYVal);
Stroke oldStroke = null;
if (row.isDrawThickLines())
{
oldStroke = ((Graphics2D) g).getStroke();
}
while (it.hasNext())
{
if (!row.isDrawOnChart())
{
continue;
}
double calcPointX = 0;
double calcPointY = 0;
if (factorInUse == 1)
{
element = it.next();
AbstractGraphPanelChartElement elt = (AbstractGraphPanelChartElement) element.getValue();
//not compatible with factor != 1, ie cannot be used if limit nb of point is selected.
if (settingsHideNonRepValLimit > 0)
{
while (!elt.isPointRepresentative(settingsHideNonRepValLimit) && it.hasNext())
{
element = it.next();
elt = (AbstractGraphPanelChartElement) element.getValue();
}
if (!elt.isPointRepresentative(settingsHideNonRepValLimit))
{
break;
}
}
calcPointX = element.getKey().doubleValue();
calcPointY = elt.getValue();
} else
{
int nbPointProcessed = 0;
for (int i = 0; i < factorInUse; i++)
{
if (it.hasNext())
{
element = it.next();
calcPointX = calcPointX + element.getKey().doubleValue();
calcPointY = calcPointY + ((AbstractGraphPanelChartElement) element.getValue()).getValue();
nbPointProcessed++;
}
}
calcPointX = calcPointX / (double)nbPointProcessed;
calcPointY = calcPointY / (double)factorInUse;
}
if(expendRows)
{
calcPointY = calcPointY * rowsZoomFactor.get(rowLabel);
}
x = chartRect.x + (int) ((calcPointX - minXVal) * dxForDVal);
int yHeight = (int) ((calcPointY - minYVal) * dyForDVal);
y = chartRect.y + chartRect.height - yHeight;
//fix flickering
if( y < chartRect.y)
{
y = chartRect.y;
}
if (row.isDrawThickLines())
{
((Graphics2D) g).setStroke(thickStroke);
}
// draw lines
if (row.isDrawLine())
{
if (prevX >= 0)
{
g.setColor(color);
if (isChartPointValid(x, y))
{
g.drawLine(prevX, prevY, x, y);
}
}
prevX = x;
prevY = y;
}
// draw bars
if (row.isDrawBar())
{
g.setColor(color);
if (isChartPointValid(x+1, y)) //as we draw bars, xMax values must be rejected
{
int x2 = chartRect.x + (int) ((calcPointX + row.getGranulationValue() - minXVal) * dxForDVal) - x -1;
Composite oldComposite = ((Graphics2D) g).getComposite();
((Graphics2D) g).setComposite(barComposite);
g.fillRect(x, y-1, x2 , yHeight+1);
((Graphics2D) g).setComposite(oldComposite);
}
}
if (row.isDrawThickLines())
{
((Graphics2D) g).setStroke(oldStroke);
}
if (row.isDrawValueLabel())
{
g.setColor(Color.DARK_GRAY);
Font oldFont = g.getFont();
g.setFont(g.getFont().deriveFont(Font.BOLD));
yAxisLabelRenderer.setValue(calcPointY);
int labelSize = g.getFontMetrics(g.getFont()).stringWidth(yAxisLabelRenderer.getText());
//if close to end
if (x + row.getMarkerSize() + spacing + labelSize > chartRect.x + chartRect.width)
{
g.drawString(yAxisLabelRenderer.getText(),
x - row.getMarkerSize() - spacing - labelSize,
y + fm.getAscent() / 2);
} else
{
g.drawString(yAxisLabelRenderer.getText(),
x + row.getMarkerSize() + spacing,
y + fm.getAscent() / 2);
}
g.setFont(oldFont);
}
// draw markers
if (radius != AbstractGraphRow.MARKER_SIZE_NONE)
{
g.setColor(color);
if (isChartPointValid(x, y))
{
g.fillOval(x - radius, y - radius, (radius) * 2, (radius) * 2);
//g.setColor(Color.black);
//g.drawOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
}
drawFinalLines(row, g, prevX, prevY, dxForDVal, oldStroke, color);
}
| private void paintRow(Graphics g, AbstractGraphRow row, String rowLabel, Color color)
{
FontMetrics fm = g.getFontMetrics(g.getFont());
Iterator<Entry<Long, AbstractGraphPanelChartElement>> it = row.iterator();
Entry<Long, AbstractGraphPanelChartElement> element;
int radius = row.getMarkerSize();
int x, y;
int prevX = settingsDrawFinalZeroingLines ? chartRect.x : -1;
int prevY = chartRect.y + chartRect.height;
final double dxForDVal = (maxXVal <= minXVal) ? 0 : (double) chartRect.width / (maxXVal - minXVal);
final double dyForDVal = (maxYVal <= minYVal) ? 0 : (double) chartRect.height / (maxYVal - minYVal);
Stroke oldStroke = null;
if (row.isDrawThickLines())
{
oldStroke = ((Graphics2D) g).getStroke();
}
while (it.hasNext())
{
if (!row.isDrawOnChart())
{
continue;
}
double calcPointX = 0;
double calcPointY = 0;
if (factorInUse == 1)
{
element = it.next();
AbstractGraphPanelChartElement elt = (AbstractGraphPanelChartElement) element.getValue();
//not compatible with factor != 1, ie cannot be used if limit nb of point is selected.
if (settingsHideNonRepValLimit > 0)
{
while (!elt.isPointRepresentative(settingsHideNonRepValLimit) && it.hasNext())
{
element = it.next();
elt = (AbstractGraphPanelChartElement) element.getValue();
}
if (!elt.isPointRepresentative(settingsHideNonRepValLimit))
{
break;
}
}
calcPointX = element.getKey().doubleValue();
calcPointY = elt.getValue();
} else
{
int nbPointProcessed = 0;
for (int i = 0; i < factorInUse; i++)
{
if (it.hasNext())
{
element = it.next();
calcPointX = calcPointX + element.getKey().doubleValue();
calcPointY = calcPointY + ((AbstractGraphPanelChartElement) element.getValue()).getValue();
nbPointProcessed++;
}
}
calcPointX = calcPointX / (double)nbPointProcessed;
calcPointY = calcPointY / (double)factorInUse;
}
if(expendRows)
{
calcPointY = calcPointY * rowsZoomFactor.get(rowLabel);
}
x = chartRect.x + (int) ((calcPointX - minXVal) * dxForDVal);
int yHeight = (int) ((calcPointY - minYVal) * dyForDVal);
y = chartRect.y + chartRect.height - yHeight;
//fix flickering
if( y < chartRect.y)
{
y = chartRect.y;
}
if (row.isDrawThickLines())
{
((Graphics2D) g).setStroke(thickStroke);
}
// draw lines
if (row.isDrawLine())
{
boolean valid = isChartPointValid(x, y);
if (prevX >= 0)
{
g.setColor(color);
if (valid)
{
g.drawLine(prevX, prevY, x, y);
}
}
if(valid)
{
prevX = x;
prevY = y;
}
}
// draw bars
if (row.isDrawBar())
{
g.setColor(color);
if (isChartPointValid(x+1, y)) //as we draw bars, xMax values must be rejected
{
int x2 = chartRect.x + (int) ((calcPointX + row.getGranulationValue() - minXVal) * dxForDVal) - x -1;
Composite oldComposite = ((Graphics2D) g).getComposite();
((Graphics2D) g).setComposite(barComposite);
g.fillRect(x, y-1, x2 , yHeight+1);
((Graphics2D) g).setComposite(oldComposite);
}
}
if (row.isDrawThickLines())
{
((Graphics2D) g).setStroke(oldStroke);
}
if (row.isDrawValueLabel())
{
g.setColor(Color.DARK_GRAY);
Font oldFont = g.getFont();
g.setFont(g.getFont().deriveFont(Font.BOLD));
yAxisLabelRenderer.setValue(calcPointY);
int labelSize = g.getFontMetrics(g.getFont()).stringWidth(yAxisLabelRenderer.getText());
//if close to end
if (x + row.getMarkerSize() + spacing + labelSize > chartRect.x + chartRect.width)
{
g.drawString(yAxisLabelRenderer.getText(),
x - row.getMarkerSize() - spacing - labelSize,
y + fm.getAscent() / 2);
} else
{
g.drawString(yAxisLabelRenderer.getText(),
x + row.getMarkerSize() + spacing,
y + fm.getAscent() / 2);
}
g.setFont(oldFont);
}
// draw markers
if (radius != AbstractGraphRow.MARKER_SIZE_NONE)
{
g.setColor(color);
if (isChartPointValid(x, y))
{
g.fillOval(x - radius, y - radius, (radius) * 2, (radius) * 2);
//g.setColor(Color.black);
//g.drawOval(x - radius, y - radius, radius * 2, radius * 2);
}
}
}
drawFinalLines(row, g, prevX, prevY, dxForDVal, oldStroke, color);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.