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/src/main/java/com/alta189/cyborg/factoids/handlers/util/VariableUtil.java b/src/main/java/com/alta189/cyborg/factoids/handlers/util/VariableUtil.java
index b7e8979..41ccbc8 100644
--- a/src/main/java/com/alta189/cyborg/factoids/handlers/util/VariableUtil.java
+++ b/src/main/java/com/alta189/cyborg/factoids/handlers/util/VariableUtil.java
@@ -1,78 +1,80 @@
/*
* Copyright (C) 2012 CyborgDev <[email protected]>
*
* This file is part of CyborgFactoids
*
* CyborgFactoids 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.
*
* CyborgFactoids 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. If not, see <http://www.gnu.org/licenses/>.
*/
package com.alta189.cyborg.factoids.handlers.util;
import com.alta189.cyborg.api.util.StringUtils;
import com.alta189.cyborg.factoids.FactoidContext;
import com.alta189.cyborg.factoids.LocationType;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class VariableUtil {
private static final Pattern varPattern = Pattern.compile("%([0-9][0-9]{0,2}|10000)%");
private static final Pattern varPatternRange = Pattern.compile("%([0-9][0-9]{0,2}|10000)-([0-9][0-9]{0,2}|10000)%");
private static final Pattern varPatternInfinite = Pattern.compile("%([0-9][0-9]{0,2}|10000)-%");
private static final Pattern nickPattern = Pattern.compile("%nick%");
private static final Pattern chanPattern = Pattern.compile("%chan%");
public static String replaceVars(String raw, FactoidContext context) {
+ if (context.getRawArgs() == null || context.getRawArgs().isEmpty())
+ return raw;
String[] args = context.getRawArgs().split(" ");
Matcher matcher = nickPattern.matcher(raw);
raw = matcher.replaceAll(context.getSender().getNick());
if (context.getLocationType() == LocationType.CHANNEL_MESSAGE) {
matcher = chanPattern.matcher(raw);
raw = matcher.replaceAll(context.getChannel().getName());
}
matcher = varPattern.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.length() - 1));
if (args.length - 1 >= index) {
raw = raw.replace(match, args[index]);
}
}
matcher = varPatternInfinite.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.length() - 2));
if (args.length - 1 >= index) {
raw = raw.replace(match, StringUtils.toString(args, index, " "));
}
}
matcher = varPatternRange.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.indexOf("-")));
int end = Integer.valueOf(match.substring(match.indexOf("-") + 1, match.length() - 1));
System.out.println("index = '" + index + "'");
System.out.println("end = '" + end + "'");
if (args.length - 1 >= index) {
raw = raw.replace(match, StringUtils.toString(args, index, end, " "));
}
}
return raw;
}
}
| true | true | public static String replaceVars(String raw, FactoidContext context) {
String[] args = context.getRawArgs().split(" ");
Matcher matcher = nickPattern.matcher(raw);
raw = matcher.replaceAll(context.getSender().getNick());
if (context.getLocationType() == LocationType.CHANNEL_MESSAGE) {
matcher = chanPattern.matcher(raw);
raw = matcher.replaceAll(context.getChannel().getName());
}
matcher = varPattern.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.length() - 1));
if (args.length - 1 >= index) {
raw = raw.replace(match, args[index]);
}
}
matcher = varPatternInfinite.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.length() - 2));
if (args.length - 1 >= index) {
raw = raw.replace(match, StringUtils.toString(args, index, " "));
}
}
matcher = varPatternRange.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.indexOf("-")));
int end = Integer.valueOf(match.substring(match.indexOf("-") + 1, match.length() - 1));
System.out.println("index = '" + index + "'");
System.out.println("end = '" + end + "'");
if (args.length - 1 >= index) {
raw = raw.replace(match, StringUtils.toString(args, index, end, " "));
}
}
return raw;
}
| public static String replaceVars(String raw, FactoidContext context) {
if (context.getRawArgs() == null || context.getRawArgs().isEmpty())
return raw;
String[] args = context.getRawArgs().split(" ");
Matcher matcher = nickPattern.matcher(raw);
raw = matcher.replaceAll(context.getSender().getNick());
if (context.getLocationType() == LocationType.CHANNEL_MESSAGE) {
matcher = chanPattern.matcher(raw);
raw = matcher.replaceAll(context.getChannel().getName());
}
matcher = varPattern.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.length() - 1));
if (args.length - 1 >= index) {
raw = raw.replace(match, args[index]);
}
}
matcher = varPatternInfinite.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.length() - 2));
if (args.length - 1 >= index) {
raw = raw.replace(match, StringUtils.toString(args, index, " "));
}
}
matcher = varPatternRange.matcher(raw);
while (matcher.find()) {
String match = matcher.group();
int index = Integer.valueOf(match.substring(1, match.indexOf("-")));
int end = Integer.valueOf(match.substring(match.indexOf("-") + 1, match.length() - 1));
System.out.println("index = '" + index + "'");
System.out.println("end = '" + end + "'");
if (args.length - 1 >= index) {
raw = raw.replace(match, StringUtils.toString(args, index, end, " "));
}
}
return raw;
}
|
diff --git a/src/javaapplication/JavaApplication.java b/src/javaapplication/JavaApplication.java
index bd008bf..b9ee93a 100644
--- a/src/javaapplication/JavaApplication.java
+++ b/src/javaapplication/JavaApplication.java
@@ -1,98 +1,98 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package javaapplication;
import java.util.Scanner;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.EntityTransaction;
import javax.persistence.Persistence;
/**
*
* @author alper
*/
public class JavaApplication {
/**
* @param args the command line arguments
*/
public static void main(String[] args) {
// TODO code application logic here
// entity manager and a transaction
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaApplicationPU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
Operations op = new Operations(em, tx);
+ Scanner general = new Scanner(System.in);
+ Book b = new Book();
while(true){
System.out.println("1. Find Book");
System.out.println("2. Create a new Book");
System.out.println("3. Remove a Book");
System.out.println("Select Operation:");
- Scanner general = new Scanner(System.in);
String selection = general.nextLine();
int selec_int = Integer.parseInt(selection);
if(selec_int == 1) {
- Book b = new Book();
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
b = em.find(Book.class, book_name);
System.out.println(b.toString());
}else if (selec_int == 2) {
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
System.out.println("Enter the name of the author:");
String author = general.nextLine();
op.createBook(author.toString(), book_name.toString());
System.out.println("New book added to store!");
}else if (selec_int == 3) {
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
op.removeBook(book_name);
}else {
System.out.println("Select A Valid Operation");
}
}
}
}
class Operations {
protected EntityManager em;
protected EntityTransaction tx;
public Operations(EntityManager em, EntityTransaction tx) {
this.em = em;
this.tx = tx;
}
public void createBook(String author, String book_name){
Book b = new Book(book_name, author);
tx.begin();
em.persist(b);
tx.commit();
em.close();
}
public void removeBook(String book_name){
Book b = em.find(Book.class, book_name);
if(b != null) {
tx.begin();
em.remove(b);
tx.commit();
em.close();
System.out.println("Entity has been deleted!");
} else {
System.out.println("Nothing found!");
}
}
}
| false | true | public static void main(String[] args) {
// TODO code application logic here
// entity manager and a transaction
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaApplicationPU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
Operations op = new Operations(em, tx);
while(true){
System.out.println("1. Find Book");
System.out.println("2. Create a new Book");
System.out.println("3. Remove a Book");
System.out.println("Select Operation:");
Scanner general = new Scanner(System.in);
String selection = general.nextLine();
int selec_int = Integer.parseInt(selection);
if(selec_int == 1) {
Book b = new Book();
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
b = em.find(Book.class, book_name);
System.out.println(b.toString());
}else if (selec_int == 2) {
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
System.out.println("Enter the name of the author:");
String author = general.nextLine();
op.createBook(author.toString(), book_name.toString());
System.out.println("New book added to store!");
}else if (selec_int == 3) {
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
op.removeBook(book_name);
}else {
System.out.println("Select A Valid Operation");
}
}
}
| public static void main(String[] args) {
// TODO code application logic here
// entity manager and a transaction
EntityManagerFactory emf = Persistence.createEntityManagerFactory("JavaApplicationPU");
EntityManager em = emf.createEntityManager();
EntityTransaction tx = em.getTransaction();
Operations op = new Operations(em, tx);
Scanner general = new Scanner(System.in);
Book b = new Book();
while(true){
System.out.println("1. Find Book");
System.out.println("2. Create a new Book");
System.out.println("3. Remove a Book");
System.out.println("Select Operation:");
String selection = general.nextLine();
int selec_int = Integer.parseInt(selection);
if(selec_int == 1) {
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
b = em.find(Book.class, book_name);
System.out.println(b.toString());
}else if (selec_int == 2) {
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
System.out.println("Enter the name of the author:");
String author = general.nextLine();
op.createBook(author.toString(), book_name.toString());
System.out.println("New book added to store!");
}else if (selec_int == 3) {
System.out.println("Enter the name of the book:");
String book_name = general.nextLine();
op.removeBook(book_name);
}else {
System.out.println("Select A Valid Operation");
}
}
}
|
diff --git a/ProcessorPlugin/src/org/gephi/io/processor/plugin/DynamicProcessor.java b/ProcessorPlugin/src/org/gephi/io/processor/plugin/DynamicProcessor.java
index 20f0ad9bf..b2bfc2269 100644
--- a/ProcessorPlugin/src/org/gephi/io/processor/plugin/DynamicProcessor.java
+++ b/ProcessorPlugin/src/org/gephi/io/processor/plugin/DynamicProcessor.java
@@ -1,421 +1,421 @@
/*
Copyright 2008-2010 Gephi
Authors : Mathieu Bastian <[email protected]>
Website : http://www.gephi.org
This file is part of Gephi.
Gephi is free software: you can redistribute it and/or modify
it under the terms of the GNU Affero General Public License as
published by the Free Software Foundation, either version 3 of the
License, or (at your option) any later version.
Gephi is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
GNU Affero General Public License for more details.
You should have received a copy of the GNU Affero General Public License
along with Gephi. If not, see <http://www.gnu.org/licenses/>.
*/
package org.gephi.io.processor.plugin;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import org.gephi.data.attributes.api.AttributeColumn;
import org.gephi.data.attributes.api.AttributeController;
import org.gephi.data.attributes.api.AttributeOrigin;
import org.gephi.data.attributes.api.AttributeRow;
import org.gephi.data.attributes.api.AttributeTable;
import org.gephi.data.attributes.api.AttributeType;
import org.gephi.data.attributes.api.AttributeValue;
import org.gephi.data.attributes.type.DynamicType;
import org.gephi.data.attributes.type.Interval;
import org.gephi.data.attributes.type.TimeInterval;
import org.gephi.data.attributes.type.TypeConvertor;
import org.gephi.data.properties.PropertiesColumn;
import org.gephi.dynamic.DynamicUtilities;
import org.gephi.dynamic.api.DynamicController;
import org.gephi.dynamic.api.DynamicModel;
import org.gephi.graph.api.Edge;
import org.gephi.graph.api.GraphController;
import org.gephi.graph.api.GraphFactory;
import org.gephi.graph.api.GraphModel;
import org.gephi.graph.api.HierarchicalGraph;
import org.gephi.graph.api.Node;
import org.gephi.io.importer.api.EdgeDraft.EdgeType;
import org.gephi.io.importer.api.EdgeDraftGetter;
import org.gephi.io.importer.api.NodeDraftGetter;
import org.gephi.io.processor.spi.Processor;
import org.gephi.project.api.ProjectController;
import org.openide.util.Lookup;
import org.openide.util.NbBundle;
import org.openide.util.lookup.ServiceProvider;
/**
*
* @author Mathieu Bastian
*/
@ServiceProvider(service = Processor.class)
public class DynamicProcessor extends AbstractProcessor implements Processor {
//Settings
private boolean dateMode = true;
private String date = "";
private boolean labelmatching = true;
//Variable
private double point;
public void process() {
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
//Workspace
if (workspace == null) {
workspace = pc.getCurrentWorkspace();
if (workspace == null) {
//Append mode but no workspace
workspace = pc.newWorkspace(pc.getCurrentProject());
pc.openWorkspace(workspace);
}
}
if (container.getSource() != null) {
pc.setSource(workspace, container.getSource());
}
//Architecture
GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();
HierarchicalGraph graph = null;
switch (container.getEdgeDefault()) {
case DIRECTED:
graph = graphModel.getHierarchicalDirectedGraph();
break;
case UNDIRECTED:
graph = graphModel.getHierarchicalUndirectedGraph();
break;
case MIXED:
graph = graphModel.getHierarchicalMixedGraph();
break;
default:
graph = graphModel.getHierarchicalMixedGraph();
break;
}
GraphFactory factory = graphModel.factory();
//Attributes - Manually merge models with new dynamic cols
attributeModel = Lookup.getDefault().lookup(AttributeController.class).getModel();
AttributeTable nodeTable = container.getAttributeModel().getNodeTable();
AttributeTable edgeTable = container.getAttributeModel().getEdgeTable();
for (AttributeColumn column : nodeTable.getColumns()) {
AttributeColumn existingCol = attributeModel.getNodeTable().getColumn(column.getTitle());
if (existingCol == null) {
if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) {
AttributeType dynamicType = TypeConvertor.getDynamicType(column.getType());
if (dynamicType != null && !column.getType().isDynamicType()) {
attributeModel.getNodeTable().addColumn(column.getId(), column.getTitle(), dynamicType, column.getOrigin(), null);
} else {
attributeModel.getNodeTable().addColumn(column.getId(), column.getTitle(), column.getType(), column.getOrigin(), column.getDefaultValue());
}
}
}
}
for (AttributeColumn column : edgeTable.getColumns()) {
AttributeColumn existingCol = attributeModel.getEdgeTable().getColumn(column.getTitle());
if (existingCol == null) {
if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) {
AttributeType dynamicType = TypeConvertor.getDynamicType(column.getType());
if (dynamicType != null && !column.getType().isDynamicType()) {
attributeModel.getEdgeTable().addColumn(column.getId(), column.getTitle(), dynamicType, column.getOrigin(), null);
} else {
attributeModel.getEdgeTable().addColumn(column.getId(), column.getTitle(), column.getType(), column.getOrigin(), column.getDefaultValue());
}
}
- } else if (PropertiesColumn.EDGE_WEIGHT.getId().equals(column.getId())) {
+ } else if (PropertiesColumn.EDGE_WEIGHT.getId().equals(column.getId()) && !existingCol.getType().isDynamicType()) {
attributeModel.getEdgeTable().replaceColumn(attributeModel.getEdgeTable().getColumn(PropertiesColumn.EDGE_WEIGHT.getIndex()), PropertiesColumn.EDGE_WEIGHT.getId(), PropertiesColumn.EDGE_WEIGHT.getTitle(), AttributeType.DYNAMIC_FLOAT, AttributeOrigin.PROPERTY, null);
}
}
//Get Time Interval Column
AttributeColumn nodeDynamicColumn = attributeModel.getNodeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);
AttributeColumn edgeDynamicColumn = attributeModel.getEdgeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);
if (nodeDynamicColumn == null) {
nodeDynamicColumn = attributeModel.getNodeTable().addColumn(DynamicModel.TIMEINTERVAL_COLUMN, "Time Interval", AttributeType.TIME_INTERVAL, AttributeOrigin.PROPERTY, null);
}
if (edgeDynamicColumn == null) {
edgeDynamicColumn = attributeModel.getEdgeTable().addColumn(DynamicModel.TIMEINTERVAL_COLUMN, "Time Interval", AttributeType.TIME_INTERVAL, AttributeOrigin.PROPERTY, null);
}
//Get Time stamp
if (dateMode) {
try {
point = DynamicUtilities.getDoubleFromXMLDateString(date);
} catch (Exception e) {
throw new RuntimeException("The entered date can't be parsed");
}
} else {
point = Double.parseDouble(date);
}
DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class);
dynamicController.setTimeFormat(dateMode ? DynamicModel.TimeFormat.DATE : DynamicModel.TimeFormat.DOUBLE);
//Index existing graph
Map<String, Node> map = new HashMap<String, Node>();
for (Node n : graph.getNodes()) {
String id = n.getNodeData().getId();
if (id != null && !labelmatching && !id.equalsIgnoreCase(String.valueOf(n.getId()))) {
map.put(id, n);
}
if (n.getNodeData().getLabel() != null && !n.getNodeData().getLabel().isEmpty() && labelmatching) {
map.put(n.getNodeData().getLabel(), n);
}
}
//Create all nodes
Set<Node> nodesInDraft = new HashSet<Node>();
int newNodeCount = 0;
for (NodeDraftGetter draftNode : container.getNodes()) {
Node node = null;
String id = draftNode.getId();
String label = draftNode.getLabel();
if (!draftNode.isAutoId() && id != null && map.get(id) != null && !labelmatching) {
node = map.get(id);
} else if (label != null && map.get(label) != null && labelmatching) {
node = map.get(label);
}
TimeInterval timeInterval = null;
if (node == null) {
//Node is new
node = factory.newNode(draftNode.isAutoId() ? null : draftNode.getId());
flushToNode(draftNode, node);
draftNode.setNode(node);
newNodeCount++;
} else {
timeInterval = (TimeInterval) node.getNodeData().getAttributes().getValue(nodeDynamicColumn.getIndex());
flushToNodeAttributes(draftNode, node);
draftNode.setNode(node);
}
nodesInDraft.add(node);
//Add Point
node.getNodeData().getAttributes().setValue(nodeDynamicColumn.getIndex(), addPoint(timeInterval, point));
}
//Push nodes in data structure
for (NodeDraftGetter draftNode : container.getNodes()) {
Node n = draftNode.getNode();
NodeDraftGetter[] parents = draftNode.getParents();
if (parents != null) {
for (int i = 0; i < parents.length; i++) {
Node parent = parents[i].getNode();
graph.addNode(n, parent);
}
} else {
graph.addNode(n);
}
}
//Remove point from all nodes not in draft
for (Node node : graph.getNodes()) {
if (!nodesInDraft.contains(node)) {
TimeInterval timeInterval = (TimeInterval) node.getNodeData().getAttributes().getValue(nodeDynamicColumn.getIndex());
node.getNodeData().getAttributes().setValue(nodeDynamicColumn.getIndex(), removePoint(timeInterval, point));
}
}
//Create all edges and push to data structure
Set<Edge> edgesInDraft = new HashSet<Edge>();
int newEdgeCount = 0;
for (EdgeDraftGetter draftEdge : container.getEdges()) {
Node source = draftEdge.getSource().getNode();
Node target = draftEdge.getTarget().getNode();
Edge edge = graph.getEdge(source, target);
TimeInterval timeInterval = null;
if (edge == null) {
//Edge is new
switch (container.getEdgeDefault()) {
case DIRECTED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), true);
break;
case UNDIRECTED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), false);
break;
case MIXED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), draftEdge.getType().equals(EdgeType.UNDIRECTED) ? false : true);
break;
}
newEdgeCount++;
graph.addEdge(edge);
flushToEdge(draftEdge, edge);
} else {
timeInterval = (TimeInterval) edge.getEdgeData().getAttributes().getValue(edgeDynamicColumn.getIndex());
flushToEdgeAttributes(draftEdge, edge);
}
edgesInDraft.add(edge);
//Add Point
edge.getEdgeData().getAttributes().setValue(edgeDynamicColumn.getIndex(), addPoint(timeInterval, point));
}
//Remove point from all edges not in draft
for (Edge edge : graph.getEdges()) {
if (!edgesInDraft.contains(edge)) {
TimeInterval timeInterval = (TimeInterval) edge.getEdgeData().getAttributes().getValue(edgeDynamicColumn.getIndex());
edge.getEdgeData().getAttributes().setValue(edgeDynamicColumn.getIndex(), removePoint(timeInterval, point));
}
}
System.out.println("# New Nodes loaded: " + newNodeCount + "\n# New Edges loaded: " + newEdgeCount);
workspace = null;
}
@Override
protected void flushToNodeAttributes(NodeDraftGetter nodeDraft, Node node) {
if (node.getNodeData().getAttributes() != null) {
AttributeRow row = (AttributeRow) node.getNodeData().getAttributes();
for (int i = 0; i < row.countValues(); i++) {
Object val = row.getValue(i);
AttributeColumn col = row.getColumnAt(i);
Object draftValue = nodeDraft.getAttributeRow().getValue(col.getId());
if (col.getType().isDynamicType()) {
if (draftValue == null && val != null) {
removePoint(col.getType(), (DynamicType) val, point);
} else if (draftValue != null) {
DynamicType dynamicValue = addPoint(col.getType(), (DynamicType) val, draftValue, point);
row.setValue(col.getIndex(), dynamicValue);
}
} else if (draftValue != null && !col.getOrigin().equals(AttributeOrigin.PROPERTY)) {
row.setValue(col.getIndex(), draftValue);
}
}
}
}
@Override
protected void flushToEdgeAttributes(EdgeDraftGetter edgeDraft, Edge edge) {
if (edge.getEdgeData().getAttributes() != null) {
AttributeRow row = (AttributeRow) edge.getEdgeData().getAttributes();
for (int i = 0; i < row.countValues(); i++) {
Object val = row.getValue(i);
AttributeColumn col = row.getColumnAt(i);
Object draftValue = edgeDraft.getAttributeRow().getValue(col);
if (col.getId().equals(PropertiesColumn.EDGE_WEIGHT.getId())) {
draftValue = new Float(edgeDraft.getWeight());
}
if (col.getType().isDynamicType()) {
if (draftValue == null && val != null) {
removePoint(col.getType(), (DynamicType) val, point);
} else if (draftValue != null) {
DynamicType dynamicValue = addPoint(col.getType(), (DynamicType) val, draftValue, point);
row.setValue(col.getIndex(), dynamicValue);
}
} else if (draftValue != null && !col.getOrigin().equals(AttributeOrigin.PROPERTY)) {
row.setValue(col.getIndex(), draftValue);
}
}
}
}
private TimeInterval addPoint(TimeInterval source, double point) {
if (source == null) {
return new TimeInterval(point, Double.POSITIVE_INFINITY);
}
List<Interval<Double[]>> intervals = source.getIntervals(point, point);
if (intervals.isEmpty()) {
return new TimeInterval(source, point, Double.POSITIVE_INFINITY);
}
return source;
}
private DynamicType addPoint(AttributeType type, DynamicType source, Object value, double point) {
if (source == null) {
return DynamicUtilities.createDynamicObject(type, new Interval(point, Double.POSITIVE_INFINITY, value));
}
List<Interval<?>> intervals = source.getIntervals(point, point);
if (intervals.isEmpty()) {
return DynamicUtilities.createDynamicObject(type, source, new Interval(point, Double.POSITIVE_INFINITY, value));
} else if (intervals.size() > 1) {
throw new RuntimeException("DynamicProcessor doesn't support overlapping intervals.");
} else {
Interval<?> toRemove = intervals.get(0);
if (!toRemove.getValue().equals(value)) {
Interval toAdd = new Interval(toRemove.getLow(), point, toRemove.isLowExcluded(), true, toRemove.getValue());
DynamicType updated = DynamicUtilities.createDynamicObject(type, source, toAdd, toRemove);
toAdd = new Interval(point, Double.POSITIVE_INFINITY, value);
updated = DynamicUtilities.createDynamicObject(type, updated, toAdd);
return updated;
}
}
return source;
}
private TimeInterval removePoint(TimeInterval source, double point) {
if (source == null) {
return null;
}
List<Interval<Double[]>> intervals = source.getIntervals(point, point);
if (intervals.size() > 1) {
throw new RuntimeException("DynamicProcessor doesn't support overlapping intervals.");
} else if (!intervals.isEmpty()) {
Interval<Double[]> toRemove = intervals.get(0);
if (toRemove.getLow() >= point) {
return source;
}
Double[] toAdd = new Double[]{toRemove.getLow(), point};
return new TimeInterval(source, toAdd[0], toAdd[1], toRemove.isLowExcluded(), true, toRemove.getLow(), toRemove.getHigh(), toRemove.isLowExcluded(), toRemove.isHighExcluded());
}
return source;
}
private DynamicType removePoint(AttributeType type, DynamicType source, double point) {
if (source == null) {
return null;
}
List<Interval<?>> intervals = source.getIntervals(point, point);
if (intervals.size() > 1) {
throw new RuntimeException("DynamicProcessor doesn't support overlapping intervals.");
} else if (!intervals.isEmpty()) {
Interval<?> toRemove = intervals.get(0);
if (toRemove.getLow() >= point) {
return source;
}
Interval toAdd = new Interval(toRemove.getLow(), point, toRemove.isLowExcluded(), true, toRemove.getValue());
return DynamicUtilities.createDynamicObject(type, source, toAdd, toRemove);
}
return source;
}
public String getDisplayName() {
return NbBundle.getMessage(DynamicProcessor.class, "DynamicProcessor.displayName");
}
public String getDate() {
return date;
}
public void setDate(String date) {
this.date = date;
}
public boolean isDateMode() {
return dateMode;
}
public void setDateMode(boolean dateMode) {
this.dateMode = dateMode;
}
public boolean isLabelmatching() {
return labelmatching;
}
public void setLabelmatching(boolean labelmatching) {
this.labelmatching = labelmatching;
}
}
| true | true | public void process() {
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
//Workspace
if (workspace == null) {
workspace = pc.getCurrentWorkspace();
if (workspace == null) {
//Append mode but no workspace
workspace = pc.newWorkspace(pc.getCurrentProject());
pc.openWorkspace(workspace);
}
}
if (container.getSource() != null) {
pc.setSource(workspace, container.getSource());
}
//Architecture
GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();
HierarchicalGraph graph = null;
switch (container.getEdgeDefault()) {
case DIRECTED:
graph = graphModel.getHierarchicalDirectedGraph();
break;
case UNDIRECTED:
graph = graphModel.getHierarchicalUndirectedGraph();
break;
case MIXED:
graph = graphModel.getHierarchicalMixedGraph();
break;
default:
graph = graphModel.getHierarchicalMixedGraph();
break;
}
GraphFactory factory = graphModel.factory();
//Attributes - Manually merge models with new dynamic cols
attributeModel = Lookup.getDefault().lookup(AttributeController.class).getModel();
AttributeTable nodeTable = container.getAttributeModel().getNodeTable();
AttributeTable edgeTable = container.getAttributeModel().getEdgeTable();
for (AttributeColumn column : nodeTable.getColumns()) {
AttributeColumn existingCol = attributeModel.getNodeTable().getColumn(column.getTitle());
if (existingCol == null) {
if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) {
AttributeType dynamicType = TypeConvertor.getDynamicType(column.getType());
if (dynamicType != null && !column.getType().isDynamicType()) {
attributeModel.getNodeTable().addColumn(column.getId(), column.getTitle(), dynamicType, column.getOrigin(), null);
} else {
attributeModel.getNodeTable().addColumn(column.getId(), column.getTitle(), column.getType(), column.getOrigin(), column.getDefaultValue());
}
}
}
}
for (AttributeColumn column : edgeTable.getColumns()) {
AttributeColumn existingCol = attributeModel.getEdgeTable().getColumn(column.getTitle());
if (existingCol == null) {
if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) {
AttributeType dynamicType = TypeConvertor.getDynamicType(column.getType());
if (dynamicType != null && !column.getType().isDynamicType()) {
attributeModel.getEdgeTable().addColumn(column.getId(), column.getTitle(), dynamicType, column.getOrigin(), null);
} else {
attributeModel.getEdgeTable().addColumn(column.getId(), column.getTitle(), column.getType(), column.getOrigin(), column.getDefaultValue());
}
}
} else if (PropertiesColumn.EDGE_WEIGHT.getId().equals(column.getId())) {
attributeModel.getEdgeTable().replaceColumn(attributeModel.getEdgeTable().getColumn(PropertiesColumn.EDGE_WEIGHT.getIndex()), PropertiesColumn.EDGE_WEIGHT.getId(), PropertiesColumn.EDGE_WEIGHT.getTitle(), AttributeType.DYNAMIC_FLOAT, AttributeOrigin.PROPERTY, null);
}
}
//Get Time Interval Column
AttributeColumn nodeDynamicColumn = attributeModel.getNodeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);
AttributeColumn edgeDynamicColumn = attributeModel.getEdgeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);
if (nodeDynamicColumn == null) {
nodeDynamicColumn = attributeModel.getNodeTable().addColumn(DynamicModel.TIMEINTERVAL_COLUMN, "Time Interval", AttributeType.TIME_INTERVAL, AttributeOrigin.PROPERTY, null);
}
if (edgeDynamicColumn == null) {
edgeDynamicColumn = attributeModel.getEdgeTable().addColumn(DynamicModel.TIMEINTERVAL_COLUMN, "Time Interval", AttributeType.TIME_INTERVAL, AttributeOrigin.PROPERTY, null);
}
//Get Time stamp
if (dateMode) {
try {
point = DynamicUtilities.getDoubleFromXMLDateString(date);
} catch (Exception e) {
throw new RuntimeException("The entered date can't be parsed");
}
} else {
point = Double.parseDouble(date);
}
DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class);
dynamicController.setTimeFormat(dateMode ? DynamicModel.TimeFormat.DATE : DynamicModel.TimeFormat.DOUBLE);
//Index existing graph
Map<String, Node> map = new HashMap<String, Node>();
for (Node n : graph.getNodes()) {
String id = n.getNodeData().getId();
if (id != null && !labelmatching && !id.equalsIgnoreCase(String.valueOf(n.getId()))) {
map.put(id, n);
}
if (n.getNodeData().getLabel() != null && !n.getNodeData().getLabel().isEmpty() && labelmatching) {
map.put(n.getNodeData().getLabel(), n);
}
}
//Create all nodes
Set<Node> nodesInDraft = new HashSet<Node>();
int newNodeCount = 0;
for (NodeDraftGetter draftNode : container.getNodes()) {
Node node = null;
String id = draftNode.getId();
String label = draftNode.getLabel();
if (!draftNode.isAutoId() && id != null && map.get(id) != null && !labelmatching) {
node = map.get(id);
} else if (label != null && map.get(label) != null && labelmatching) {
node = map.get(label);
}
TimeInterval timeInterval = null;
if (node == null) {
//Node is new
node = factory.newNode(draftNode.isAutoId() ? null : draftNode.getId());
flushToNode(draftNode, node);
draftNode.setNode(node);
newNodeCount++;
} else {
timeInterval = (TimeInterval) node.getNodeData().getAttributes().getValue(nodeDynamicColumn.getIndex());
flushToNodeAttributes(draftNode, node);
draftNode.setNode(node);
}
nodesInDraft.add(node);
//Add Point
node.getNodeData().getAttributes().setValue(nodeDynamicColumn.getIndex(), addPoint(timeInterval, point));
}
//Push nodes in data structure
for (NodeDraftGetter draftNode : container.getNodes()) {
Node n = draftNode.getNode();
NodeDraftGetter[] parents = draftNode.getParents();
if (parents != null) {
for (int i = 0; i < parents.length; i++) {
Node parent = parents[i].getNode();
graph.addNode(n, parent);
}
} else {
graph.addNode(n);
}
}
//Remove point from all nodes not in draft
for (Node node : graph.getNodes()) {
if (!nodesInDraft.contains(node)) {
TimeInterval timeInterval = (TimeInterval) node.getNodeData().getAttributes().getValue(nodeDynamicColumn.getIndex());
node.getNodeData().getAttributes().setValue(nodeDynamicColumn.getIndex(), removePoint(timeInterval, point));
}
}
//Create all edges and push to data structure
Set<Edge> edgesInDraft = new HashSet<Edge>();
int newEdgeCount = 0;
for (EdgeDraftGetter draftEdge : container.getEdges()) {
Node source = draftEdge.getSource().getNode();
Node target = draftEdge.getTarget().getNode();
Edge edge = graph.getEdge(source, target);
TimeInterval timeInterval = null;
if (edge == null) {
//Edge is new
switch (container.getEdgeDefault()) {
case DIRECTED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), true);
break;
case UNDIRECTED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), false);
break;
case MIXED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), draftEdge.getType().equals(EdgeType.UNDIRECTED) ? false : true);
break;
}
newEdgeCount++;
graph.addEdge(edge);
flushToEdge(draftEdge, edge);
} else {
timeInterval = (TimeInterval) edge.getEdgeData().getAttributes().getValue(edgeDynamicColumn.getIndex());
flushToEdgeAttributes(draftEdge, edge);
}
edgesInDraft.add(edge);
//Add Point
edge.getEdgeData().getAttributes().setValue(edgeDynamicColumn.getIndex(), addPoint(timeInterval, point));
}
//Remove point from all edges not in draft
for (Edge edge : graph.getEdges()) {
if (!edgesInDraft.contains(edge)) {
TimeInterval timeInterval = (TimeInterval) edge.getEdgeData().getAttributes().getValue(edgeDynamicColumn.getIndex());
edge.getEdgeData().getAttributes().setValue(edgeDynamicColumn.getIndex(), removePoint(timeInterval, point));
}
}
System.out.println("# New Nodes loaded: " + newNodeCount + "\n# New Edges loaded: " + newEdgeCount);
workspace = null;
}
| public void process() {
ProjectController pc = Lookup.getDefault().lookup(ProjectController.class);
//Workspace
if (workspace == null) {
workspace = pc.getCurrentWorkspace();
if (workspace == null) {
//Append mode but no workspace
workspace = pc.newWorkspace(pc.getCurrentProject());
pc.openWorkspace(workspace);
}
}
if (container.getSource() != null) {
pc.setSource(workspace, container.getSource());
}
//Architecture
GraphModel graphModel = Lookup.getDefault().lookup(GraphController.class).getModel();
HierarchicalGraph graph = null;
switch (container.getEdgeDefault()) {
case DIRECTED:
graph = graphModel.getHierarchicalDirectedGraph();
break;
case UNDIRECTED:
graph = graphModel.getHierarchicalUndirectedGraph();
break;
case MIXED:
graph = graphModel.getHierarchicalMixedGraph();
break;
default:
graph = graphModel.getHierarchicalMixedGraph();
break;
}
GraphFactory factory = graphModel.factory();
//Attributes - Manually merge models with new dynamic cols
attributeModel = Lookup.getDefault().lookup(AttributeController.class).getModel();
AttributeTable nodeTable = container.getAttributeModel().getNodeTable();
AttributeTable edgeTable = container.getAttributeModel().getEdgeTable();
for (AttributeColumn column : nodeTable.getColumns()) {
AttributeColumn existingCol = attributeModel.getNodeTable().getColumn(column.getTitle());
if (existingCol == null) {
if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) {
AttributeType dynamicType = TypeConvertor.getDynamicType(column.getType());
if (dynamicType != null && !column.getType().isDynamicType()) {
attributeModel.getNodeTable().addColumn(column.getId(), column.getTitle(), dynamicType, column.getOrigin(), null);
} else {
attributeModel.getNodeTable().addColumn(column.getId(), column.getTitle(), column.getType(), column.getOrigin(), column.getDefaultValue());
}
}
}
}
for (AttributeColumn column : edgeTable.getColumns()) {
AttributeColumn existingCol = attributeModel.getEdgeTable().getColumn(column.getTitle());
if (existingCol == null) {
if (!column.getOrigin().equals(AttributeOrigin.PROPERTY)) {
AttributeType dynamicType = TypeConvertor.getDynamicType(column.getType());
if (dynamicType != null && !column.getType().isDynamicType()) {
attributeModel.getEdgeTable().addColumn(column.getId(), column.getTitle(), dynamicType, column.getOrigin(), null);
} else {
attributeModel.getEdgeTable().addColumn(column.getId(), column.getTitle(), column.getType(), column.getOrigin(), column.getDefaultValue());
}
}
} else if (PropertiesColumn.EDGE_WEIGHT.getId().equals(column.getId()) && !existingCol.getType().isDynamicType()) {
attributeModel.getEdgeTable().replaceColumn(attributeModel.getEdgeTable().getColumn(PropertiesColumn.EDGE_WEIGHT.getIndex()), PropertiesColumn.EDGE_WEIGHT.getId(), PropertiesColumn.EDGE_WEIGHT.getTitle(), AttributeType.DYNAMIC_FLOAT, AttributeOrigin.PROPERTY, null);
}
}
//Get Time Interval Column
AttributeColumn nodeDynamicColumn = attributeModel.getNodeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);
AttributeColumn edgeDynamicColumn = attributeModel.getEdgeTable().getColumn(DynamicModel.TIMEINTERVAL_COLUMN);
if (nodeDynamicColumn == null) {
nodeDynamicColumn = attributeModel.getNodeTable().addColumn(DynamicModel.TIMEINTERVAL_COLUMN, "Time Interval", AttributeType.TIME_INTERVAL, AttributeOrigin.PROPERTY, null);
}
if (edgeDynamicColumn == null) {
edgeDynamicColumn = attributeModel.getEdgeTable().addColumn(DynamicModel.TIMEINTERVAL_COLUMN, "Time Interval", AttributeType.TIME_INTERVAL, AttributeOrigin.PROPERTY, null);
}
//Get Time stamp
if (dateMode) {
try {
point = DynamicUtilities.getDoubleFromXMLDateString(date);
} catch (Exception e) {
throw new RuntimeException("The entered date can't be parsed");
}
} else {
point = Double.parseDouble(date);
}
DynamicController dynamicController = Lookup.getDefault().lookup(DynamicController.class);
dynamicController.setTimeFormat(dateMode ? DynamicModel.TimeFormat.DATE : DynamicModel.TimeFormat.DOUBLE);
//Index existing graph
Map<String, Node> map = new HashMap<String, Node>();
for (Node n : graph.getNodes()) {
String id = n.getNodeData().getId();
if (id != null && !labelmatching && !id.equalsIgnoreCase(String.valueOf(n.getId()))) {
map.put(id, n);
}
if (n.getNodeData().getLabel() != null && !n.getNodeData().getLabel().isEmpty() && labelmatching) {
map.put(n.getNodeData().getLabel(), n);
}
}
//Create all nodes
Set<Node> nodesInDraft = new HashSet<Node>();
int newNodeCount = 0;
for (NodeDraftGetter draftNode : container.getNodes()) {
Node node = null;
String id = draftNode.getId();
String label = draftNode.getLabel();
if (!draftNode.isAutoId() && id != null && map.get(id) != null && !labelmatching) {
node = map.get(id);
} else if (label != null && map.get(label) != null && labelmatching) {
node = map.get(label);
}
TimeInterval timeInterval = null;
if (node == null) {
//Node is new
node = factory.newNode(draftNode.isAutoId() ? null : draftNode.getId());
flushToNode(draftNode, node);
draftNode.setNode(node);
newNodeCount++;
} else {
timeInterval = (TimeInterval) node.getNodeData().getAttributes().getValue(nodeDynamicColumn.getIndex());
flushToNodeAttributes(draftNode, node);
draftNode.setNode(node);
}
nodesInDraft.add(node);
//Add Point
node.getNodeData().getAttributes().setValue(nodeDynamicColumn.getIndex(), addPoint(timeInterval, point));
}
//Push nodes in data structure
for (NodeDraftGetter draftNode : container.getNodes()) {
Node n = draftNode.getNode();
NodeDraftGetter[] parents = draftNode.getParents();
if (parents != null) {
for (int i = 0; i < parents.length; i++) {
Node parent = parents[i].getNode();
graph.addNode(n, parent);
}
} else {
graph.addNode(n);
}
}
//Remove point from all nodes not in draft
for (Node node : graph.getNodes()) {
if (!nodesInDraft.contains(node)) {
TimeInterval timeInterval = (TimeInterval) node.getNodeData().getAttributes().getValue(nodeDynamicColumn.getIndex());
node.getNodeData().getAttributes().setValue(nodeDynamicColumn.getIndex(), removePoint(timeInterval, point));
}
}
//Create all edges and push to data structure
Set<Edge> edgesInDraft = new HashSet<Edge>();
int newEdgeCount = 0;
for (EdgeDraftGetter draftEdge : container.getEdges()) {
Node source = draftEdge.getSource().getNode();
Node target = draftEdge.getTarget().getNode();
Edge edge = graph.getEdge(source, target);
TimeInterval timeInterval = null;
if (edge == null) {
//Edge is new
switch (container.getEdgeDefault()) {
case DIRECTED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), true);
break;
case UNDIRECTED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), false);
break;
case MIXED:
edge = factory.newEdge(draftEdge.isAutoId() ? null : draftEdge.getId(), source, target, draftEdge.getWeight(), draftEdge.getType().equals(EdgeType.UNDIRECTED) ? false : true);
break;
}
newEdgeCount++;
graph.addEdge(edge);
flushToEdge(draftEdge, edge);
} else {
timeInterval = (TimeInterval) edge.getEdgeData().getAttributes().getValue(edgeDynamicColumn.getIndex());
flushToEdgeAttributes(draftEdge, edge);
}
edgesInDraft.add(edge);
//Add Point
edge.getEdgeData().getAttributes().setValue(edgeDynamicColumn.getIndex(), addPoint(timeInterval, point));
}
//Remove point from all edges not in draft
for (Edge edge : graph.getEdges()) {
if (!edgesInDraft.contains(edge)) {
TimeInterval timeInterval = (TimeInterval) edge.getEdgeData().getAttributes().getValue(edgeDynamicColumn.getIndex());
edge.getEdgeData().getAttributes().setValue(edgeDynamicColumn.getIndex(), removePoint(timeInterval, point));
}
}
System.out.println("# New Nodes loaded: " + newNodeCount + "\n# New Edges loaded: " + newEdgeCount);
workspace = null;
}
|
diff --git a/javasrc/src/org/ccnx/ccn/impl/CCNFlowControl.java b/javasrc/src/org/ccnx/ccn/impl/CCNFlowControl.java
index 8c2ec889f..34ad36c5f 100644
--- a/javasrc/src/org/ccnx/ccn/impl/CCNFlowControl.java
+++ b/javasrc/src/org/ccnx/ccn/impl/CCNFlowControl.java
@@ -1,452 +1,453 @@
package org.ccnx.ccn.impl;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashSet;
import java.util.Iterator;
import java.util.Set;
import java.util.TreeMap;
import org.ccnx.ccn.CCNFilterListener;
import org.ccnx.ccn.CCNHandle;
import org.ccnx.ccn.config.ConfigurationException;
import org.ccnx.ccn.impl.InterestTable.Entry;
import org.ccnx.ccn.impl.support.Log;
import org.ccnx.ccn.protocol.ContentName;
import org.ccnx.ccn.protocol.ContentObject;
import org.ccnx.ccn.protocol.Interest;
import org.ccnx.ccn.protocol.MalformedContentNameStringException;
/**
* Implements rudimentary flow control by matching content objects
* with interests before actually putting them out to ccnd.
*
* Holds content objects until a matching interest is seen and holds
* interests and matches immediately if a content object matching a
* held interest is put.
*
* Implements a highwater mark in the holding buffer. If the buffer size
* reaches the highwater mark, a put will block until there is more
* room in the buffer. Currently this is only per "flow controller". There
* is nothing to stop multiple streams writing to the repo for instance to
* independently all fill their buffers and cause a lot of memory to be used.
*
* The buffer emptying policy in "afterPutAction can be overridden by
* subclasses to implement a different way of draining the buffer. This is used
* by the repo client to allow objects to remain in the buffer until they are
* acked.
*
* @author rasmusse
*
*/
public class CCNFlowControl implements CCNFilterListener {
public enum Shape {STREAM};
protected CCNHandle _library = null;
// Temporarily default to very high timeout so that puts have a good
// chance of going through. We actually may want to keep this.
protected static final int MAX_TIMEOUT = 10000;
protected static final int HIGHWATER_DEFAULT = 128 + 1;
protected static final int INTEREST_HIGHWATER_DEFAULT = 40;
protected int _timeout = MAX_TIMEOUT;
protected int _highwater = HIGHWATER_DEFAULT;
protected long _nOut = 0;
protected static final int PURGE = 2000;
protected TreeMap<ContentName, ContentObject> _holdingArea = new TreeMap<ContentName, ContentObject>();
protected InterestTable<UnmatchedInterest> _unmatchedInterests = new InterestTable<UnmatchedInterest>();
protected HashSet<ContentName> _filteredNames = new HashSet<ContentName>();
private class UnmatchedInterest {
long timestamp = new Date().getTime();
}
private boolean _flowControlEnabled = true;
/**
* Enabled flow control constructor
* @param name
* @param library
*/
public CCNFlowControl(ContentName name, CCNHandle library) throws IOException {
this(library);
if (name != null) {
Log.finest("adding namespace: " + name);
// don't call full addNameSpace, in order to allow subclasses to
// override. just do minimal part
_filteredNames.add(name);
_library.registerFilter(name, this);
}
_unmatchedInterests.setHighWater(INTEREST_HIGHWATER_DEFAULT);
}
public CCNFlowControl(String name, CCNHandle library)
throws MalformedContentNameStringException, IOException {
this(ContentName.fromNative(name), library);
}
public CCNFlowControl(CCNHandle library) throws IOException {
if (null == library) {
// Could make this create a library.
try {
library = CCNHandle.open();
} catch (ConfigurationException e) {
Log.info("Got ConfigurationException attempting to create a library. Rethrowing it as an IOException. Message: " + e.getMessage());
throw new IOException("ConfigurationException creating a library: " + e.getMessage());
}
}
_library = library;
_unmatchedInterests.setHighWater(INTEREST_HIGHWATER_DEFAULT);
}
/**
* Add a new namespace to the controller
* @param name
* @throws IOException
*/
public void addNameSpace(ContentName name) throws IOException {
if (!_flowControlEnabled)
return;
Iterator<ContentName> it = _filteredNames.iterator();
while (it.hasNext()) {
ContentName filteredName = it.next();
if (filteredName.isPrefixOf(name)) {
Log.info("addNameSpace: not adding name: " + name + " already monitoring prefix: " + filteredName);
return; // Already part of filter
}
if (name.isPrefixOf(filteredName)) {
_library.unregisterFilter(filteredName, this);
it.remove();
}
}
Log.info("addNameSpace: adding namespace: " + name);
_filteredNames.add(name);
_library.registerFilter(name, this);
}
public void addNameSpace(String name) throws MalformedContentNameStringException, IOException {
addNameSpace(ContentName.fromNative(name));
}
/**
* This is used by the RepoFlowController to indicate that it should start a write
* @param name
* @param shape
* @throws MalformedContentNameStringException
* @throws IOException
*/
public void startWrite(String name, Shape shape) throws MalformedContentNameStringException, IOException {
startWrite(ContentName.fromNative(name), shape);
}
public void startWrite(ContentName name, Shape shape) throws IOException {}
/**
* For now we don't have anyway to remove a partial namespace from
* flow control (would we want to do that?) so for now we only allow
* removal of a namespace if it actually matches something that was
* registered
*
* @param name
*/
public void removeNameSpace(ContentName name) {
removeNameSpace(name, false);
}
private void removeNameSpace(ContentName name, boolean all) {
Iterator<ContentName> it = _filteredNames.iterator();
while (it.hasNext()) {
ContentName filteredName = it.next();
if (all || filteredName.equals(name)) {
_library.unregisterFilter(filteredName, this);
it.remove();
Log.finest("removing namespace: " + name);
break;
}
}
}
public ContentName getNameSpace(ContentName childName) {
ContentName prefix = null;
for (ContentName nameSpace : _filteredNames) {
if (nameSpace.isPrefixOf(childName)) {
// is this the only one?
if (null == prefix) {
prefix = nameSpace;
} else if (nameSpace.count() > prefix.count()) {
prefix = nameSpace;
}
}
}
return prefix;
}
/**
* Add content objects to this flow controller
* @param cos
* @throws IOException
*/
public void put(ArrayList<ContentObject> cos) throws IOException {
for (ContentObject co : cos) {
put(co);
}
}
/**
* Add content objects to this flow controller
* @param cos
* @throws IOException
*/
public void put(ContentObject [] cos) throws IOException {
for (ContentObject co : cos) {
put(co);
}
}
/**
* Add namespace and content at the same time
* @param co
* @throws IOException
* @throws IOException
*/
public void put(ContentName name, ArrayList<ContentObject> cos) throws IOException {
addNameSpace(name);
put(cos);
}
public ContentObject put(ContentName name, ContentObject co) throws IOException {
addNameSpace(name);
return put(co);
}
public ContentObject put(ContentObject co) throws IOException {
if (_flowControlEnabled) {
boolean found = false;
for (ContentName name : _filteredNames) {
if (name.isPrefixOf(co.name())) {
found = true;
break;
}
}
if (!found)
throw new IOException("Flow control: co name \"" + co.name()
+ "\" is not in the flow control namespace");
}
return waitForMatch(co);
}
private ContentObject waitForMatch(ContentObject co) throws IOException {
if (_flowControlEnabled) {
synchronized (_holdingArea) {
Entry<UnmatchedInterest> match = null;
Log.finest("Holding " + co.name());
_holdingArea.put(co.name(), co);
match = _unmatchedInterests.removeMatch(co);
if (match != null) {
Log.finest("Found pending matching interest for " + co.name() + ", putting to network.");
_library.put(co);
+ _nOut++;
afterPutAction(co);
}
if (_holdingArea.size() >= _highwater) {
boolean interrupted;
long ourTime = new Date().getTime();
Entry<UnmatchedInterest> removeIt;
do {
removeIt = null;
for (Entry<UnmatchedInterest> uie : _unmatchedInterests.values()) {
if ((ourTime - uie.value().timestamp) > PURGE) {
removeIt = uie;
break;
}
}
if (removeIt != null)
_unmatchedInterests.remove(removeIt.interest(), removeIt.value());
} while (removeIt != null);
do {
interrupted = false;
try {
Log.finest("Waiting for drain");
_holdingArea.wait(_timeout);
if (_holdingArea.size() >= _highwater)
throw new IOException("Flow control buffer full and not draining");
} catch (InterruptedException e) {
interrupted = true;
}
} while (interrupted);
}
}
} else
_library.put(co);
return co;
}
public int handleInterests(ArrayList<Interest> interests) {
synchronized (_holdingArea) {
for (Interest interest : interests) {
Log.fine("Flow controller: got interest: " + interest);
ContentObject co = getBestMatch(interest);
if (co != null) {
Log.finest("Found content " + co.name() + " matching interest: " + interest);
try {
_library.put(co);
_nOut++;
afterPutAction(co);
} catch (IOException e) {
Log.warning("IOException in handleInterests: " + e.getClass().getName() + ": " + e.getMessage());
Log.warningStackTrace(e);
}
} else {
Log.finest("No content matching pending interest: " + interest + ", holding.");
_unmatchedInterests.add(interest, new UnmatchedInterest());
}
}
}
return interests.size();
}
/**
* Allow override of action after co is put to ccnd
* Don't need to sync on holding area because this is only called within
* holding area sync
* @param co
*/
public void afterPutAction(ContentObject co) throws IOException {
_holdingArea.remove(co.name());
_holdingArea.notify();
}
/**
* Try to optimize this by giving preference to "getNext" which is
* presumably going to be the most common kind of get. So we first try
* on a tailmap following the interest, and if that doesn't get us
* anything, we try all the data.
* XXX there are probably better ways to optimize this that I haven't
* thought of yet also...
*
* @param interest
* @param set
* @return
*/
public ContentObject getBestMatch(Interest interest) {
// paul r - following seems broken for some reason - I'll try
// to sort it out later
//SortedMap<ContentName, ContentObject> matchMap = _holdingArea.tailMap(interest.name());
//ContentObject result = getBestMatch(interest, matchMap.keySet());
//if (result != null)
// return result;
return getBestMatch(interest, _holdingArea.keySet());
}
private ContentObject getBestMatch(Interest interest, Set<ContentName> set) {
ContentObject bestMatch = null;
Log.finest("Looking for best match to " + interest + " among " + set.size() + " options.");
for (ContentName name : set) {
ContentObject result = _holdingArea.get(name);
// We only have to do something unusual here if the caller is looking for CHILD_SELECTOR_RIGHT
if (null != interest.childSelector() && interest.childSelector() == Interest.CHILD_SELECTOR_RIGHT) {
if (interest.matches(result)) {
if (bestMatch == null)
bestMatch = result;
if (name.compareTo(bestMatch.name()) > 0) {
bestMatch = result;
}
}
} else
if (interest.matches(result))
return result;
}
return bestMatch;
}
public void beforeClose() throws IOException {
// default -- do nothing.
}
public void afterClose() throws IOException {
waitForPutDrain();
}
public void waitForPutDrain() throws IOException {
synchronized (_holdingArea) {
long startSize = _nOut;
while (_holdingArea.size() > 0) {
long startTime = System.currentTimeMillis();
boolean keepTrying = true;
do {
try {
long waitTime = _timeout - (System.currentTimeMillis() - startTime);
if (waitTime > 0)
_holdingArea.wait(waitTime);
} catch (InterruptedException ie) {
keepTrying = true;
}
if (_nOut == startSize || (System.currentTimeMillis() - startTime) >= _timeout)
keepTrying = false;
} while (keepTrying);
if (_nOut == startSize) {
for(ContentName co : _holdingArea.keySet()) {
Log.warning("FlowController: still holding: " + co.toString());
}
throw new IOException("Put(s) with no matching interests - size is " + _holdingArea.size());
}
startSize = _holdingArea.size();
}
}
}
public void setTimeout(int timeout) {
_timeout = timeout;
}
public int getTimeout() {
return _timeout;
}
/**
* Shutdown but wait for puts to drain first
* @throws IOException
*/
public void shutdown() throws IOException {
waitForPutDrain();
_library.getNetworkManager().shutdown();
}
public CCNHandle getLibrary() {
return _library;
}
public void clearUnmatchedInterests() {
Log.info("Clearing " + _unmatchedInterests.size() + " unmatched interests.");
_unmatchedInterests.clear();
}
public void enable() {
_flowControlEnabled = true;
}
public void setHighwater(int value) {
_highwater = value;
}
public void setInterestHighwater(int value) {
_unmatchedInterests.setHighWater(value);
}
/**
* Warning - calling this risks packet drops. It should only
* be used for tests or other special circumstances in which
* you "know what you are doing".
*/
public void disable() {
removeNameSpace(null, true);
_flowControlEnabled = false;
}
}
| true | true | private ContentObject waitForMatch(ContentObject co) throws IOException {
if (_flowControlEnabled) {
synchronized (_holdingArea) {
Entry<UnmatchedInterest> match = null;
Log.finest("Holding " + co.name());
_holdingArea.put(co.name(), co);
match = _unmatchedInterests.removeMatch(co);
if (match != null) {
Log.finest("Found pending matching interest for " + co.name() + ", putting to network.");
_library.put(co);
afterPutAction(co);
}
if (_holdingArea.size() >= _highwater) {
boolean interrupted;
long ourTime = new Date().getTime();
Entry<UnmatchedInterest> removeIt;
do {
removeIt = null;
for (Entry<UnmatchedInterest> uie : _unmatchedInterests.values()) {
if ((ourTime - uie.value().timestamp) > PURGE) {
removeIt = uie;
break;
}
}
if (removeIt != null)
_unmatchedInterests.remove(removeIt.interest(), removeIt.value());
} while (removeIt != null);
do {
interrupted = false;
try {
Log.finest("Waiting for drain");
_holdingArea.wait(_timeout);
if (_holdingArea.size() >= _highwater)
throw new IOException("Flow control buffer full and not draining");
} catch (InterruptedException e) {
interrupted = true;
}
} while (interrupted);
}
}
} else
_library.put(co);
return co;
}
| private ContentObject waitForMatch(ContentObject co) throws IOException {
if (_flowControlEnabled) {
synchronized (_holdingArea) {
Entry<UnmatchedInterest> match = null;
Log.finest("Holding " + co.name());
_holdingArea.put(co.name(), co);
match = _unmatchedInterests.removeMatch(co);
if (match != null) {
Log.finest("Found pending matching interest for " + co.name() + ", putting to network.");
_library.put(co);
_nOut++;
afterPutAction(co);
}
if (_holdingArea.size() >= _highwater) {
boolean interrupted;
long ourTime = new Date().getTime();
Entry<UnmatchedInterest> removeIt;
do {
removeIt = null;
for (Entry<UnmatchedInterest> uie : _unmatchedInterests.values()) {
if ((ourTime - uie.value().timestamp) > PURGE) {
removeIt = uie;
break;
}
}
if (removeIt != null)
_unmatchedInterests.remove(removeIt.interest(), removeIt.value());
} while (removeIt != null);
do {
interrupted = false;
try {
Log.finest("Waiting for drain");
_holdingArea.wait(_timeout);
if (_holdingArea.size() >= _highwater)
throw new IOException("Flow control buffer full and not draining");
} catch (InterruptedException e) {
interrupted = true;
}
} while (interrupted);
}
}
} else
_library.put(co);
return co;
}
|
diff --git a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java
index e299ff72..2263205e 100644
--- a/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java
+++ b/jetty-server/src/main/java/org/eclipse/jetty/server/AbstractConnector.java
@@ -1,1043 +1,1043 @@
// ========================================================================
// Copyright (c) 2004-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.server;
import java.io.IOException;
import java.net.InetAddress;
import java.net.Socket;
import java.net.UnknownHostException;
import javax.servlet.ServletRequest;
import org.eclipse.jetty.http.HttpBuffers;
import org.eclipse.jetty.http.HttpFields;
import org.eclipse.jetty.http.HttpHeaders;
import org.eclipse.jetty.http.HttpSchemes;
import org.eclipse.jetty.io.Buffer;
import org.eclipse.jetty.io.ByteArrayBuffer;
import org.eclipse.jetty.io.EndPoint;
import org.eclipse.jetty.io.EofException;
import org.eclipse.jetty.util.component.LifeCycle;
import org.eclipse.jetty.util.log.Log;
import org.eclipse.jetty.util.thread.ThreadPool;
/** Abstract Connector implementation.
* This abstract implementation of the Connector interface provides:<ul>
* <li>AbstractLifeCycle implementation</li>
* <li>Implementations for connector getters and setters</li>
* <li>Buffer management</li>
* <li>Socket configuration</li>
* <li>Base acceptor thread</li>
* <li>Optional reverse proxy headers checking</li>
* </ul>
*
*
*/
public abstract class AbstractConnector extends HttpBuffers implements Connector
{
private String _name;
private Server _server;
private ThreadPool _threadPool;
private String _host;
private int _port=0;
private String _integralScheme=HttpSchemes.HTTPS;
private int _integralPort=0;
private String _confidentialScheme=HttpSchemes.HTTPS;
private int _confidentialPort=0;
private int _acceptQueueSize=0;
private int _acceptors=1;
private int _acceptorPriorityOffset=0;
private boolean _useDNS;
private boolean _forwarded;
private String _hostHeader;
private String _forwardedHostHeader = "X-Forwarded-Host"; // default to mod_proxy_http header
private String _forwardedServerHeader = "X-Forwarded-Server"; // default to mod_proxy_http header
private String _forwardedForHeader = "X-Forwarded-For"; // default to mod_proxy_http header
private boolean _reuseAddress=true;
protected int _maxIdleTime=200000;
protected int _lowResourceMaxIdleTime=-1;
protected int _soLingerTime=-1;
private transient Thread[] _acceptorThread;
final Object _statsLock = new Object();
transient long _statsStartedAt=-1;
// TODO use concurrents for these!
transient int _requests;
transient int _connections; // total number of connections made to server
transient int _connectionsOpen; // number of connections currently open
transient int _connectionsOpenMin; // min number of connections open simultaneously
transient int _connectionsOpenMax; // max number of connections open simultaneously
transient long _connectionsDurationMin; // min duration of a connection
transient long _connectionsDurationMax; // max duration of a connection
transient long _connectionsDurationTotal; // total duration of all coneection
transient int _connectionsRequestsMin; // min requests per connection
transient int _connectionsRequestsMax; // max requests per connection
/* ------------------------------------------------------------------------------- */
/**
*/
public AbstractConnector()
{
}
/* ------------------------------------------------------------------------------- */
public final Buffer newBuffer(int size)
{
// TODO remove once no overrides established
return null;
}
/* ------------------------------------------------------------------------------- */
public Buffer newRequestBuffer(int size)
{
return new ByteArrayBuffer(size);
}
/* ------------------------------------------------------------------------------- */
public Buffer newRequestHeader(int size)
{
return new ByteArrayBuffer(size);
}
/* ------------------------------------------------------------------------------- */
public Buffer newResponseBuffer(int size)
{
return new ByteArrayBuffer(size);
}
/* ------------------------------------------------------------------------------- */
public Buffer newResponseHeader(int size)
{
return new ByteArrayBuffer(size);
}
/* ------------------------------------------------------------------------------- */
protected boolean isRequestHeader(Buffer buffer)
{
return true;
}
/* ------------------------------------------------------------------------------- */
protected boolean isResponseHeader(Buffer buffer)
{
return true;
}
/* ------------------------------------------------------------------------------- */
/*
*/
public Server getServer()
{
return _server;
}
/* ------------------------------------------------------------------------------- */
public void setServer(Server server)
{
_server=server;
}
/* ------------------------------------------------------------------------------- */
/*
* @see org.eclipse.jetty.http.HttpListener#getHttpServer()
*/
public ThreadPool getThreadPool()
{
return _threadPool;
}
/* ------------------------------------------------------------------------------- */
public void setThreadPool(ThreadPool pool)
{
_threadPool=pool;
}
/* ------------------------------------------------------------------------------- */
/**
*/
public void setHost(String host)
{
_host=host;
}
/* ------------------------------------------------------------------------------- */
/*
*/
public String getHost()
{
return _host;
}
/* ------------------------------------------------------------------------------- */
/*
* @see org.eclipse.jetty.server.server.HttpListener#setPort(int)
*/
public void setPort(int port)
{
_port=port;
}
/* ------------------------------------------------------------------------------- */
/*
* @see org.eclipse.jetty.server.server.HttpListener#getPort()
*/
public int getPort()
{
return _port;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the maxIdleTime.
*/
public int getMaxIdleTime()
{
return _maxIdleTime;
}
/* ------------------------------------------------------------ */
/**
* Set the maximum Idle time for a connection, which roughly translates
* to the {@link Socket#setSoTimeout(int)} call, although with NIO
* implementations other mechanisms may be used to implement the timeout.
* The max idle time is applied:<ul>
* <li>When waiting for a new request to be received on a connection</li>
* <li>When reading the headers and content of a request</li>
* <li>When writing the headers and content of a response</li>
* </ul>
* Jetty interprets this value as the maximum time between some progress being
* made on the connection. So if a single byte is read or written, then the
* timeout (if implemented by jetty) is reset. However, in many instances,
* the reading/writing is delegated to the JVM, and the semantic is more
* strictly enforced as the maximum time a single read/write operation can
* take. Note, that as Jetty supports writes of memory mapped file buffers,
* then a write may take many 10s of seconds for large content written to a
* slow device.
* <p>
* Previously, Jetty supported separate idle timeouts and IO operation timeouts,
* however the expense of changing the value of soTimeout was significant, so
* these timeouts were merged. With the advent of NIO, it may be possible to
* again differentiate these values (if there is demand).
*
* @param maxIdleTime The maxIdleTime to set.
*/
public void setMaxIdleTime(int maxIdleTime)
{
_maxIdleTime = maxIdleTime;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the maxIdleTime.
*/
public int getLowResourceMaxIdleTime()
{
return _lowResourceMaxIdleTime;
}
/* ------------------------------------------------------------ */
/**
* @param maxIdleTime The maxIdleTime to set.
*/
public void setLowResourceMaxIdleTime(int maxIdleTime)
{
_lowResourceMaxIdleTime = maxIdleTime;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the soLingerTime.
*/
public int getSoLingerTime()
{
return _soLingerTime;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the acceptQueueSize.
*/
public int getAcceptQueueSize()
{
return _acceptQueueSize;
}
/* ------------------------------------------------------------ */
/**
* @param acceptQueueSize The acceptQueueSize to set.
*/
public void setAcceptQueueSize(int acceptQueueSize)
{
_acceptQueueSize = acceptQueueSize;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the number of acceptor threads.
*/
public int getAcceptors()
{
return _acceptors;
}
/* ------------------------------------------------------------ */
/**
* @param acceptors The number of acceptor threads to set.
*/
public void setAcceptors(int acceptors)
{
_acceptors = acceptors;
}
/* ------------------------------------------------------------ */
/**
* @param soLingerTime The soLingerTime to set or -1 to disable.
*/
public void setSoLingerTime(int soLingerTime)
{
_soLingerTime = soLingerTime;
}
/* ------------------------------------------------------------ */
protected void doStart() throws Exception
{
if (_server==null)
throw new IllegalStateException("No server");
// open listener port
open();
super.doStart();
if (_threadPool==null)
_threadPool=_server.getThreadPool();
if (_threadPool!=_server.getThreadPool() && (_threadPool instanceof LifeCycle))
((LifeCycle)_threadPool).start();
// Start selector thread
synchronized(this)
{
_acceptorThread=new Thread[getAcceptors()];
for (int i=0;i<_acceptorThread.length;i++)
{
if (!_threadPool.dispatch(new Acceptor(i)))
{
Log.warn("insufficient maxThreads configured for {}",this);
break;
}
}
}
Log.info("Started {}",this);
}
/* ------------------------------------------------------------ */
protected void doStop() throws Exception
{
try{close();} catch(IOException e) {Log.warn(e);}
if (_threadPool==_server.getThreadPool())
_threadPool=null;
else if (_threadPool instanceof LifeCycle)
((LifeCycle)_threadPool).stop();
super.doStop();
Thread[] acceptors=null;
synchronized(this)
{
acceptors=_acceptorThread;
_acceptorThread=null;
}
if (acceptors != null)
{
for (int i=0;i<acceptors.length;i++)
{
Thread thread=acceptors[i];
if (thread!=null)
thread.interrupt();
}
}
}
/* ------------------------------------------------------------ */
public void join() throws InterruptedException
{
Thread[] threads=_acceptorThread;
if (threads!=null)
for (int i=0;i<threads.length;i++)
if (threads[i]!=null)
threads[i].join();
}
/* ------------------------------------------------------------ */
protected void configure(Socket socket)
throws IOException
{
try
{
socket.setTcpNoDelay(true);
if (_maxIdleTime >= 0)
socket.setSoTimeout(_maxIdleTime);
if (_soLingerTime >= 0)
socket.setSoLinger(true, _soLingerTime/1000);
else
socket.setSoLinger(false, 0);
}
catch (Exception e)
{
Log.ignore(e);
}
}
/* ------------------------------------------------------------ */
public void customize(EndPoint endpoint, Request request)
throws IOException
{
if (isForwarded())
checkForwardedHeaders(endpoint, request);
}
/* ------------------------------------------------------------ */
protected void checkForwardedHeaders(EndPoint endpoint, Request request)
throws IOException
{
HttpFields httpFields = request.getConnection().getRequestFields();
// Retrieving headers from the request
String forwardedHost = getLeftMostValue(httpFields.getStringField(getForwardedHostHeader()));
String forwardedServer = getLeftMostValue(httpFields.getStringField(getForwardedServerHeader()));
String forwardedFor = getLeftMostValue(httpFields.getStringField(getForwardedForHeader()));
if (_hostHeader!=null)
{
// Update host header
httpFields.put(HttpHeaders.HOST_BUFFER, _hostHeader);
request.setServerName(null);
request.setServerPort(-1);
request.getServerName();
}
else if (forwardedHost != null)
{
// Update host header
httpFields.put(HttpHeaders.HOST_BUFFER, forwardedHost);
request.setServerName(null);
request.setServerPort(-1);
request.getServerName();
}
else if (forwardedServer != null)
{
// Use provided server name
request.setServerName(forwardedServer);
}
if (forwardedFor != null)
{
request.setRemoteAddr(forwardedFor);
InetAddress inetAddress = null;
if (_useDNS)
{
try
{
inetAddress = InetAddress.getByName(forwardedFor);
}
catch (UnknownHostException e)
{
Log.ignore(e);
}
}
request.setRemoteHost(inetAddress==null?forwardedFor:inetAddress.getHostName());
}
}
/* ------------------------------------------------------------ */
protected String getLeftMostValue(String headerValue) {
if (headerValue == null)
return null;
int commaIndex = headerValue.indexOf(',');
if (commaIndex == -1)
{
// Single value
return headerValue;
}
// The left-most value is the farthest downstream client
return headerValue.substring(0, commaIndex);
}
/* ------------------------------------------------------------ */
public void persist(EndPoint endpoint)
throws IOException
{
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialPort()
*/
public int getConfidentialPort()
{
return _confidentialPort;
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialScheme()
*/
public String getConfidentialScheme()
{
return _confidentialScheme;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server.Request)
*/
public boolean isIntegral(Request request)
{
return false;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getConfidentialPort()
*/
public int getIntegralPort()
{
return _integralPort;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#getIntegralScheme()
*/
public String getIntegralScheme()
{
return _integralScheme;
}
/* ------------------------------------------------------------ */
/*
* @see org.eclipse.jetty.server.Connector#isConfidential(org.eclipse.jetty.server.Request)
*/
public boolean isConfidential(Request request)
{
return false;
}
/* ------------------------------------------------------------ */
/**
* @param confidentialPort The confidentialPort to set.
*/
public void setConfidentialPort(int confidentialPort)
{
_confidentialPort = confidentialPort;
}
/* ------------------------------------------------------------ */
/**
* @param confidentialScheme The confidentialScheme to set.
*/
public void setConfidentialScheme(String confidentialScheme)
{
_confidentialScheme = confidentialScheme;
}
/* ------------------------------------------------------------ */
/**
* @param integralPort The integralPort to set.
*/
public void setIntegralPort(int integralPort)
{
_integralPort = integralPort;
}
/* ------------------------------------------------------------ */
/**
* @param integralScheme The integralScheme to set.
*/
public void setIntegralScheme(String integralScheme)
{
_integralScheme = integralScheme;
}
/* ------------------------------------------------------------ */
protected abstract void accept(int acceptorID) throws IOException, InterruptedException;
/* ------------------------------------------------------------ */
public void stopAccept(int acceptorID) throws Exception
{
}
/* ------------------------------------------------------------ */
public boolean getResolveNames()
{
return _useDNS;
}
/* ------------------------------------------------------------ */
public void setResolveNames(boolean resolve)
{
_useDNS=resolve;
}
/* ------------------------------------------------------------ */
/**
* Is reverse proxy handling on?
* @return true if this connector is checking the x-forwarded-for/host/server headers
*/
public boolean isForwarded()
{
return _forwarded;
}
/* ------------------------------------------------------------ */
/**
* Set reverse proxy handling
* @param check true if this connector is checking the x-forwarded-for/host/server headers
*/
public void setForwarded(boolean check)
{
if (check)
Log.debug(this+" is forwarded");
_forwarded=check;
}
/* ------------------------------------------------------------ */
public String getHostHeader()
{
return _hostHeader;
}
/* ------------------------------------------------------------ */
/**
* Set a forced valued for the host header to control what is returned
* by {@link ServletRequest#getServerName()} and {@link ServletRequest#getServerPort()}.
* This value is only used if {@link #isForwarded()} is true.
* @param hostHeader The value of the host header to force.
*/
public void setHostHeader(String hostHeader)
{
_hostHeader=hostHeader;
}
/* ------------------------------------------------------------ */
public String getForwardedHostHeader()
{
return _forwardedHostHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedHostHeader The header name for forwarded hosts (default x-forwarded-host)
*/
public void setForwardedHostHeader(String forwardedHostHeader)
{
_forwardedHostHeader=forwardedHostHeader;
}
/* ------------------------------------------------------------ */
public String getForwardedServerHeader()
{
return _forwardedServerHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedHostHeader The header name for forwarded server (default x-forwarded-server)
*/
public void setForwardedServerHeader(String forwardedServerHeader)
{
_forwardedServerHeader=forwardedServerHeader;
}
/* ------------------------------------------------------------ */
public String getForwardedForHeader()
{
return _forwardedForHeader;
}
/* ------------------------------------------------------------ */
/**
* @param forwardedHostHeader The header name for forwarded for (default x-forwarded-for)
*/
public void setForwardedForHeader(String forwardedRemoteAddressHeade)
{
_forwardedForHeader=forwardedRemoteAddressHeade;
}
/* ------------------------------------------------------------ */
public String toString()
{
String name = this.getClass().getName();
int dot = name.lastIndexOf('.');
if (dot>0)
name=name.substring(dot+1);
return name+"@"+(getHost()==null?"0.0.0.0":getHost())+":"+(getLocalPort()<=0?getPort():getLocalPort());
}
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
/* ------------------------------------------------------------ */
private class Acceptor implements Runnable
{
int _acceptor=0;
Acceptor(int id)
{
_acceptor=id;
}
/* ------------------------------------------------------------ */
public void run()
{
Thread current = Thread.currentThread();
synchronized(AbstractConnector.this)
{
if (_acceptorThread==null)
return;
_acceptorThread[_acceptor]=current;
+ String name =_acceptorThread[_acceptor].getName();
+ current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this);
}
- String name =_acceptorThread[_acceptor].getName();
- current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this);
int old_priority=current.getPriority();
try
{
current.setPriority(old_priority-_acceptorPriorityOffset);
while (isRunning() && getConnection()!=null)
{
try
{
accept(_acceptor);
}
catch(EofException e)
{
Log.ignore(e);
}
catch(IOException e)
{
Log.ignore(e);
}
catch(ThreadDeath e)
{
Log.warn(e);
throw e;
}
catch(Throwable e)
{
Log.warn(e);
}
}
}
finally
{
current.setPriority(old_priority);
current.setName(name);
try
{
if (_acceptor==0)
close();
}
catch (IOException e)
{
Log.warn(e);
}
synchronized(AbstractConnector.this)
{
if (_acceptorThread!=null)
_acceptorThread[_acceptor]=null;
}
}
}
}
/* ------------------------------------------------------------ */
public String getName()
{
if (_name==null)
_name= (getHost()==null?"0.0.0.0":getHost())+":"+(getLocalPort()<=0?getPort():getLocalPort());
return _name;
}
/* ------------------------------------------------------------ */
public void setName(String name)
{
_name = name;
}
/* ------------------------------------------------------------ */
/**
* @return Get the number of requests handled by this context
* since last call of statsReset(). If setStatsOn(false) then this
* is undefined.
*/
public int getRequests() {return _requests;}
/* ------------------------------------------------------------ */
/**
* @return Returns the connectionsDurationMin.
*/
public long getConnectionsDurationMin()
{
return _connectionsDurationMin;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the connectionsDurationTotal.
*/
public long getConnectionsDurationTotal()
{
return _connectionsDurationTotal;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the connectionsOpenMin.
*/
public int getConnectionsOpenMin()
{
return _connectionsOpenMin;
}
/* ------------------------------------------------------------ */
/**
* @return Returns the connectionsRequestsMin.
*/
public int getConnectionsRequestsMin()
{
return _connectionsRequestsMin;
}
/* ------------------------------------------------------------ */
/**
* @return Number of connections accepted by the server since
* statsReset() called. Undefined if setStatsOn(false).
*/
public int getConnections() {return _connections;}
/* ------------------------------------------------------------ */
/**
* @return Number of connections currently open that were opened
* since statsReset() called. Undefined if setStatsOn(false).
*/
public int getConnectionsOpen() {return _connectionsOpen;}
/* ------------------------------------------------------------ */
/**
* @return Maximum number of connections opened simultaneously
* since statsReset() called. Undefined if setStatsOn(false).
*/
public int getConnectionsOpenMax() {return _connectionsOpenMax;}
/* ------------------------------------------------------------ */
/**
* @return Average duration in milliseconds of open connections
* since statsReset() called. Undefined if setStatsOn(false).
*/
public long getConnectionsDurationAve() {return _connections==0?0:(_connectionsDurationTotal/_connections);}
/* ------------------------------------------------------------ */
/**
* @return Maximum duration in milliseconds of an open connection
* since statsReset() called. Undefined if setStatsOn(false).
*/
public long getConnectionsDurationMax() {return _connectionsDurationMax;}
/* ------------------------------------------------------------ */
/**
* @return Average number of requests per connection
* since statsReset() called. Undefined if setStatsOn(false).
*/
public int getConnectionsRequestsAve() {return _connections==0?0:(_requests/_connections);}
/* ------------------------------------------------------------ */
/**
* @return Maximum number of requests per connection
* since statsReset() called. Undefined if setStatsOn(false).
*/
public int getConnectionsRequestsMax() {return _connectionsRequestsMax;}
/* ------------------------------------------------------------ */
/** Reset statistics.
*/
public void statsReset()
{
_statsStartedAt=_statsStartedAt==-1?-1:System.currentTimeMillis();
_connections=0;
_connectionsOpenMin=_connectionsOpen;
_connectionsOpenMax=_connectionsOpen;
_connectionsOpen=0;
_connectionsDurationMin=0;
_connectionsDurationMax=0;
_connectionsDurationTotal=0;
_requests=0;
_connectionsRequestsMin=0;
_connectionsRequestsMax=0;
}
/* ------------------------------------------------------------ */
public void setStatsOn(boolean on)
{
if (on && _statsStartedAt!=-1)
return;
Log.debug("Statistics on = "+on+" for "+this);
statsReset();
_statsStartedAt=on?System.currentTimeMillis():-1;
}
/* ------------------------------------------------------------ */
/**
* @return True if statistics collection is turned on.
*/
public boolean getStatsOn()
{
return _statsStartedAt!=-1;
}
/* ------------------------------------------------------------ */
/**
* @return Timestamp stats were started at.
*/
public long getStatsOnMs()
{
return (_statsStartedAt!=-1)?(System.currentTimeMillis()-_statsStartedAt):0;
}
/* ------------------------------------------------------------ */
protected void connectionOpened(HttpConnection connection)
{
if (_statsStartedAt==-1)
return;
synchronized(_statsLock)
{
_connectionsOpen++;
if (_connectionsOpen > _connectionsOpenMax)
_connectionsOpenMax=_connectionsOpen;
}
}
/* ------------------------------------------------------------ */
protected void connectionClosed(HttpConnection connection)
{
if (_statsStartedAt>=0)
{
long duration=System.currentTimeMillis()-connection.getTimeStamp();
int requests=connection.getRequests();
synchronized(_statsLock)
{
_requests+=requests;
_connections++;
_connectionsOpen--;
_connectionsDurationTotal+=duration;
if (_connectionsOpen<0)
_connectionsOpen=0;
if (_connectionsOpen<_connectionsOpenMin)
_connectionsOpenMin=_connectionsOpen;
if (_connectionsDurationMin==0 || duration<_connectionsDurationMin)
_connectionsDurationMin=duration;
if (duration>_connectionsDurationMax)
_connectionsDurationMax=duration;
if (_connectionsRequestsMin==0 || requests<_connectionsRequestsMin)
_connectionsRequestsMin=requests;
if (requests>_connectionsRequestsMax)
_connectionsRequestsMax=requests;
}
}
}
/* ------------------------------------------------------------ */
/**
* @return the acceptorPriority
*/
public int getAcceptorPriorityOffset()
{
return _acceptorPriorityOffset;
}
/* ------------------------------------------------------------ */
/**
* Set the priority offset of the acceptor threads. The priority is adjusted by
* this amount (default 0) to either favour the acceptance of new threads and newly active
* connections or to favour the handling of already dispatched connections.
* @param offset the amount to alter the priority of the acceptor threads.
*/
public void setAcceptorPriorityOffset(int offset)
{
_acceptorPriorityOffset=offset;
}
/* ------------------------------------------------------------ */
/**
* @return True if the the server socket will be opened in SO_REUSEADDR mode.
*/
public boolean getReuseAddress()
{
return _reuseAddress;
}
/* ------------------------------------------------------------ */
/**
* @param reuseAddress True if the the server socket will be opened in SO_REUSEADDR mode.
*/
public void setReuseAddress(boolean reuseAddress)
{
_reuseAddress=reuseAddress;
}
/* ------------------------------------------------------------ */
public boolean isLowResources()
{
if (_threadPool!=null)
return _threadPool.isLowOnThreads();
return _server.getThreadPool().isLowOnThreads();
}
}
| false | true | public void run()
{
Thread current = Thread.currentThread();
synchronized(AbstractConnector.this)
{
if (_acceptorThread==null)
return;
_acceptorThread[_acceptor]=current;
}
String name =_acceptorThread[_acceptor].getName();
current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this);
int old_priority=current.getPriority();
try
{
current.setPriority(old_priority-_acceptorPriorityOffset);
while (isRunning() && getConnection()!=null)
{
try
{
accept(_acceptor);
}
catch(EofException e)
{
Log.ignore(e);
}
catch(IOException e)
{
Log.ignore(e);
}
catch(ThreadDeath e)
{
Log.warn(e);
throw e;
}
catch(Throwable e)
{
Log.warn(e);
}
}
}
finally
{
current.setPriority(old_priority);
current.setName(name);
try
{
if (_acceptor==0)
close();
}
catch (IOException e)
{
Log.warn(e);
}
synchronized(AbstractConnector.this)
{
if (_acceptorThread!=null)
_acceptorThread[_acceptor]=null;
}
}
}
| public void run()
{
Thread current = Thread.currentThread();
synchronized(AbstractConnector.this)
{
if (_acceptorThread==null)
return;
_acceptorThread[_acceptor]=current;
String name =_acceptorThread[_acceptor].getName();
current.setName(name+" - Acceptor"+_acceptor+" "+AbstractConnector.this);
}
int old_priority=current.getPriority();
try
{
current.setPriority(old_priority-_acceptorPriorityOffset);
while (isRunning() && getConnection()!=null)
{
try
{
accept(_acceptor);
}
catch(EofException e)
{
Log.ignore(e);
}
catch(IOException e)
{
Log.ignore(e);
}
catch(ThreadDeath e)
{
Log.warn(e);
throw e;
}
catch(Throwable e)
{
Log.warn(e);
}
}
}
finally
{
current.setPriority(old_priority);
current.setName(name);
try
{
if (_acceptor==0)
close();
}
catch (IOException e)
{
Log.warn(e);
}
synchronized(AbstractConnector.this)
{
if (_acceptorThread!=null)
_acceptorThread[_acceptor]=null;
}
}
}
|
diff --git a/core/src/main/java/org/mobicents/media/core/connections/LocalConnectionImpl.java b/core/src/main/java/org/mobicents/media/core/connections/LocalConnectionImpl.java
index f0f9727e3..84ae06d52 100644
--- a/core/src/main/java/org/mobicents/media/core/connections/LocalConnectionImpl.java
+++ b/core/src/main/java/org/mobicents/media/core/connections/LocalConnectionImpl.java
@@ -1,155 +1,156 @@
/*
* JBoss, Home of Professional Open Source
* Copyright 2011, Red Hat, Inc. 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.mobicents.media.core.connections;
import java.io.IOException;
import org.mobicents.media.server.spi.Connection;
import org.mobicents.media.server.spi.ConnectionMode;
import org.mobicents.media.server.spi.ConnectionType;
import org.mobicents.media.server.spi.MediaType;
import org.mobicents.media.server.spi.ModeNotSupportedException;
import org.mobicents.media.server.spi.ConnectionFailureListener;
import org.mobicents.media.server.component.audio.AudioComponent;
import org.mobicents.media.server.component.oob.OOBComponent;
import org.mobicents.media.server.impl.rtp.ChannelsManager;
import org.mobicents.media.server.impl.rtp.LocalDataChannel;
import org.mobicents.media.server.utils.Text;
/**
*
* @author yulian oifa
*/
public class LocalConnectionImpl extends BaseConnection {
private LocalDataChannel localAudioChannel;
public LocalConnectionImpl(String id,ChannelsManager channelsManager) {
super(id,channelsManager.getScheduler());
this.localAudioChannel=channelsManager.getLocalChannel();
}
public AudioComponent getAudioComponent()
{
return this.localAudioChannel.getAudioComponent();
}
public OOBComponent getOOBComponent()
{
return this.localAudioChannel.getOOBComponent();
}
@Override
public void setOtherParty(Connection other) throws IOException {
if (!(other instanceof LocalConnectionImpl)) {
throw new IOException("Not compatible");
}
this.localAudioChannel.join(((LocalConnectionImpl)other).localAudioChannel);
try {
- join();
+ join();
+ ((LocalConnectionImpl)other).join();
} catch (Exception e) {
throw new IOException(e);
}
}
public void setOtherParty(Text descriptor) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
public void setOtherParty(byte[] descriptor) throws IOException {
throw new UnsupportedOperationException("Not supported yet.");
}
public long getPacketsReceived() {
return 0;
}
public long getBytesReceived() {
return 0;
}
public long getPacketsTransmitted() {
return 0;
}
public long getBytesTransmitted() {
return 0;
}
public String toString() {
return "Local Connection [" + getId() + "]";
}
public double getJitter() {
return 0;
}
@Override
public void setConnectionFailureListener(ConnectionFailureListener connectionListener)
{
//currently used only in RTP Connection
}
@Override
protected void onCreated() throws Exception {
//descriptor = template.getSDP("127.0.0.1", "LOCAL", "ENP", getEndpoint().getLocalName(), 0, 0);
}
@Override
protected void onFailed() {
try {
setMode(ConnectionMode.INACTIVE);
} catch (ModeNotSupportedException e) {
}
this.localAudioChannel.unjoin();
//release connection
releaseConnection(ConnectionType.LOCAL);
}
@Override
public void setMode(ConnectionMode mode) throws ModeNotSupportedException {
localAudioChannel.updateMode(mode);
super.setMode(mode);
}
@Override
protected void onOpened() throws Exception {
}
@Override
protected void onClosed() {
try {
setMode(ConnectionMode.INACTIVE);
} catch (ModeNotSupportedException e) {
}
this.localAudioChannel.unjoin();
//release connection
releaseConnection(ConnectionType.LOCAL);
}
}
| true | true | public void setOtherParty(Connection other) throws IOException {
if (!(other instanceof LocalConnectionImpl)) {
throw new IOException("Not compatible");
}
this.localAudioChannel.join(((LocalConnectionImpl)other).localAudioChannel);
try {
join();
} catch (Exception e) {
throw new IOException(e);
}
}
| public void setOtherParty(Connection other) throws IOException {
if (!(other instanceof LocalConnectionImpl)) {
throw new IOException("Not compatible");
}
this.localAudioChannel.join(((LocalConnectionImpl)other).localAudioChannel);
try {
join();
((LocalConnectionImpl)other).join();
} catch (Exception e) {
throw new IOException(e);
}
}
|
diff --git a/src/main/java/com/github/ucchyocean/et/ExpTimer.java b/src/main/java/com/github/ucchyocean/et/ExpTimer.java
index c1cbc0f..289f62c 100644
--- a/src/main/java/com/github/ucchyocean/et/ExpTimer.java
+++ b/src/main/java/com/github/ucchyocean/et/ExpTimer.java
@@ -1,355 +1,355 @@
/*
* @author ucchy
* @license LGPLv3
* @copyright Copyright ucchy 2013
*/
package com.github.ucchyocean.et;
import java.io.File;
import java.util.HashMap;
import org.bukkit.Bukkit;
import org.bukkit.ChatColor;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.configuration.ConfigurationSection;
import org.bukkit.configuration.file.FileConfiguration;
import org.bukkit.entity.Player;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import org.bukkit.event.entity.PlayerDeathEvent;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.scheduler.BukkitTask;
/**
* 経験値タイマー
* @author ucchy
*/
public class ExpTimer extends JavaPlugin implements Listener {
private static ExpTimer instance;
private TimerTask runnable;
private BukkitTask task;
protected static ETConfigData config;
protected static HashMap<String, ETConfigData> configs;
private String currentConfigName;
/**
* @see org.bukkit.plugin.java.JavaPlugin#onEnable()
*/
@Override
public void onEnable() {
instance = this;
// コンフィグのロード
reloadConfigData();
// メッセージの初期化
Messages.initialize(null);
// イベントの登録
getServer().getPluginManager().registerEvents(this, this);
// ColorTeaming のロード
if ( getServer().getPluginManager().isPluginEnabled("ColorTeaming") ) {
Plugin temp = getServer().getPluginManager().getPlugin("ColorTeaming");
String ctversion = temp.getDescription().getVersion();
if ( Utility.isUpperVersion(ctversion, "2.2.0") ) {
getLogger().info("ColorTeaming がロードされました。連携機能を有効にします。");
getServer().getPluginManager().registerEvents(
new ColorTeamingListener(this), this);
} else {
getLogger().warning("ColorTeaming のバージョンが古いため、連携機能は無効になりました。");
getLogger().warning("連携機能を使用するには、ColorTeaming v2.2.0 以上が必要です。");
}
}
}
/**
* @see org.bukkit.plugin.java.JavaPlugin#onDisable()
*/
@Override
public void onDisable() {
// タスクが残ったままなら、強制終了しておく。
if ( runnable != null ) {
getLogger().warning("タイマーが残ったままです。強制終了します。");
getServer().getScheduler().cancelTask(task.getTaskId());
runnable = null;
}
}
/**
* @see org.bukkit.plugin.java.JavaPlugin#onCommand(org.bukkit.command.CommandSender, org.bukkit.command.Command, java.lang.String, java.lang.String[])
*/
@Override
public boolean onCommand(
CommandSender sender, Command command, String label, String[] args) {
// 引数がない場合は実行しない
if ( args.length <= 0 ) {
return false;
}
if ( args[0].equalsIgnoreCase("start") ) {
// タイマーをスタートする
if ( runnable == null ) {
if ( args.length == 1 ) {
config = configs.get("default").clone();
} else if ( args.length >= 2 ) {
if ( args[1].matches("^[0-9]+$") ) {
config = configs.get("default").clone();
config.seconds = Integer.parseInt(args[1]);
if ( args.length >= 3 && args[2].matches("^[0-9]+$")) {
config.readySeconds = Integer.parseInt(args[2]);
}
} else {
if ( !configs.containsKey(args[1]) ) {
sender.sendMessage(ChatColor.RED +
String.format("設定 %s が見つかりません!", args[1]));
return true;
}
config = configs.get(args[1]).clone();
}
}
// configからメッセージのリロード
Messages.initialize(config.messageFileName);
startNewTask(null);
sender.sendMessage(ChatColor.GRAY + "タイマーを新規に開始しました。");
return true;
} else {
runnable.startFromPause();
sender.sendMessage(ChatColor.GRAY + "タイマーを再開しました。");
return true;
}
} else if ( args[0].equalsIgnoreCase("pause") ) {
// タイマーを一時停止する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
if ( !runnable.isPaused() ) {
runnable.pause();
sender.sendMessage(ChatColor.GRAY + "タイマーを一時停止しました。");
return true;
} else {
- sender.sendMessage(ChatColor.GRAY + "タイマーを一時停止しました。");
+ sender.sendMessage(ChatColor.RED + "タイマーは既に一時停止状態です!");
return true;
}
} else if ( args[0].equalsIgnoreCase("end") ) {
// タイマーを強制終了する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
endTask();
if ( config.useExpBar )
setExpLevel(0, 1);
sender.sendMessage(ChatColor.GRAY + "タイマーを停止しました。");
return true;
} else if ( args[0].equalsIgnoreCase("cancel") ) {
// タイマーを強制終了する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
cancelTask();
if ( config.useExpBar )
setExpLevel(0, 1);
sender.sendMessage(ChatColor.GRAY + "タイマーを強制停止しました。");
return true;
} else if ( args[0].equalsIgnoreCase("status") ) {
// ステータスを参照する
String stat;
if ( runnable == null ) {
stat = "タイマー停止中";
} else {
stat = runnable.getStatusDescription();
}
sender.sendMessage(ChatColor.GRAY + "----- ExpTimer information -----");
sender.sendMessage(ChatColor.GRAY + "現在の状況:" +
ChatColor.WHITE + stat);
sender.sendMessage(ChatColor.GRAY + "現在の設定名:" + currentConfigName);
sender.sendMessage(ChatColor.GRAY + "開始時に実行するコマンド:");
for ( String com : config.commandsOnStart ) {
sender.sendMessage(ChatColor.WHITE + " " + com);
}
sender.sendMessage(ChatColor.GRAY + "終了時に実行するコマンド:");
for ( String com : config.commandsOnEnd ) {
sender.sendMessage(ChatColor.WHITE + " " + com);
}
sender.sendMessage(ChatColor.GRAY + "--------------------------------");
return true;
} else if ( args[0].equalsIgnoreCase("reload") ) {
// config.yml をリロードする
reloadConfigData();
sender.sendMessage(ChatColor.GRAY + "config.yml をリロードしました。");
return true;
}
return false;
}
/**
* config.yml を再読み込みする
*/
protected void reloadConfigData() {
saveDefaultConfig();
reloadConfig();
FileConfiguration config = getConfig();
ExpTimer.configs = new HashMap<String, ETConfigData>();
// デフォルトのデータ読み込み
ConfigurationSection section = config.getConfigurationSection("default");
ETConfigData defaultData = ETConfigData.loadFromSection(section, null);
ExpTimer.config = defaultData;
ExpTimer.configs.put("default", defaultData);
currentConfigName = "default";
// デフォルト以外のデータ読み込み
for ( String key : config.getKeys(false) ) {
if ( key.equals("default") ) {
continue;
}
section = config.getConfigurationSection(key);
ETConfigData data = ETConfigData.loadFromSection(section, defaultData);
ExpTimer.configs.put(key, data);
}
}
/**
* 全プレイヤーの経験値レベルを設定する
* @param level 設定するレベル
*/
protected static void setExpLevel(int level, int max) {
float progress = (float)level / (float)max;
if ( progress > 1.0f ) {
progress = 1.0f;
} else if ( progress < 0.0f ) {
progress = 0.0f;
}
if ( level > 24000 ) {
level = 24000;
} else if ( level < 0 ) {
level = 0;
}
Player[] players = instance.getServer().getOnlinePlayers();
for ( Player player : players ) {
player.setLevel(level);
player.setExp(progress);
}
}
/**
* 新しいタスクを開始する
* @param configName コンフィグ名、nullならそのままconfigを変更せずにタスクを開始する
*/
protected void startNewTask(String configName) {
if ( configName != null && configs.containsKey(configName) ) {
config = configs.get(configName).clone();
Messages.initialize(config.messageFileName);
currentConfigName = configName;
}
runnable = new TimerTask(this, config.readySeconds, config.seconds);
task = getServer().getScheduler().runTaskTimer(this, runnable, 20, 20);
}
/**
* 現在実行中のタスクを中断する。終了時のコマンドは実行されない。
*/
protected void cancelTask() {
if ( runnable != null ) {
getServer().getScheduler().cancelTask(task.getTaskId());
runnable = null;
task = null;
}
}
/**
* 現在実行中のタスクを終了コマンドを実行してから終了する
*/
protected void endTask() {
if ( runnable != null ) {
// 終了コマンドの実行
for ( String c : config.commandsOnEnd ) {
if ( c.startsWith("/") ) {
c = c.substring(1); // スラッシュ削除
}
Bukkit.dispatchCommand(Bukkit.getConsoleSender(), c);
}
getServer().getScheduler().cancelTask(task.getTaskId());
runnable = null;
task = null;
}
}
/**
* 現在のタイマータスクを取得する
* @return タスク
*/
public TimerTask getTask() {
return runnable;
}
/**
* プラグインのデータフォルダを返す
* @return プラグインのデータフォルダ
*/
protected static File getConfigFolder() {
return instance.getDataFolder();
}
/**
* プラグインのJarファイル自体を示すFileオブジェクトを返す
* @return プラグインのJarファイル
*/
protected static File getPluginJarFile() {
return instance.getFile();
}
/**
* プレイヤー死亡時に呼び出されるメソッド
* @param event
*/
@EventHandler
public void onPlayerDeath(PlayerDeathEvent event) {
// タイマー起動中の死亡は、経験値を落とさない
if ( runnable != null )
event.setDroppedExp(0);
}
}
| true | true | public boolean onCommand(
CommandSender sender, Command command, String label, String[] args) {
// 引数がない場合は実行しない
if ( args.length <= 0 ) {
return false;
}
if ( args[0].equalsIgnoreCase("start") ) {
// タイマーをスタートする
if ( runnable == null ) {
if ( args.length == 1 ) {
config = configs.get("default").clone();
} else if ( args.length >= 2 ) {
if ( args[1].matches("^[0-9]+$") ) {
config = configs.get("default").clone();
config.seconds = Integer.parseInt(args[1]);
if ( args.length >= 3 && args[2].matches("^[0-9]+$")) {
config.readySeconds = Integer.parseInt(args[2]);
}
} else {
if ( !configs.containsKey(args[1]) ) {
sender.sendMessage(ChatColor.RED +
String.format("設定 %s が見つかりません!", args[1]));
return true;
}
config = configs.get(args[1]).clone();
}
}
// configからメッセージのリロード
Messages.initialize(config.messageFileName);
startNewTask(null);
sender.sendMessage(ChatColor.GRAY + "タイマーを新規に開始しました。");
return true;
} else {
runnable.startFromPause();
sender.sendMessage(ChatColor.GRAY + "タイマーを再開しました。");
return true;
}
} else if ( args[0].equalsIgnoreCase("pause") ) {
// タイマーを一時停止する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
if ( !runnable.isPaused() ) {
runnable.pause();
sender.sendMessage(ChatColor.GRAY + "タイマーを一時停止しました。");
return true;
} else {
sender.sendMessage(ChatColor.GRAY + "タイマーを一時停止しました。");
return true;
}
} else if ( args[0].equalsIgnoreCase("end") ) {
// タイマーを強制終了する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
endTask();
if ( config.useExpBar )
setExpLevel(0, 1);
sender.sendMessage(ChatColor.GRAY + "タイマーを停止しました。");
return true;
} else if ( args[0].equalsIgnoreCase("cancel") ) {
// タイマーを強制終了する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
cancelTask();
if ( config.useExpBar )
setExpLevel(0, 1);
sender.sendMessage(ChatColor.GRAY + "タイマーを強制停止しました。");
return true;
} else if ( args[0].equalsIgnoreCase("status") ) {
// ステータスを参照する
String stat;
if ( runnable == null ) {
stat = "タイマー停止中";
} else {
stat = runnable.getStatusDescription();
}
sender.sendMessage(ChatColor.GRAY + "----- ExpTimer information -----");
sender.sendMessage(ChatColor.GRAY + "現在の状況:" +
ChatColor.WHITE + stat);
sender.sendMessage(ChatColor.GRAY + "現在の設定名:" + currentConfigName);
sender.sendMessage(ChatColor.GRAY + "開始時に実行するコマンド:");
for ( String com : config.commandsOnStart ) {
sender.sendMessage(ChatColor.WHITE + " " + com);
}
sender.sendMessage(ChatColor.GRAY + "終了時に実行するコマンド:");
for ( String com : config.commandsOnEnd ) {
sender.sendMessage(ChatColor.WHITE + " " + com);
}
sender.sendMessage(ChatColor.GRAY + "--------------------------------");
return true;
} else if ( args[0].equalsIgnoreCase("reload") ) {
// config.yml をリロードする
reloadConfigData();
sender.sendMessage(ChatColor.GRAY + "config.yml をリロードしました。");
return true;
}
return false;
}
| public boolean onCommand(
CommandSender sender, Command command, String label, String[] args) {
// 引数がない場合は実行しない
if ( args.length <= 0 ) {
return false;
}
if ( args[0].equalsIgnoreCase("start") ) {
// タイマーをスタートする
if ( runnable == null ) {
if ( args.length == 1 ) {
config = configs.get("default").clone();
} else if ( args.length >= 2 ) {
if ( args[1].matches("^[0-9]+$") ) {
config = configs.get("default").clone();
config.seconds = Integer.parseInt(args[1]);
if ( args.length >= 3 && args[2].matches("^[0-9]+$")) {
config.readySeconds = Integer.parseInt(args[2]);
}
} else {
if ( !configs.containsKey(args[1]) ) {
sender.sendMessage(ChatColor.RED +
String.format("設定 %s が見つかりません!", args[1]));
return true;
}
config = configs.get(args[1]).clone();
}
}
// configからメッセージのリロード
Messages.initialize(config.messageFileName);
startNewTask(null);
sender.sendMessage(ChatColor.GRAY + "タイマーを新規に開始しました。");
return true;
} else {
runnable.startFromPause();
sender.sendMessage(ChatColor.GRAY + "タイマーを再開しました。");
return true;
}
} else if ( args[0].equalsIgnoreCase("pause") ) {
// タイマーを一時停止する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
if ( !runnable.isPaused() ) {
runnable.pause();
sender.sendMessage(ChatColor.GRAY + "タイマーを一時停止しました。");
return true;
} else {
sender.sendMessage(ChatColor.RED + "タイマーは既に一時停止状態です!");
return true;
}
} else if ( args[0].equalsIgnoreCase("end") ) {
// タイマーを強制終了する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
endTask();
if ( config.useExpBar )
setExpLevel(0, 1);
sender.sendMessage(ChatColor.GRAY + "タイマーを停止しました。");
return true;
} else if ( args[0].equalsIgnoreCase("cancel") ) {
// タイマーを強制終了する
if ( runnable == null ) {
sender.sendMessage(ChatColor.RED + "タイマーが開始されていません!");
return true;
}
cancelTask();
if ( config.useExpBar )
setExpLevel(0, 1);
sender.sendMessage(ChatColor.GRAY + "タイマーを強制停止しました。");
return true;
} else if ( args[0].equalsIgnoreCase("status") ) {
// ステータスを参照する
String stat;
if ( runnable == null ) {
stat = "タイマー停止中";
} else {
stat = runnable.getStatusDescription();
}
sender.sendMessage(ChatColor.GRAY + "----- ExpTimer information -----");
sender.sendMessage(ChatColor.GRAY + "現在の状況:" +
ChatColor.WHITE + stat);
sender.sendMessage(ChatColor.GRAY + "現在の設定名:" + currentConfigName);
sender.sendMessage(ChatColor.GRAY + "開始時に実行するコマンド:");
for ( String com : config.commandsOnStart ) {
sender.sendMessage(ChatColor.WHITE + " " + com);
}
sender.sendMessage(ChatColor.GRAY + "終了時に実行するコマンド:");
for ( String com : config.commandsOnEnd ) {
sender.sendMessage(ChatColor.WHITE + " " + com);
}
sender.sendMessage(ChatColor.GRAY + "--------------------------------");
return true;
} else if ( args[0].equalsIgnoreCase("reload") ) {
// config.yml をリロードする
reloadConfigData();
sender.sendMessage(ChatColor.GRAY + "config.yml をリロードしました。");
return true;
}
return false;
}
|
diff --git a/nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/walker/DefaultWalker.java b/nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/walker/DefaultWalker.java
index 4e7fc07b8..ab664ba82 100644
--- a/nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/walker/DefaultWalker.java
+++ b/nexus/nexus-proxy/src/main/java/org/sonatype/nexus/proxy/walker/DefaultWalker.java
@@ -1,371 +1,371 @@
/**
* 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.walker;
import java.util.Collection;
import org.codehaus.plexus.component.annotations.Component;
import org.codehaus.plexus.logging.AbstractLogEnabled;
import org.sonatype.nexus.proxy.AccessDeniedException;
import org.sonatype.nexus.proxy.IllegalOperationException;
import org.sonatype.nexus.proxy.ItemNotFoundException;
import org.sonatype.nexus.proxy.StorageException;
import org.sonatype.nexus.proxy.item.RepositoryItemUid;
import org.sonatype.nexus.proxy.item.StorageCollectionItem;
import org.sonatype.nexus.proxy.item.StorageItem;
/**
* The Class Walker.
*
* @author cstamas
*/
@Component( role = Walker.class )
public class DefaultWalker
extends AbstractLogEnabled
implements Walker
{
public static final String WALKER_WALKED_COLLECTION_COUNT = Walker.class.getSimpleName() + ".collCount";
public static final String WALKER_WALKED_FROM_PATH = Walker.class.getSimpleName() + ".fromPath";
public void walk( WalkerContext context )
throws WalkerException
{
String fromPath = context.getResourceStoreRequest().getRequestPath();
if ( fromPath == null )
{
fromPath = RepositoryItemUid.PATH_ROOT;
}
context.getContext().put( WALKER_WALKED_FROM_PATH, fromPath );
if ( getLogger().isDebugEnabled() )
{
getLogger().debug(
"Start walking on ResourceStore " + context.getRepository().getId() + " from path '" + fromPath + "'." );
}
// user may call stop()
beforeWalk( context );
if ( context.isStopped() )
{
reportWalkEnd( context, fromPath );
return;
}
StorageItem item = null;
try
{
- item = context.getRepository().retrieveItem( context.getResourceStoreRequest() );
+ item = context.getRepository().retrieveItem( true, context.getResourceStoreRequest() );
}
catch ( ItemNotFoundException ex )
{
if ( getLogger().isDebugEnabled() )
{
getLogger().debug( "ItemNotFound where walking should start, bailing out.", ex );
}
context.stop( ex );
reportWalkEnd( context, fromPath );
return;
}
catch ( Exception ex )
{
getLogger().warn( "Got exception while doing retrieve, bailing out.", ex );
context.stop( ex );
reportWalkEnd( context, fromPath );
return;
}
int collCount = 0;
if ( StorageCollectionItem.class.isAssignableFrom( item.getClass() ) )
{
try
{
WalkerFilter filter = context.getFilter() != null
? context.getFilter()
: new AffirmativeStoreWalkerFilter();
collCount = walkRecursive( 0, context, filter, (StorageCollectionItem) item );
context.getContext().put( WALKER_WALKED_COLLECTION_COUNT, collCount );
}
catch ( Throwable e )
{
context.stop( e );
reportWalkEnd( context, fromPath );
return;
}
}
if ( !context.isStopped() )
{
afterWalk( context );
}
reportWalkEnd( context, fromPath );
}
protected void reportWalkEnd( WalkerContext context, String fromPath )
throws WalkerException
{
if ( context.isStopped() )
{
// we have a cause, report any non-ItemNotFounds with stack trace
if ( context.getStopCause() instanceof ItemNotFoundException )
{
getLogger().info(
"Aborted walking on repository ID='" + context.getRepository().getId() + "' from path='"
+ fromPath + "', cause: " + context.getStopCause().getMessage() );
}
else
{
getLogger().info(
"Aborted walking on repository ID='" + context.getRepository().getId() + "' from path='" + fromPath
+ "', cause:",
context.getStopCause() );
}
throw new WalkerException( context, "Aborted walking on repository ID='" + context.getRepository().getId()
+ "' from path='" + fromPath + "'." );
}
else
{
// regular finish, it was not stopped
if ( getLogger().isDebugEnabled() )
{
getLogger().debug(
"Finished walking on ResourceStore '" + context.getRepository().getId() + "' from path '"
+ context.getContext().get( WALKER_WALKED_FROM_PATH ) + "'." );
}
}
}
protected final int walkRecursive( int collCount, WalkerContext context, WalkerFilter filter,
StorageCollectionItem coll )
throws AccessDeniedException,
IllegalOperationException,
ItemNotFoundException,
StorageException
{
if ( context.isStopped() )
{
return collCount;
}
boolean shouldProcess = filter.shouldProcess( context, coll );
boolean shouldProcessRecursively = filter.shouldProcessRecursively( context, coll );
if ( !shouldProcess && !shouldProcessRecursively )
{
return collCount;
}
// user may call stop()
if ( shouldProcess )
{
onCollectionEnter( context, coll );
collCount++;
}
if ( context.isStopped() )
{
return collCount;
}
// user may call stop()
if ( shouldProcess )
{
processItem( context, coll );
}
if ( context.isStopped() )
{
return collCount;
}
Collection<StorageItem> ls = null;
if ( shouldProcessRecursively )
{
ls = context.getRepository().list( false, coll );
for ( StorageItem i : ls )
{
if ( !context.isCollectionsOnly() && !StorageCollectionItem.class.isAssignableFrom( i.getClass() ) )
{
if ( filter.shouldProcess( context, i ) )
{
// user may call stop()
processItem( context, i );
}
if ( context.isStopped() )
{
return collCount;
}
}
if ( StorageCollectionItem.class.isAssignableFrom( i.getClass() ) )
{
// user may call stop()
collCount = walkRecursive( collCount, context, filter, (StorageCollectionItem) i );
if ( context.isStopped() )
{
return collCount;
}
}
}
}
// user may call stop()
if ( shouldProcess )
{
onCollectionExit( context, coll );
}
return collCount;
}
protected void beforeWalk( WalkerContext context )
{
try
{
for ( WalkerProcessor processor : context.getProcessors() )
{
if ( processor.isActive() )
{
processor.beforeWalk( context );
if ( context.isStopped() )
{
break;
}
}
}
}
catch ( Exception e )
{
context.stop( e );
}
}
protected void onCollectionEnter( WalkerContext context, StorageCollectionItem coll )
{
try
{
for ( WalkerProcessor processor : context.getProcessors() )
{
if ( processor.isActive() )
{
processor.onCollectionEnter( context, coll );
if ( context.isStopped() )
{
break;
}
}
}
}
catch ( Exception e )
{
context.stop( e );
}
}
protected void processItem( WalkerContext context, StorageItem item )
{
try
{
for ( WalkerProcessor processor : context.getProcessors() )
{
if ( processor.isActive() )
{
processor.processItem( context, item );
if ( context.isStopped() )
{
break;
}
}
}
}
catch ( Exception e )
{
context.stop( e );
}
}
protected void onCollectionExit( WalkerContext context, StorageCollectionItem coll )
{
try
{
for ( WalkerProcessor processor : context.getProcessors() )
{
if ( processor.isActive() )
{
processor.onCollectionExit( context, coll );
if ( context.isStopped() )
{
break;
}
}
}
}
catch ( Exception e )
{
context.stop( e );
}
}
protected void afterWalk( WalkerContext context )
{
try
{
for ( WalkerProcessor processor : context.getProcessors() )
{
if ( processor.isActive() )
{
processor.afterWalk( context );
if ( context.isStopped() )
{
break;
}
}
}
}
catch ( Exception e )
{
context.stop( e );
}
}
}
| true | true | public void walk( WalkerContext context )
throws WalkerException
{
String fromPath = context.getResourceStoreRequest().getRequestPath();
if ( fromPath == null )
{
fromPath = RepositoryItemUid.PATH_ROOT;
}
context.getContext().put( WALKER_WALKED_FROM_PATH, fromPath );
if ( getLogger().isDebugEnabled() )
{
getLogger().debug(
"Start walking on ResourceStore " + context.getRepository().getId() + " from path '" + fromPath + "'." );
}
// user may call stop()
beforeWalk( context );
if ( context.isStopped() )
{
reportWalkEnd( context, fromPath );
return;
}
StorageItem item = null;
try
{
item = context.getRepository().retrieveItem( context.getResourceStoreRequest() );
}
catch ( ItemNotFoundException ex )
{
if ( getLogger().isDebugEnabled() )
{
getLogger().debug( "ItemNotFound where walking should start, bailing out.", ex );
}
context.stop( ex );
reportWalkEnd( context, fromPath );
return;
}
catch ( Exception ex )
{
getLogger().warn( "Got exception while doing retrieve, bailing out.", ex );
context.stop( ex );
reportWalkEnd( context, fromPath );
return;
}
int collCount = 0;
if ( StorageCollectionItem.class.isAssignableFrom( item.getClass() ) )
{
try
{
WalkerFilter filter = context.getFilter() != null
? context.getFilter()
: new AffirmativeStoreWalkerFilter();
collCount = walkRecursive( 0, context, filter, (StorageCollectionItem) item );
context.getContext().put( WALKER_WALKED_COLLECTION_COUNT, collCount );
}
catch ( Throwable e )
{
context.stop( e );
reportWalkEnd( context, fromPath );
return;
}
}
if ( !context.isStopped() )
{
afterWalk( context );
}
reportWalkEnd( context, fromPath );
}
| public void walk( WalkerContext context )
throws WalkerException
{
String fromPath = context.getResourceStoreRequest().getRequestPath();
if ( fromPath == null )
{
fromPath = RepositoryItemUid.PATH_ROOT;
}
context.getContext().put( WALKER_WALKED_FROM_PATH, fromPath );
if ( getLogger().isDebugEnabled() )
{
getLogger().debug(
"Start walking on ResourceStore " + context.getRepository().getId() + " from path '" + fromPath + "'." );
}
// user may call stop()
beforeWalk( context );
if ( context.isStopped() )
{
reportWalkEnd( context, fromPath );
return;
}
StorageItem item = null;
try
{
item = context.getRepository().retrieveItem( true, context.getResourceStoreRequest() );
}
catch ( ItemNotFoundException ex )
{
if ( getLogger().isDebugEnabled() )
{
getLogger().debug( "ItemNotFound where walking should start, bailing out.", ex );
}
context.stop( ex );
reportWalkEnd( context, fromPath );
return;
}
catch ( Exception ex )
{
getLogger().warn( "Got exception while doing retrieve, bailing out.", ex );
context.stop( ex );
reportWalkEnd( context, fromPath );
return;
}
int collCount = 0;
if ( StorageCollectionItem.class.isAssignableFrom( item.getClass() ) )
{
try
{
WalkerFilter filter = context.getFilter() != null
? context.getFilter()
: new AffirmativeStoreWalkerFilter();
collCount = walkRecursive( 0, context, filter, (StorageCollectionItem) item );
context.getContext().put( WALKER_WALKED_COLLECTION_COUNT, collCount );
}
catch ( Throwable e )
{
context.stop( e );
reportWalkEnd( context, fromPath );
return;
}
}
if ( !context.isStopped() )
{
afterWalk( context );
}
reportWalkEnd( context, fromPath );
}
|
diff --git a/feeder-sns-parent/feeder-sns-twitter/src/main/java/org/komusubi/feeder/sns/twitter/Twitter4j.java b/feeder-sns-parent/feeder-sns-twitter/src/main/java/org/komusubi/feeder/sns/twitter/Twitter4j.java
index 91b8b7c..b84808d 100644
--- a/feeder-sns-parent/feeder-sns-twitter/src/main/java/org/komusubi/feeder/sns/twitter/Twitter4j.java
+++ b/feeder-sns-parent/feeder-sns-twitter/src/main/java/org/komusubi/feeder/sns/twitter/Twitter4j.java
@@ -1,112 +1,112 @@
/*
* 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.komusubi.feeder.sns.twitter;
import org.komusubi.feeder.model.Message;
import org.komusubi.feeder.model.Message.Script;
import org.komusubi.feeder.model.Topic;
import org.komusubi.feeder.model.Topics;
import org.komusubi.feeder.sns.History;
import org.komusubi.feeder.sns.SocialNetwork;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import twitter4j.Status;
import twitter4j.StatusUpdate;
import twitter4j.Twitter;
import twitter4j.TwitterException;
import twitter4j.TwitterFactory;
/**
* @author jun.ozeki
*/
public class Twitter4j implements SocialNetwork {
private static final Logger logger = LoggerFactory.getLogger(Twitter4j.class);
private Twitter twitter;
private boolean outputConsole = Boolean.getBoolean("tweet.console");
/**
* create new instance.
*/
public Twitter4j() {
this(TwitterFactory.getSingleton());
}
/**
* create new instance for unit test
* @param twitter
*/
// package
Twitter4j(Twitter twitter) {
this.twitter = twitter;
}
/**
* @see org.komusubi.feeder.sns.SocialNetwork#post(org.komusubi.feeder.model.Message)
*/
@Override
public void post(Message message) {
tweet(message);
}
/**
* @see org.komusubi.feeder.sns.SocialNetwork#post(Topic topic)
*/
@Override
public void post(Topic topic) {
tweet(topic.message());
}
@Override
public void post(Topics<? extends Topic> topics) {
for (Topic t: topics)
post(t);
}
/**
* tweet.
* @param message
*/
public void tweet(Message message) {
try {
for (Script script: message) {
- logger.info("script codepoint length: {}", script.codePointCount());
if (outputConsole) {
System.out.printf("tweet: %s%n", script.trimedLine());
} else {
StatusUpdate status = new StatusUpdate(script.trimedLine());
+ logger.info("tweet : {}", status.getStatus());
Status result = twitter.updateStatus(status);
- logger.info("tweet: {}", result.getText());
}
+ logger.info("script codepoint length: {}", script.codePointCount());
}
} catch (TwitterException e) {
throw new Twitter4jException(e);
}
}
/**
* @see org.komusubi.feeder.sns.SocialNetwork#history()
*/
@Override
public History history() {
return new TweetHistory(twitter);
}
}
| false | true | public void tweet(Message message) {
try {
for (Script script: message) {
logger.info("script codepoint length: {}", script.codePointCount());
if (outputConsole) {
System.out.printf("tweet: %s%n", script.trimedLine());
} else {
StatusUpdate status = new StatusUpdate(script.trimedLine());
Status result = twitter.updateStatus(status);
logger.info("tweet: {}", result.getText());
}
}
} catch (TwitterException e) {
throw new Twitter4jException(e);
}
}
| public void tweet(Message message) {
try {
for (Script script: message) {
if (outputConsole) {
System.out.printf("tweet: %s%n", script.trimedLine());
} else {
StatusUpdate status = new StatusUpdate(script.trimedLine());
logger.info("tweet : {}", status.getStatus());
Status result = twitter.updateStatus(status);
}
logger.info("script codepoint length: {}", script.codePointCount());
}
} catch (TwitterException e) {
throw new Twitter4jException(e);
}
}
|
diff --git a/src/btwmod/protectedzones/mod_ProtectedZones.java b/src/btwmod/protectedzones/mod_ProtectedZones.java
index 55b20ae..4e3c3fb 100644
--- a/src/btwmod/protectedzones/mod_ProtectedZones.java
+++ b/src/btwmod/protectedzones/mod_ProtectedZones.java
@@ -1,489 +1,490 @@
package btwmod.protectedzones;
import java.util.ArrayList;
import java.util.List;
import java.util.Set;
import net.minecraft.server.MinecraftServer;
import net.minecraft.src.Block;
import net.minecraft.src.BlockButton;
import net.minecraft.src.BlockContainer;
import net.minecraft.src.BlockRail;
import net.minecraft.src.Entity;
import net.minecraft.src.EntityHanging;
import net.minecraft.src.EntityLiving;
import net.minecraft.src.EntityMooshroom;
import net.minecraft.src.EntityPlayer;
import net.minecraft.src.EntityVillager;
import net.minecraft.src.FCBlockBloodMoss;
import net.minecraft.src.FCEntityCanvas;
import net.minecraft.src.Facing;
import net.minecraft.src.Item;
import net.minecraft.src.ItemStack;
import net.minecraft.src.MathHelper;
import net.minecraft.src.ServerCommandManager;
import net.minecraft.src.TileEntity;
import net.minecraft.src.TileEntitySkull;
import net.minecraft.src.World;
import net.minecraft.src.mod_FCBetterThanWolves;
import btwmods.CommandsAPI;
import btwmods.EntityAPI;
import btwmods.IMod;
import btwmods.ModLoader;
import btwmods.PlayerAPI;
import btwmods.Util;
import btwmods.WorldAPI;
import btwmods.entity.EntityEvent;
import btwmods.entity.IEntityListener;
import btwmods.events.APIEvent;
import btwmods.io.Settings;
import btwmods.player.IPlayerActionListener;
import btwmods.player.PlayerActionEvent;
import btwmods.player.PlayerBlockEvent;
import btwmods.player.IPlayerBlockListener;
import btwmods.util.Area;
import btwmods.world.BlockEvent;
import btwmods.world.BlockEventBase;
import btwmods.world.IBlockListener;
public class mod_ProtectedZones implements IMod, IPlayerBlockListener, IBlockListener, IPlayerActionListener, IEntityListener {
public enum ACTION {
DIG, ACTIVATE, EXPLODE, ATTACK_ENTITY, USE_ENTITY,
ITEM_USE_CHECK_EDIT, IS_ENTITY_INVULNERABLE, BURN, IS_FLAMMABLE, FIRE_SPREAD_ATTEMPT, CAN_PUSH, TRAMPLE_FARMLAND
};
private Settings data;
private ProtectedZones[] zonesByDimension;
private CommandZone commandZone;
private MinecraftServer server;
private ServerCommandManager commandManager;
private Set ops;
private boolean alwaysAllowOps = true;
@Override
public String getName() {
return "Protected Zones";
}
@Override
public void init(Settings settings, Settings data) throws Exception {
server = MinecraftServer.getServer();
commandManager = (ServerCommandManager)server.getCommandManager();
PlayerAPI.addListener(this);
WorldAPI.addListener(this);
EntityAPI.addListener(this);
CommandsAPI.registerCommand(commandZone = new CommandZone(this), this);
alwaysAllowOps = settings.getBoolean("alwaysAllowOps", alwaysAllowOps);
ops = server.getConfigurationManager().getOps();
this.data = data;
zonesByDimension = new ProtectedZones[server.worldServers.length];
for (int i = 0; i < server.worldServers.length; i++) {
zonesByDimension[i] = new ProtectedZones();
}
int zoneCount = data.getInt("count", 0);
for (int i = 1; i <= zoneCount; i++) {
if (data.hasSection("zone" + i) && !add(new Zone(data, "zone" + i))) {
ModLoader.outputError(getName() + " failed to load zone " + i + " as it has a duplicate name or has invalid dimensions.");
}
}
}
@Override
public void unload() throws Exception {
PlayerAPI.removeListener(this);
WorldAPI.removeListener(this);
EntityAPI.removeListener(this);
CommandsAPI.unregisterCommand(commandZone);
}
@Override
public IMod getMod() {
return this;
}
public boolean add(Zone zone) {
return zone != null && zonesByDimension[Util.getWorldIndexFromDimension(zone.dimension)].add(zone);
}
public boolean remove(int dimension, String name) {
return name != null && zonesByDimension[Util.getWorldIndexFromDimension(dimension)].removeZone(name);
}
public boolean remove(Zone zone) {
return zone != null && remove(zone.dimension, zone.name);
}
public Zone get(int dimension, String name) {
return zonesByDimension[Util.getWorldIndexFromDimension(dimension)].getZone(name);
}
public List<String> getZoneNames() {
ArrayList names = new ArrayList();
for (ProtectedZones zones : zonesByDimension) {
names.addAll(zones.getZoneNames());
}
return names;
}
public List<String> getZoneNames(int dimension) {
return zonesByDimension[Util.getWorldIndexFromDimension(dimension)].getZoneNames();
}
public static boolean isProtectedBlockType(ACTION action, Block block) {
if (action == ACTION.ACTIVATE) {
if (block instanceof BlockRail)
return false;
if (block == Block.workbench)
return false;
if (block == mod_FCBetterThanWolves.fcAnvil)
return false;
if (block == Block.lever)
return false;
if (block instanceof BlockButton)
return false;
if (block == Block.enderChest)
return false;
if (block == Block.enchantmentTable)
return false;
if (block == Block.bed)
return false;
if (block == mod_FCBetterThanWolves.fcInfernalEnchanter)
return false;
}
return true;
}
public static boolean isProtectedEntityType(ACTION action, Entity entity) {
if (entity instanceof EntityLiving) {
if (entity instanceof EntityVillager && action != ACTION.USE_ENTITY)
return true;
if (entity instanceof EntityMooshroom)
return true;
}
else if (entity instanceof EntityHanging) {
return true;
}
else if (entity instanceof FCEntityCanvas) {
return true;
}
return false;
}
public boolean isOp(String username) {
return ops.contains(username.trim().toLowerCase());
}
public boolean isPlayerGloballyAllowed(String username) {
return alwaysAllowOps && isOp(username);
}
protected boolean isProtectedEntity(ACTION action, EntityPlayer player, Entity entity, int x, int y, int z) {
if (!isProtectedEntityType(action, entity))
return false;
if (player != null && isPlayerGloballyAllowed(player.username))
return false;
List<Area<Zone>> areas = zonesByDimension[Util.getWorldIndexFromDimension(entity.worldObj.provider.dimensionId)].get(x, y, z);
for (Area<Zone> area : areas) {
Zone zone = area.data;
if (zone != null && zone.permissions.protectEntities != Permission.OFF) {
boolean isProtected = true;
if (entity instanceof EntityMooshroom) {
if (zone.permissions.allowMooshroom)
isProtected = false;
else if (player != null && action == ACTION.USE_ENTITY) {
ItemStack heldItem = player.getHeldItem();
if (heldItem != null && heldItem.getItem() == Item.bowlEmpty) {
isProtected = false;
}
}
}
else if (entity instanceof EntityVillager && zone.permissions.allowVillagers) {
isProtected = false;
}
if (isProtected && player != null && zone.permissions.protectEntities == Permission.WHITELIST && zone.whitelist.contains(player.username))
isProtected = false;
if (isProtected) {
if (zone.permissions.sendDebugMessages)
commandManager.notifyAdmins(server, 0, "Protect " + entity.getEntityName() + " " + action + " " + x + "," + y + "," + z + (player == null ? "" : " from " + player.username + " by " + area.data.name + "#" + area.data.getAreaIndex(area)), new Object[0]);
return true;
}
}
}
return false;
}
protected boolean isProtectedBlock(APIEvent event, ACTION action, EntityPlayer player, Block block, World world, int x, int y, int z) {
if (!isProtectedBlockType(action, block))
return false;
if (player != null && isPlayerGloballyAllowed(player.username))
return true;
List<Area<Zone>> areas = zonesByDimension[Util.getWorldIndexFromDimension(world.provider.dimensionId)].get(x, y, z);
for (Area<Zone> area : areas) {
Zone zone = area.data;
ItemStack itemStack = null;
if (zone != null) {
boolean isProtected = false;
switch (action) {
case EXPLODE:
if (zone.permissions.protectExplosions)
isProtected = true;
break;
case IS_FLAMMABLE:
case BURN:
case FIRE_SPREAD_ATTEMPT:
if (zone.permissions.protectBurning)
isProtected = true;
break;
case CAN_PUSH:
// Protect against pistons from outside the area.
if (event instanceof BlockEvent && zone.permissions.protectEdits != Permission.OFF) {
BlockEvent blockEvent = (BlockEvent)event;
isProtected = true;
// Check all areas for the ZoneSettings.
for (Area zoneArea : area.data.areas) {
if (zoneArea.isWithin(blockEvent.getPistonX(), blockEvent.getPistonY(), blockEvent.getPistonZ())) {
isProtected = false;
break;
}
}
}
break;
default:
if (zone.permissions.protectEdits != Permission.OFF) {
isProtected = true;
// Allow immature bloodmoss to be destroyed.
if ((action == ACTION.DIG) && block instanceof FCBlockBloodMoss && event instanceof BlockEventBase && (((BlockEventBase)event).getMetadata() & 7) < 7) {
isProtected = false;
}
if (isProtected && player != null) {
if (isProtected && action == ACTION.ACTIVATE) {
if ((block == Block.doorWood || block == Block.trapdoor || block == Block.fenceGate)
&& zone.isPlayerAllowed(player.username, zone.permissions.allowDoors))
isProtected = false;
else if (block instanceof BlockContainer && zone.isPlayerAllowed(player.username, zone.permissions.allowContainers))
isProtected = false;
}
if (isProtected && zone.permissions.allowOps && isOp(player.username))
isProtected = false;
if (isProtected && action == ACTION.DIG && block == Block.skull && zone.isPlayerAllowed(player.username, zone.permissions.allowHeads)) {
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity instanceof TileEntitySkull) {
TileEntitySkull tileEntitySkull = (TileEntitySkull)tileEntity;
if (tileEntitySkull.getSkullType() == 3 && player.username.equalsIgnoreCase(tileEntitySkull.getExtraType())) {
isProtected = false;
}
}
}
if (isProtected && action == ACTION.ITEM_USE_CHECK_EDIT) {
PlayerBlockEvent playerBlockEvent = (PlayerBlockEvent)event;
if ((itemStack = playerBlockEvent.getItemStack()) != null
&& playerBlockEvent.getDirection() == 1
&& itemStack.getItem() == Item.skull
&& itemStack.getItemDamage() == 3
+ && zone.isPlayerAllowed(player.username, zone.permissions.allowHeads)
&& itemStack.hasTagCompound()
&& itemStack.getTagCompound().hasKey("SkullOwner")
&& player.username.equalsIgnoreCase(itemStack.getTagCompound().getString("SkullOwner"))
&& playerBlockEvent.getBlockId() == 0
&& playerBlockEvent.getY() > 1
&& playerBlockEvent.getWorld().getBlockId(playerBlockEvent.getX(), playerBlockEvent.getY() - 1, playerBlockEvent.getZ()) != 0) {
isProtected = false;
}
}
if (isProtected && zone.permissions.protectEdits == Permission.WHITELIST && zone.whitelist.contains(player.username))
isProtected = false;
}
}
break;
}
if (isProtected) {
if (zone.permissions.sendDebugMessages) {
if (itemStack == null && event instanceof PlayerBlockEvent) {
itemStack = ((PlayerBlockEvent)event).getItemStack();
}
String message = "Protect"
+ " " + action
+ (block == null ? "" : " " + block.getBlockName())
+ (itemStack == null ? "" : " " + itemStack.getItemName())
+ " " + x + "," + y + "," + z + " by " + area.data.name + "#" + area.data.getAreaIndex(area);
if (player == null)
commandManager.notifyAdmins(server, 0, message + (player == null ? "" : " from " + player.username), new Object[0]);
else
player.sendChatToPlayer(message);
}
return true;
}
}
}
return false;
}
@Override
public void onPlayerBlockAction(PlayerBlockEvent event) {
ACTION action = null;
switch (event.getType()) {
case ACTIVATION_ATTEMPT:
action = ACTION.ACTIVATE;
break;
case ACTIVATED:
break;
case REMOVE_ATTEMPT:
action = ACTION.DIG;
break;
case REMOVED:
break;
case ITEM_USE_ATTEMPT:
break;
case ITEM_USE_CHECK_EDIT:
action = ACTION.ITEM_USE_CHECK_EDIT;
break;
case ITEM_USED:
break;
case GET_ENDERCHEST_INVENTORY:
break;
}
if (action != null && isProtectedBlock(event, action, event.getPlayer(), event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) {
if (event.getType() == PlayerBlockEvent.TYPE.ACTIVATION_ATTEMPT)
event.markHandled();
else
event.markNotAllowed();
}
}
@Override
public void onBlockAction(BlockEvent event) {
if (event.getType() == BlockEvent.TYPE.EXPLODE_ATTEMPT) {
if (isProtectedBlock(event, ACTION.EXPLODE, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) {
event.markNotAllowed();
}
}
else if (event.getType() == BlockEvent.TYPE.BURN_ATTEMPT) {
if (isProtectedBlock(event, ACTION.BURN, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) {
event.markNotAllowed();
}
}
else if (event.getType() == BlockEvent.TYPE.IS_FLAMMABLE_BLOCK) {
if (isProtectedBlock(event, ACTION.IS_FLAMMABLE, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) {
event.markNotFlammable();
}
}
else if (event.getType() == BlockEvent.TYPE.FIRE_SPREAD_ATTEMPT) {
if (isProtectedBlock(event, ACTION.FIRE_SPREAD_ATTEMPT, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) {
event.markNotAllowed();
}
}
else if (event.getType() == BlockEvent.TYPE.CAN_PUSH_BLOCK) {
if (isProtectedBlock(event, ACTION.CAN_PUSH, null, event.getBlock(), event.getWorld(), event.getX(), event.getY(), event.getZ())) {
event.markNotAllowed();
}
else {
int nextX = event.getX() + Facing.offsetsXForSide[event.getPistonOrientation()];
int nextY = event.getY() + Facing.offsetsYForSide[event.getPistonOrientation()];
int nextZ = event.getZ() + Facing.offsetsZForSide[event.getPistonOrientation()];
int nextBlockId = event.getWorld().getBlockId(nextX, nextY, nextZ);
if (isProtectedBlock(event, ACTION.CAN_PUSH, null, nextBlockId > 0 ? Block.blocksList[nextBlockId] : null, event.getWorld(), nextX, nextY, nextZ)) {
event.markNotAllowed();
}
}
}
}
@Override
public void onPlayerAction(PlayerActionEvent event) {
if (event.getType() == PlayerActionEvent.TYPE.PLAYER_USE_ENTITY_ATTEMPT) {
if (isProtectedEntity(event.isLeftClick() ? ACTION.ATTACK_ENTITY : ACTION.USE_ENTITY, event.getPlayer(), event.getEntity(), MathHelper.floor_double(event.getEntity().posX), MathHelper.floor_double(event.getEntity().posY), MathHelper.floor_double(event.getEntity().posZ))) {
event.markNotAllowed();
}
}
}
@Override
public void onEntityAction(EntityEvent event) {
if (event.getType() == EntityEvent.TYPE.IS_ENTITY_INVULNERABLE) {
if (isProtectedEntity(ACTION.IS_ENTITY_INVULNERABLE, null, event.getEntity(), event.getX(), event.getY(), event.getZ())) {
event.markIsInvulnerable();
}
}
else if (event.getType() == EntityEvent.TYPE.TRAMPLE_FARMLAND_ATTEMPT) {
if (isProtectedBlock(event, ACTION.TRAMPLE_FARMLAND, null, Block.tilledField, event.getWorld(), event.getBlockX(), event.getBlockY(), event.getBlockZ())) {
event.markNotAllowed();
}
}
/*else if (event.getType() == EntityEvent.TYPE.EXPLODE_ATTEMPT) {
if (isProtectedEntity(ACTION.EXPLODE, null, event.getEntity(), MathHelper.floor_double(event.getEntity().posX), MathHelper.floor_double(event.getEntity().posY), MathHelper.floor_double(event.getEntity().posZ))) {
event.markNotAllowed();
}
}*/
}
public void saveAreas() {
data.clear();
int count = 1;
for (ProtectedZones zones : zonesByDimension) {
for (Zone zone : zones.getZones()) {
zone.saveToSettings(data, "zone" + count);
count++;
}
}
data.setInt("count", count);
data.saveSettings(this);
}
}
| true | true | protected boolean isProtectedBlock(APIEvent event, ACTION action, EntityPlayer player, Block block, World world, int x, int y, int z) {
if (!isProtectedBlockType(action, block))
return false;
if (player != null && isPlayerGloballyAllowed(player.username))
return true;
List<Area<Zone>> areas = zonesByDimension[Util.getWorldIndexFromDimension(world.provider.dimensionId)].get(x, y, z);
for (Area<Zone> area : areas) {
Zone zone = area.data;
ItemStack itemStack = null;
if (zone != null) {
boolean isProtected = false;
switch (action) {
case EXPLODE:
if (zone.permissions.protectExplosions)
isProtected = true;
break;
case IS_FLAMMABLE:
case BURN:
case FIRE_SPREAD_ATTEMPT:
if (zone.permissions.protectBurning)
isProtected = true;
break;
case CAN_PUSH:
// Protect against pistons from outside the area.
if (event instanceof BlockEvent && zone.permissions.protectEdits != Permission.OFF) {
BlockEvent blockEvent = (BlockEvent)event;
isProtected = true;
// Check all areas for the ZoneSettings.
for (Area zoneArea : area.data.areas) {
if (zoneArea.isWithin(blockEvent.getPistonX(), blockEvent.getPistonY(), blockEvent.getPistonZ())) {
isProtected = false;
break;
}
}
}
break;
default:
if (zone.permissions.protectEdits != Permission.OFF) {
isProtected = true;
// Allow immature bloodmoss to be destroyed.
if ((action == ACTION.DIG) && block instanceof FCBlockBloodMoss && event instanceof BlockEventBase && (((BlockEventBase)event).getMetadata() & 7) < 7) {
isProtected = false;
}
if (isProtected && player != null) {
if (isProtected && action == ACTION.ACTIVATE) {
if ((block == Block.doorWood || block == Block.trapdoor || block == Block.fenceGate)
&& zone.isPlayerAllowed(player.username, zone.permissions.allowDoors))
isProtected = false;
else if (block instanceof BlockContainer && zone.isPlayerAllowed(player.username, zone.permissions.allowContainers))
isProtected = false;
}
if (isProtected && zone.permissions.allowOps && isOp(player.username))
isProtected = false;
if (isProtected && action == ACTION.DIG && block == Block.skull && zone.isPlayerAllowed(player.username, zone.permissions.allowHeads)) {
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity instanceof TileEntitySkull) {
TileEntitySkull tileEntitySkull = (TileEntitySkull)tileEntity;
if (tileEntitySkull.getSkullType() == 3 && player.username.equalsIgnoreCase(tileEntitySkull.getExtraType())) {
isProtected = false;
}
}
}
if (isProtected && action == ACTION.ITEM_USE_CHECK_EDIT) {
PlayerBlockEvent playerBlockEvent = (PlayerBlockEvent)event;
if ((itemStack = playerBlockEvent.getItemStack()) != null
&& playerBlockEvent.getDirection() == 1
&& itemStack.getItem() == Item.skull
&& itemStack.getItemDamage() == 3
&& itemStack.hasTagCompound()
&& itemStack.getTagCompound().hasKey("SkullOwner")
&& player.username.equalsIgnoreCase(itemStack.getTagCompound().getString("SkullOwner"))
&& playerBlockEvent.getBlockId() == 0
&& playerBlockEvent.getY() > 1
&& playerBlockEvent.getWorld().getBlockId(playerBlockEvent.getX(), playerBlockEvent.getY() - 1, playerBlockEvent.getZ()) != 0) {
isProtected = false;
}
}
if (isProtected && zone.permissions.protectEdits == Permission.WHITELIST && zone.whitelist.contains(player.username))
isProtected = false;
}
}
break;
}
if (isProtected) {
if (zone.permissions.sendDebugMessages) {
if (itemStack == null && event instanceof PlayerBlockEvent) {
itemStack = ((PlayerBlockEvent)event).getItemStack();
}
String message = "Protect"
+ " " + action
+ (block == null ? "" : " " + block.getBlockName())
+ (itemStack == null ? "" : " " + itemStack.getItemName())
+ " " + x + "," + y + "," + z + " by " + area.data.name + "#" + area.data.getAreaIndex(area);
if (player == null)
commandManager.notifyAdmins(server, 0, message + (player == null ? "" : " from " + player.username), new Object[0]);
else
player.sendChatToPlayer(message);
}
return true;
}
}
}
return false;
}
| protected boolean isProtectedBlock(APIEvent event, ACTION action, EntityPlayer player, Block block, World world, int x, int y, int z) {
if (!isProtectedBlockType(action, block))
return false;
if (player != null && isPlayerGloballyAllowed(player.username))
return true;
List<Area<Zone>> areas = zonesByDimension[Util.getWorldIndexFromDimension(world.provider.dimensionId)].get(x, y, z);
for (Area<Zone> area : areas) {
Zone zone = area.data;
ItemStack itemStack = null;
if (zone != null) {
boolean isProtected = false;
switch (action) {
case EXPLODE:
if (zone.permissions.protectExplosions)
isProtected = true;
break;
case IS_FLAMMABLE:
case BURN:
case FIRE_SPREAD_ATTEMPT:
if (zone.permissions.protectBurning)
isProtected = true;
break;
case CAN_PUSH:
// Protect against pistons from outside the area.
if (event instanceof BlockEvent && zone.permissions.protectEdits != Permission.OFF) {
BlockEvent blockEvent = (BlockEvent)event;
isProtected = true;
// Check all areas for the ZoneSettings.
for (Area zoneArea : area.data.areas) {
if (zoneArea.isWithin(blockEvent.getPistonX(), blockEvent.getPistonY(), blockEvent.getPistonZ())) {
isProtected = false;
break;
}
}
}
break;
default:
if (zone.permissions.protectEdits != Permission.OFF) {
isProtected = true;
// Allow immature bloodmoss to be destroyed.
if ((action == ACTION.DIG) && block instanceof FCBlockBloodMoss && event instanceof BlockEventBase && (((BlockEventBase)event).getMetadata() & 7) < 7) {
isProtected = false;
}
if (isProtected && player != null) {
if (isProtected && action == ACTION.ACTIVATE) {
if ((block == Block.doorWood || block == Block.trapdoor || block == Block.fenceGate)
&& zone.isPlayerAllowed(player.username, zone.permissions.allowDoors))
isProtected = false;
else if (block instanceof BlockContainer && zone.isPlayerAllowed(player.username, zone.permissions.allowContainers))
isProtected = false;
}
if (isProtected && zone.permissions.allowOps && isOp(player.username))
isProtected = false;
if (isProtected && action == ACTION.DIG && block == Block.skull && zone.isPlayerAllowed(player.username, zone.permissions.allowHeads)) {
TileEntity tileEntity = world.getBlockTileEntity(x, y, z);
if (tileEntity instanceof TileEntitySkull) {
TileEntitySkull tileEntitySkull = (TileEntitySkull)tileEntity;
if (tileEntitySkull.getSkullType() == 3 && player.username.equalsIgnoreCase(tileEntitySkull.getExtraType())) {
isProtected = false;
}
}
}
if (isProtected && action == ACTION.ITEM_USE_CHECK_EDIT) {
PlayerBlockEvent playerBlockEvent = (PlayerBlockEvent)event;
if ((itemStack = playerBlockEvent.getItemStack()) != null
&& playerBlockEvent.getDirection() == 1
&& itemStack.getItem() == Item.skull
&& itemStack.getItemDamage() == 3
&& zone.isPlayerAllowed(player.username, zone.permissions.allowHeads)
&& itemStack.hasTagCompound()
&& itemStack.getTagCompound().hasKey("SkullOwner")
&& player.username.equalsIgnoreCase(itemStack.getTagCompound().getString("SkullOwner"))
&& playerBlockEvent.getBlockId() == 0
&& playerBlockEvent.getY() > 1
&& playerBlockEvent.getWorld().getBlockId(playerBlockEvent.getX(), playerBlockEvent.getY() - 1, playerBlockEvent.getZ()) != 0) {
isProtected = false;
}
}
if (isProtected && zone.permissions.protectEdits == Permission.WHITELIST && zone.whitelist.contains(player.username))
isProtected = false;
}
}
break;
}
if (isProtected) {
if (zone.permissions.sendDebugMessages) {
if (itemStack == null && event instanceof PlayerBlockEvent) {
itemStack = ((PlayerBlockEvent)event).getItemStack();
}
String message = "Protect"
+ " " + action
+ (block == null ? "" : " " + block.getBlockName())
+ (itemStack == null ? "" : " " + itemStack.getItemName())
+ " " + x + "," + y + "," + z + " by " + area.data.name + "#" + area.data.getAreaIndex(area);
if (player == null)
commandManager.notifyAdmins(server, 0, message + (player == null ? "" : " from " + player.username), new Object[0]);
else
player.sendChatToPlayer(message);
}
return true;
}
}
}
return false;
}
|
diff --git a/android/src/com/google/zxing/client/android/wifi/WifiActivity.java b/android/src/com/google/zxing/client/android/wifi/WifiActivity.java
index 56488098..0654d868 100644
--- a/android/src/com/google/zxing/client/android/wifi/WifiActivity.java
+++ b/android/src/com/google/zxing/client/android/wifi/WifiActivity.java
@@ -1,312 +1,311 @@
/*
* Copyright (C) 2010 ZXing authors
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.google.zxing.client.android.wifi;
import java.util.List;
import java.util.regex.Pattern;
import android.app.Activity;
import android.content.Intent;
import android.content.IntentFilter;
import android.net.ConnectivityManager;
import android.net.wifi.WifiConfiguration;
import android.net.wifi.WifiManager;
import android.os.Bundle;
import android.util.Log;
import android.widget.TextView;
import com.google.zxing.client.android.Intents;
import com.google.zxing.client.android.R;
/**
* A new activity showing the progress of Wifi connection
*
* @author Vikram Aggarwal
*/
public final class WifiActivity extends Activity {
private static final String TAG = WifiActivity.class.getSimpleName();
private static final int MAX_ERROR_COUNT = 3;
private static final int FAILURE_NO_NETWORK_ID = -1;
private static final Pattern HEX_DIGITS_64 = Pattern.compile("[0-9A-Fa-f]{64}");
private WifiManager wifiManager;
private TextView statusView;
private WifiReceiver wifiReceiver;
private boolean receiverRegistered;
private int networkId;
private int errorCount;
private IntentFilter mWifiStateFilter;
void gotError() {
errorCount++;
Log.d(TAG, "Encountered another error. Errorcount = " + errorCount);
if (errorCount > MAX_ERROR_COUNT){
errorCount = 0;
doError(R.string.wifi_connect_failed);
}
}
public enum NetworkType {
NETWORK_WEP, NETWORK_WPA, NETWORK_NOPASS, NETWORK_INVALID,
}
private int changeNetwork(NetworkSetting setting) {
// If the SSID is empty, throw an error and return
if (setting.getSsid() == null || setting.getSsid().length() == 0) {
return doError(R.string.wifi_ssid_missing);
}
// If the network type is invalid
if (setting.getNetworkType() == NetworkType.NETWORK_INVALID){
return doError(R.string.wifi_type_incorrect);
}
// If the password is empty, this is an unencrypted network
if (setting.getPassword() == null || setting.getPassword().length() == 0 ||
setting.getNetworkType() == null ||
setting.getNetworkType() == NetworkType.NETWORK_NOPASS) {
return changeNetworkUnEncrypted(setting);
}
if (setting.getNetworkType() == NetworkType.NETWORK_WPA) {
return changeNetworkWPA(setting);
} else {
return changeNetworkWEP(setting);
}
}
private int doError(int resource_string) {
statusView.setText(resource_string);
// Give up on the connection
wifiManager.disconnect();
if (networkId > 0) {
wifiManager.removeNetwork(networkId);
networkId = -1;
}
if (receiverRegistered) {
unregisterReceiver(wifiReceiver);
receiverRegistered = false;
}
return -1;
}
private WifiConfiguration changeNetworkCommon(NetworkSetting input){
statusView.setText(R.string.wifi_creating_network);
Log.d(TAG, "Adding new configuration: \nSSID: " + input.getSsid() + "\nType: " +
input.getNetworkType());
WifiConfiguration config = new WifiConfiguration();
config.allowedAuthAlgorithms.clear();
config.allowedGroupCiphers.clear();
config.allowedKeyManagement.clear();
config.allowedPairwiseCiphers.clear();
config.allowedProtocols.clear();
// Android API insists that an ascii SSID must be quoted to be correctly handled.
config.SSID = NetworkUtil.convertToQuotedString(input.getSsid());
config.hiddenSSID = true;
return config;
}
private int requestNetworkChange(WifiConfiguration config){
statusView.setText(R.string.wifi_changing_network);
return updateNetwork(config, false);
}
// Adding a WEP network
private int changeNetworkWEP(NetworkSetting input) {
WifiConfiguration config = changeNetworkCommon(input);
String pass = input.getPassword();
if (NetworkUtil.isHexWepKey(pass)) {
config.wepKeys[0] = pass;
} else {
config.wepKeys[0] = NetworkUtil.convertToQuotedString(pass);
}
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.SHARED);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP40);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.WEP104);
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
return requestNetworkChange(config);
}
// Adding a WPA or WPA2 network
private int changeNetworkWPA(NetworkSetting input) {
WifiConfiguration config = changeNetworkCommon(input);
String pass = input.getPassword();
// Hex passwords that are 64 bits long are not to be quoted.
if (HEX_DIGITS_64.matcher(pass).matches()){
Log.d(TAG, "A 64 bit hex password entered.");
config.preSharedKey = pass;
} else {
Log.d(TAG, "A normal password entered: I am quoting it.");
config.preSharedKey = NetworkUtil.convertToQuotedString(pass);
}
config.allowedAuthAlgorithms.set(WifiConfiguration.AuthAlgorithm.OPEN);
// For WPA
config.allowedProtocols.set(WifiConfiguration.Protocol.WPA);
// For WPA2
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.WPA_PSK);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.TKIP);
config.allowedGroupCiphers.set(WifiConfiguration.GroupCipher.CCMP);
config.allowedProtocols.set(WifiConfiguration.Protocol.RSN);
return requestNetworkChange(config);
}
// Adding an open, unsecured network
private int changeNetworkUnEncrypted(NetworkSetting input){
Log.d(TAG, "Empty password prompting a simple account setting");
WifiConfiguration config = changeNetworkCommon(input);
config.wepKeys[0] = "";
config.allowedKeyManagement.set(WifiConfiguration.KeyMgmt.NONE);
config.wepTxKeyIndex = 0;
return requestNetworkChange(config);
}
/**
* If the given ssid name exists in the settings, then change its password to the one given here,
* and save
* @param ssid
*/
private WifiConfiguration findNetworkInExistingConfig(String ssid){
List<WifiConfiguration> existingConfigs = wifiManager.getConfiguredNetworks();
for (WifiConfiguration existingConfig : existingConfigs) {
if (existingConfig.SSID.equals(ssid)) {
return existingConfig;
}
}
return null;
}
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent == null || !intent.getAction().equals(Intents.WifiConnect.ACTION)) {
finish();
return;
}
String ssid = intent.getStringExtra(Intents.WifiConnect.SSID);
String password = intent.getStringExtra(Intents.WifiConnect.PASSWORD);
String networkType = intent.getStringExtra(Intents.WifiConnect.TYPE);
setContentView(R.layout.network);
statusView = (TextView) findViewById(R.id.networkStatus);
NetworkType networkT;
if ("WPA".equals(networkType)) {
networkT = NetworkType.NETWORK_WPA;
} else if ("WEP".equals(networkType)) {
networkT = NetworkType.NETWORK_WEP;
} else if ("nopass".equals(networkType)) {
- networkT = NetworkType.NETWORK_NOPASS;
+ networkT = NetworkType.NETWORK_NOPASS;
} else {
- doError(R.string.wifi_type_incorrect);
- return;
+ networkT = NetworkType.NETWORK_INVALID;
}
// This is not available before onCreate
wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
// Start WiFi, otherwise nothing will work
wifiManager.setWifiEnabled(true);
// So we know when the network changes
wifiReceiver = new WifiReceiver(wifiManager, this, statusView, ssid);
// The order matters!
mWifiStateFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mWifiStateFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(wifiReceiver, mWifiStateFilter);
receiverRegistered = true;
if (password == null) {
password = "";
}
Log.d(TAG, "Adding new configuration: \nSSID: " + ssid + "Type: " + networkT);
NetworkSetting setting = new NetworkSetting(ssid, password, networkT);
changeNetwork(setting);
}
@Override
public void onPause() {
super.onPause();
if (receiverRegistered) {
unregisterReceiver(wifiReceiver);
receiverRegistered = false;
}
}
@Override
public void onResume() {
super.onResume();
if (wifiReceiver != null && mWifiStateFilter != null && !receiverRegistered) {
registerReceiver(wifiReceiver, mWifiStateFilter);
receiverRegistered = true;
}
}
@Override
protected void onDestroy() {
if (wifiReceiver != null) {
if (receiverRegistered) {
unregisterReceiver(wifiReceiver);
receiverRegistered = false;
}
wifiReceiver = null;
}
super.onDestroy();
}
/**
* Update the network: either create a new network or modify an existing network
* @param config the new network configuration
* @param disableOthers true if other networks must be disabled
* @return network ID of the connected network.
*/
private int updateNetwork(WifiConfiguration config, boolean disableOthers) {
WifiConfiguration found = findNetworkInExistingConfig(config.SSID);
wifiManager.disconnect();
if (found == null) {
statusView.setText(R.string.wifi_creating_network);
} else {
statusView.setText(R.string.wifi_modifying_network);
Log.d(TAG, "Removing network " + found.networkId);
wifiManager.removeNetwork(found.networkId);
wifiManager.saveConfiguration();
}
networkId = wifiManager.addNetwork(config);
Log.d(TAG, "Inserted/Modified network " + networkId);
if (networkId < 0) {
return FAILURE_NO_NETWORK_ID;
}
// Try to disable the current network and start a new one.
if (!wifiManager.enableNetwork(networkId, disableOthers)) {
networkId = FAILURE_NO_NETWORK_ID;
return FAILURE_NO_NETWORK_ID;
}
errorCount = 0;
wifiManager.reassociate();
return networkId;
}
}
| false | true | protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent == null || !intent.getAction().equals(Intents.WifiConnect.ACTION)) {
finish();
return;
}
String ssid = intent.getStringExtra(Intents.WifiConnect.SSID);
String password = intent.getStringExtra(Intents.WifiConnect.PASSWORD);
String networkType = intent.getStringExtra(Intents.WifiConnect.TYPE);
setContentView(R.layout.network);
statusView = (TextView) findViewById(R.id.networkStatus);
NetworkType networkT;
if ("WPA".equals(networkType)) {
networkT = NetworkType.NETWORK_WPA;
} else if ("WEP".equals(networkType)) {
networkT = NetworkType.NETWORK_WEP;
} else if ("nopass".equals(networkType)) {
networkT = NetworkType.NETWORK_NOPASS;
} else {
doError(R.string.wifi_type_incorrect);
return;
}
// This is not available before onCreate
wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
// Start WiFi, otherwise nothing will work
wifiManager.setWifiEnabled(true);
// So we know when the network changes
wifiReceiver = new WifiReceiver(wifiManager, this, statusView, ssid);
// The order matters!
mWifiStateFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mWifiStateFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(wifiReceiver, mWifiStateFilter);
receiverRegistered = true;
if (password == null) {
password = "";
}
Log.d(TAG, "Adding new configuration: \nSSID: " + ssid + "Type: " + networkT);
NetworkSetting setting = new NetworkSetting(ssid, password, networkT);
changeNetwork(setting);
}
| protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Intent intent = getIntent();
if (intent == null || !intent.getAction().equals(Intents.WifiConnect.ACTION)) {
finish();
return;
}
String ssid = intent.getStringExtra(Intents.WifiConnect.SSID);
String password = intent.getStringExtra(Intents.WifiConnect.PASSWORD);
String networkType = intent.getStringExtra(Intents.WifiConnect.TYPE);
setContentView(R.layout.network);
statusView = (TextView) findViewById(R.id.networkStatus);
NetworkType networkT;
if ("WPA".equals(networkType)) {
networkT = NetworkType.NETWORK_WPA;
} else if ("WEP".equals(networkType)) {
networkT = NetworkType.NETWORK_WEP;
} else if ("nopass".equals(networkType)) {
networkT = NetworkType.NETWORK_NOPASS;
} else {
networkT = NetworkType.NETWORK_INVALID;
}
// This is not available before onCreate
wifiManager = (WifiManager) this.getSystemService(WIFI_SERVICE);
// Start WiFi, otherwise nothing will work
wifiManager.setWifiEnabled(true);
// So we know when the network changes
wifiReceiver = new WifiReceiver(wifiManager, this, statusView, ssid);
// The order matters!
mWifiStateFilter = new IntentFilter(WifiManager.WIFI_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(ConnectivityManager.CONNECTIVITY_ACTION);
mWifiStateFilter.addAction(WifiManager.SUPPLICANT_STATE_CHANGED_ACTION);
mWifiStateFilter.addAction(WifiManager.NETWORK_STATE_CHANGED_ACTION);
registerReceiver(wifiReceiver, mWifiStateFilter);
receiverRegistered = true;
if (password == null) {
password = "";
}
Log.d(TAG, "Adding new configuration: \nSSID: " + ssid + "Type: " + networkT);
NetworkSetting setting = new NetworkSetting(ssid, password, networkT);
changeNetwork(setting);
}
|
diff --git a/public/java/test/org/broadinstitute/sting/gatk/walkers/recalibration/RecalibrationWalkersPerformanceTest.java b/public/java/test/org/broadinstitute/sting/gatk/walkers/recalibration/RecalibrationWalkersPerformanceTest.java
index 08b9e0431..f89b80ead 100755
--- a/public/java/test/org/broadinstitute/sting/gatk/walkers/recalibration/RecalibrationWalkersPerformanceTest.java
+++ b/public/java/test/org/broadinstitute/sting/gatk/walkers/recalibration/RecalibrationWalkersPerformanceTest.java
@@ -1,80 +1,80 @@
package org.broadinstitute.sting.gatk.walkers.recalibration;
import org.broadinstitute.sting.WalkerTest;
import org.testng.annotations.Test;
import java.util.ArrayList;
public class RecalibrationWalkersPerformanceTest extends WalkerTest {
private void testCountCovariatesWholeGenomeRunner(String moreArgs) {
WalkerTestSpec spec = new WalkerTestSpec(
"-R " + hg18Reference +
" -T CountCovariates" +
" -I " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.bam" +
" -L chr1:1-50,000,000" +
" -standard" +
" -OQ" +
- " D:dbsnp,VCF " + GATKDataLocation + "dbsnp_132_hg18.vcf" +
+ " -B:dbsnp,VCF " + GATKDataLocation + "dbsnp_132_hg18.vcf" +
" -recalFile /dev/null" + moreArgs,
0,
new ArrayList<String>(0));
executeTest("testCountCovariatesWholeGenome", spec);
}
private void testCountCovariatesWholeExomeRunner(String moreArgs) {
WalkerTestSpec spec = new WalkerTestSpec(
"-R " + hg18Reference +
" -T CountCovariates" +
" -I " + evaluationDataLocation + "NA12878.ESP.WEx.chr1.bam" +
" -L " + evaluationDataLocation + "whole_exome_agilent_designed_120.targets.chr1.interval_list" +
" -standard" +
" -OQ" +
" -B:dbsnp,VCF " + GATKDataLocation + "dbsnp_132.hg18.vcf" +
" -recalFile /dev/null" + moreArgs,
0,
new ArrayList<String>(0));
executeTest("testCountCovariatesWholeExome", spec);
}
@Test
public void testCountCovariatesWholeGenome() { testCountCovariatesWholeGenomeRunner(""); }
@Test
public void testCountCovariatesWholeGenomeParallel() { testCountCovariatesWholeGenomeRunner(" -nt 4"); }
@Test
public void testCountCovariatesWholeExome() { testCountCovariatesWholeExomeRunner(""); }
@Test
public void testCountCovariatesWholeExomeParallel() { testCountCovariatesWholeExomeRunner(" -nt 4"); }
@Test
public void testTableRecalibratorWholeGenome() {
WalkerTestSpec spec = new WalkerTestSpec(
"-R " + hg18Reference +
" -T TableRecalibration" +
" -I " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.bam" +
" -L chr1:1-50,000,000" +
" -OQ" +
" -recalFile " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.recal.csv" +
" -o /dev/null",
0,
new ArrayList<String>(0));
executeTest("testTableRecalibratorWholeGenome", spec);
}
@Test
public void testTableRecalibratorWholeExome() {
WalkerTestSpec spec = new WalkerTestSpec(
"-R " + hg18Reference +
" -T TableRecalibration" +
" -I " + evaluationDataLocation + "NA12878.ESP.WEx.chr1.bam" +
" -L " + evaluationDataLocation + "whole_exome_agilent_designed_120.targets.chr1.interval_list" +
" -OQ" +
" -recalFile " + evaluationDataLocation + "NA12878.ESP.WEx.chr1.recal.csv" +
" -o /dev/null",
0,
new ArrayList<String>(0));
executeTest("testTableRecalibratorWholeExome", spec);
}
}
| true | true | private void testCountCovariatesWholeGenomeRunner(String moreArgs) {
WalkerTestSpec spec = new WalkerTestSpec(
"-R " + hg18Reference +
" -T CountCovariates" +
" -I " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.bam" +
" -L chr1:1-50,000,000" +
" -standard" +
" -OQ" +
" D:dbsnp,VCF " + GATKDataLocation + "dbsnp_132_hg18.vcf" +
" -recalFile /dev/null" + moreArgs,
0,
new ArrayList<String>(0));
executeTest("testCountCovariatesWholeGenome", spec);
}
| private void testCountCovariatesWholeGenomeRunner(String moreArgs) {
WalkerTestSpec spec = new WalkerTestSpec(
"-R " + hg18Reference +
" -T CountCovariates" +
" -I " + evaluationDataLocation + "NA12878.GAII.chr1.50MB.bam" +
" -L chr1:1-50,000,000" +
" -standard" +
" -OQ" +
" -B:dbsnp,VCF " + GATKDataLocation + "dbsnp_132_hg18.vcf" +
" -recalFile /dev/null" + moreArgs,
0,
new ArrayList<String>(0));
executeTest("testCountCovariatesWholeGenome", spec);
}
|
diff --git a/src/au/com/addstar/truehardcore/CommandTH.java b/src/au/com/addstar/truehardcore/CommandTH.java
index 55cd283..a257ddd 100644
--- a/src/au/com/addstar/truehardcore/CommandTH.java
+++ b/src/au/com/addstar/truehardcore/CommandTH.java
@@ -1,348 +1,348 @@
package au.com.addstar.truehardcore;
/*
* TrueHardcore
* Copyright (C) 2013 add5tar <copyright at addstar dot com dot au>
*
* 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/>
*/
import java.util.ArrayList;
import java.util.Date;
import org.apache.commons.lang.StringUtils;
import org.bukkit.ChatColor;
import org.bukkit.World;
import org.bukkit.command.Command;
import org.bukkit.command.CommandExecutor;
import org.bukkit.command.CommandSender;
import org.bukkit.entity.Player;
import au.com.addstar.truehardcore.HardcorePlayers.HardcorePlayer;
import au.com.addstar.truehardcore.HardcorePlayers.PlayerState;
public class CommandTH implements CommandExecutor {
private TrueHardcore plugin;
public CommandTH(TrueHardcore instance) {
plugin = instance;
}
/*
* Handle the /truehardcore command
*/
public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String action = "";
if (args.length > 0) {
action = args[0].toUpperCase();
}
if (action.equals("PLAY")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.use")) { return true; }
}
if (args.length > 1) {
World world = plugin.getServer().getWorld(args[1]);
if (world == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown world!");
return true;
}
if (plugin.IsHardcoreWorld(world)) {
plugin.PlayGame(world.getName(), (Player) sender);
} else {
sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>");
}
}
else if (action.equals("LEAVE")) {
plugin.LeaveGame((Player) sender);
}
else if (action.equals("INFO")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
if (hcp != null) {
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "You must be in the hardcore world to use this command");
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (plugin.IsHardcoreWorld(player.getWorld())) {
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp != null) {
Player player = (Player) plugin.getServer().getPlayer(args[2]);
if (player != null) {
if (plugin.IsHardcoreWorld(player.getWorld())) {
if (args[1] == player.getWorld().getName()) {
hcp.updatePlayer(player);
}
}
}
} else {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
}
if (hcp != null) {
Integer gt;
if (hcp.getState() == PlayerState.IN_GAME) {
gt = (hcp.getGameTime() + hcp.TimeDiff(hcp.getLastJoin(), new Date()));
} else {
gt = hcp.getGameTime();
}
String gametime = Util.Long2Time(gt);
sender.sendMessage(ChatColor.GREEN + "Hardcore player information:");
sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "Game Time: " + ChatColor.AQUA + gametime);
sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore());
}
}
else if (action.equals("DUMP")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 1) {
for (String key : plugin.HCPlayers.AllRecords().keySet()) {
HardcorePlayer hcp = plugin.HCPlayers.Get(key);
sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState());
}
}
else if (args.length == 3) {
HardcorePlayer hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp != null) {
sender.sendMessage(ChatColor.YELLOW + "Player Name : " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World : " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "LastPos : " + ChatColor.AQUA + hcp.getLastPos());
sender.sendMessage(ChatColor.YELLOW + "LastJoin : " + ChatColor.AQUA + hcp.getLastJoin());
sender.sendMessage(ChatColor.YELLOW + "LastQuit : " + ChatColor.AQUA + hcp.getLastQuit());
sender.sendMessage(ChatColor.YELLOW + "GameStart : " + ChatColor.AQUA + hcp.getGameStart());
sender.sendMessage(ChatColor.YELLOW + "GameEnd : " + ChatColor.AQUA + hcp.getGameEnd());
sender.sendMessage(ChatColor.YELLOW + "GameTime : " + ChatColor.AQUA + hcp.getGameTime());
sender.sendMessage(ChatColor.YELLOW + "Level : " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Exp : " + ChatColor.AQUA + hcp.getExp());
sender.sendMessage(ChatColor.YELLOW + "Score : " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "TopScore : " + ChatColor.AQUA + hcp.getTopScore());
sender.sendMessage(ChatColor.YELLOW + "State : " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "GodMode : " + ChatColor.AQUA + hcp.isGodMode());
sender.sendMessage(ChatColor.YELLOW + "DeathMsg : " + ChatColor.AQUA + hcp.getDeathMsg());
sender.sendMessage(ChatColor.YELLOW + "DeathPos : " + ChatColor.AQUA + hcp.getDeathPos());
sender.sendMessage(ChatColor.YELLOW + "Deaths : " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Modified : " + ChatColor.AQUA + hcp.isModified());
sender.sendMessage(ChatColor.YELLOW + "Cow Kills : " + ChatColor.AQUA + hcp.getCowKills());
sender.sendMessage(ChatColor.YELLOW + "Pig Kills : " + ChatColor.AQUA + hcp.getPigKills());
sender.sendMessage(ChatColor.YELLOW + "Sheep Kills : " + ChatColor.AQUA + hcp.getSheepKills());
sender.sendMessage(ChatColor.YELLOW + "Chicken Kills : " + ChatColor.AQUA + hcp.getChickenKills());
sender.sendMessage(ChatColor.YELLOW + "Creeper Kills : " + ChatColor.AQUA + hcp.getCreeperKills());
sender.sendMessage(ChatColor.YELLOW + "Zombie Kills : " + ChatColor.AQUA + hcp.getZombieKills());
sender.sendMessage(ChatColor.YELLOW + "Skeleton Kills : " + ChatColor.AQUA + hcp.getSkeletonKills());
sender.sendMessage(ChatColor.YELLOW + "Spider Kills : " + ChatColor.AQUA + hcp.getSpiderKills());
sender.sendMessage(ChatColor.YELLOW + "Ender Kills : " + ChatColor.AQUA + hcp.getEnderKills());
sender.sendMessage(ChatColor.YELLOW + "Slime Kills : " + ChatColor.AQUA + hcp.getSlimeKills());
sender.sendMessage(ChatColor.YELLOW + "Moosh Kills : " + ChatColor.AQUA + hcp.getMooshKills());
sender.sendMessage(ChatColor.YELLOW + "Other Kills : " + ChatColor.AQUA + hcp.getOtherKills());
sender.sendMessage(ChatColor.YELLOW + "Player Kills : " + ChatColor.AQUA + hcp.getPlayerKills());
}
}
}
else if (action.equals("DUMPWORLDS")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 1) {
for (String key : plugin.HardcoreWorlds.keySet()) {
HardcoreWorld hcw = plugin.HardcoreWorlds.get(key);
sender.sendMessage(ChatColor.YELLOW + "World Name : " + ChatColor.AQUA + hcw.getWorld().getName());
sender.sendMessage(ChatColor.YELLOW + "Greeting : " + ChatColor.AQUA + ChatColor.translateAlternateColorCodes('&', hcw.getGreeting()));
sender.sendMessage(ChatColor.YELLOW + "Ban Time : " + ChatColor.AQUA + hcw.getBantime());
sender.sendMessage(ChatColor.YELLOW + "Distance : " + ChatColor.AQUA + hcw.getSpawnDistance());
sender.sendMessage(ChatColor.YELLOW + "Protection : " + ChatColor.AQUA + hcw.getSpawnProtection());
sender.sendMessage(ChatColor.YELLOW + "ExitPos : " + ChatColor.AQUA + hcw.getExitPos());
}
}
}
else if (action.equals("SET")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 3) {
- if (args[1].toUpperCase() == "EXIT") {
+ if (args[1].toUpperCase().equals("EXIT")) {
World world = plugin.getServer().getWorld(args[2]);
if ((world != null) && (plugin.IsHardcoreWorld(world))) {
HardcoreWorld hcw = plugin.HardcoreWorlds.get(world.getName());
plugin.Debug("Setting ExitPos for " + hcw.getWorld().getName());
Player player = (Player) sender;
hcw.setExitPos(player.getLocation());
plugin.Config().set("worlds." + world.getName() + ".exitpos", Util.Loc2Str(player.getLocation(), true));
plugin.saveConfig();
} else {
sender.sendMessage(ChatColor.RED + "Not a valid hardcore world");
}
} else {
- sender.sendMessage(ChatColor.RED + "Invalid option");
+ sender.sendMessage(ChatColor.RED + "Invalid option \"" + args[1] + "\"");
}
}
}
else if (action.equals("LIST") || action.equals("WHO")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.list")) { return true; }
}
sender.sendMessage(ChatColor.GREEN + "Players currently in hardcore worlds:");
boolean Playing = false;
for (String w : plugin.HardcoreWorlds.keySet()) {
World world = plugin.getServer().getWorld(w);
if ((world != null) && (world.getPlayers().size() > 0)) {
ArrayList<String> players = new ArrayList<String>();
for (Player p : world.getPlayers()) {
Playing = true;
players.add(p.getName());
}
sender.sendMessage(ChatColor.YELLOW + world.getName() + ": " + ChatColor.AQUA + StringUtils.join(players, ", "));
}
}
if (!Playing) {
sender.sendMessage(ChatColor.RED + "None");
}
}
else if (action.equals("STATS") || action.equals("KILLS")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
if (hcp == null) {
sender.sendMessage(ChatColor.RED + "You must be in the hardcore world to use this command");
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (!plugin.IsHardcoreWorld(player.getWorld())) {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
}
if (hcp != null) {
sender.sendMessage(ChatColor.GREEN + "Hardcore player statistics:");
sender.sendMessage(ChatColor.YELLOW + "Cow Kills : " + ChatColor.AQUA + hcp.getCowKills());
sender.sendMessage(ChatColor.YELLOW + "Pig Kills : " + ChatColor.AQUA + hcp.getPigKills());
sender.sendMessage(ChatColor.YELLOW + "Sheep Kills : " + ChatColor.AQUA + hcp.getSheepKills());
sender.sendMessage(ChatColor.YELLOW + "Chicken Kills : " + ChatColor.AQUA + hcp.getChickenKills());
sender.sendMessage(ChatColor.YELLOW + "Creeper Kills : " + ChatColor.AQUA + hcp.getCreeperKills());
sender.sendMessage(ChatColor.YELLOW + "Zombie Kills : " + ChatColor.AQUA + hcp.getZombieKills());
sender.sendMessage(ChatColor.YELLOW + "Skeleton Kills : " + ChatColor.AQUA + hcp.getSkeletonKills());
sender.sendMessage(ChatColor.YELLOW + "Spider Kills : " + ChatColor.AQUA + hcp.getSpiderKills());
sender.sendMessage(ChatColor.YELLOW + "Ender Kills : " + ChatColor.AQUA + hcp.getEnderKills());
sender.sendMessage(ChatColor.YELLOW + "Slime Kills : " + ChatColor.AQUA + hcp.getSlimeKills());
sender.sendMessage(ChatColor.YELLOW + "Moosh Kills : " + ChatColor.AQUA + hcp.getMooshKills());
sender.sendMessage(ChatColor.YELLOW + "Other Kills : " + ChatColor.AQUA + hcp.getOtherKills());
sender.sendMessage(ChatColor.YELLOW + "Player Kills : " + ChatColor.AQUA + hcp.getPlayerKills());
}
}
else if (action.equals("SAVE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.Debug("Saving buffered data...");
plugin.SaveAllPlayers();
}
else if (action.equals("RELOAD")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.LoadWhiteList();
}
else if (action.equals("DISABLE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.GameEnabled = false;
sender.sendMessage(ChatColor.RED + "TrueHardcore has been disabled.");
}
else if (action.equals("ENABLE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.GameEnabled = true;
sender.sendMessage(ChatColor.GREEN + "TrueHardcore has been enabled.");
}
else {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:");
sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game");
sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)");
sender.sendMessage(ChatColor.AQUA + "/th list " + ChatColor.YELLOW + ": List the current hardcore players");
sender.sendMessage(ChatColor.AQUA + "/th info " + ChatColor.YELLOW + ": Display your current game information");
sender.sendMessage(ChatColor.AQUA + "/th stats " + ChatColor.YELLOW + ": Display kill statistics");
}
return true;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String action = "";
if (args.length > 0) {
action = args[0].toUpperCase();
}
if (action.equals("PLAY")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.use")) { return true; }
}
if (args.length > 1) {
World world = plugin.getServer().getWorld(args[1]);
if (world == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown world!");
return true;
}
if (plugin.IsHardcoreWorld(world)) {
plugin.PlayGame(world.getName(), (Player) sender);
} else {
sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>");
}
}
else if (action.equals("LEAVE")) {
plugin.LeaveGame((Player) sender);
}
else if (action.equals("INFO")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
if (hcp != null) {
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "You must be in the hardcore world to use this command");
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (plugin.IsHardcoreWorld(player.getWorld())) {
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp != null) {
Player player = (Player) plugin.getServer().getPlayer(args[2]);
if (player != null) {
if (plugin.IsHardcoreWorld(player.getWorld())) {
if (args[1] == player.getWorld().getName()) {
hcp.updatePlayer(player);
}
}
}
} else {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
}
if (hcp != null) {
Integer gt;
if (hcp.getState() == PlayerState.IN_GAME) {
gt = (hcp.getGameTime() + hcp.TimeDiff(hcp.getLastJoin(), new Date()));
} else {
gt = hcp.getGameTime();
}
String gametime = Util.Long2Time(gt);
sender.sendMessage(ChatColor.GREEN + "Hardcore player information:");
sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "Game Time: " + ChatColor.AQUA + gametime);
sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore());
}
}
else if (action.equals("DUMP")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 1) {
for (String key : plugin.HCPlayers.AllRecords().keySet()) {
HardcorePlayer hcp = plugin.HCPlayers.Get(key);
sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState());
}
}
else if (args.length == 3) {
HardcorePlayer hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp != null) {
sender.sendMessage(ChatColor.YELLOW + "Player Name : " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World : " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "LastPos : " + ChatColor.AQUA + hcp.getLastPos());
sender.sendMessage(ChatColor.YELLOW + "LastJoin : " + ChatColor.AQUA + hcp.getLastJoin());
sender.sendMessage(ChatColor.YELLOW + "LastQuit : " + ChatColor.AQUA + hcp.getLastQuit());
sender.sendMessage(ChatColor.YELLOW + "GameStart : " + ChatColor.AQUA + hcp.getGameStart());
sender.sendMessage(ChatColor.YELLOW + "GameEnd : " + ChatColor.AQUA + hcp.getGameEnd());
sender.sendMessage(ChatColor.YELLOW + "GameTime : " + ChatColor.AQUA + hcp.getGameTime());
sender.sendMessage(ChatColor.YELLOW + "Level : " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Exp : " + ChatColor.AQUA + hcp.getExp());
sender.sendMessage(ChatColor.YELLOW + "Score : " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "TopScore : " + ChatColor.AQUA + hcp.getTopScore());
sender.sendMessage(ChatColor.YELLOW + "State : " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "GodMode : " + ChatColor.AQUA + hcp.isGodMode());
sender.sendMessage(ChatColor.YELLOW + "DeathMsg : " + ChatColor.AQUA + hcp.getDeathMsg());
sender.sendMessage(ChatColor.YELLOW + "DeathPos : " + ChatColor.AQUA + hcp.getDeathPos());
sender.sendMessage(ChatColor.YELLOW + "Deaths : " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Modified : " + ChatColor.AQUA + hcp.isModified());
sender.sendMessage(ChatColor.YELLOW + "Cow Kills : " + ChatColor.AQUA + hcp.getCowKills());
sender.sendMessage(ChatColor.YELLOW + "Pig Kills : " + ChatColor.AQUA + hcp.getPigKills());
sender.sendMessage(ChatColor.YELLOW + "Sheep Kills : " + ChatColor.AQUA + hcp.getSheepKills());
sender.sendMessage(ChatColor.YELLOW + "Chicken Kills : " + ChatColor.AQUA + hcp.getChickenKills());
sender.sendMessage(ChatColor.YELLOW + "Creeper Kills : " + ChatColor.AQUA + hcp.getCreeperKills());
sender.sendMessage(ChatColor.YELLOW + "Zombie Kills : " + ChatColor.AQUA + hcp.getZombieKills());
sender.sendMessage(ChatColor.YELLOW + "Skeleton Kills : " + ChatColor.AQUA + hcp.getSkeletonKills());
sender.sendMessage(ChatColor.YELLOW + "Spider Kills : " + ChatColor.AQUA + hcp.getSpiderKills());
sender.sendMessage(ChatColor.YELLOW + "Ender Kills : " + ChatColor.AQUA + hcp.getEnderKills());
sender.sendMessage(ChatColor.YELLOW + "Slime Kills : " + ChatColor.AQUA + hcp.getSlimeKills());
sender.sendMessage(ChatColor.YELLOW + "Moosh Kills : " + ChatColor.AQUA + hcp.getMooshKills());
sender.sendMessage(ChatColor.YELLOW + "Other Kills : " + ChatColor.AQUA + hcp.getOtherKills());
sender.sendMessage(ChatColor.YELLOW + "Player Kills : " + ChatColor.AQUA + hcp.getPlayerKills());
}
}
}
else if (action.equals("DUMPWORLDS")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 1) {
for (String key : plugin.HardcoreWorlds.keySet()) {
HardcoreWorld hcw = plugin.HardcoreWorlds.get(key);
sender.sendMessage(ChatColor.YELLOW + "World Name : " + ChatColor.AQUA + hcw.getWorld().getName());
sender.sendMessage(ChatColor.YELLOW + "Greeting : " + ChatColor.AQUA + ChatColor.translateAlternateColorCodes('&', hcw.getGreeting()));
sender.sendMessage(ChatColor.YELLOW + "Ban Time : " + ChatColor.AQUA + hcw.getBantime());
sender.sendMessage(ChatColor.YELLOW + "Distance : " + ChatColor.AQUA + hcw.getSpawnDistance());
sender.sendMessage(ChatColor.YELLOW + "Protection : " + ChatColor.AQUA + hcw.getSpawnProtection());
sender.sendMessage(ChatColor.YELLOW + "ExitPos : " + ChatColor.AQUA + hcw.getExitPos());
}
}
}
else if (action.equals("SET")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 3) {
if (args[1].toUpperCase() == "EXIT") {
World world = plugin.getServer().getWorld(args[2]);
if ((world != null) && (plugin.IsHardcoreWorld(world))) {
HardcoreWorld hcw = plugin.HardcoreWorlds.get(world.getName());
plugin.Debug("Setting ExitPos for " + hcw.getWorld().getName());
Player player = (Player) sender;
hcw.setExitPos(player.getLocation());
plugin.Config().set("worlds." + world.getName() + ".exitpos", Util.Loc2Str(player.getLocation(), true));
plugin.saveConfig();
} else {
sender.sendMessage(ChatColor.RED + "Not a valid hardcore world");
}
} else {
sender.sendMessage(ChatColor.RED + "Invalid option");
}
}
}
else if (action.equals("LIST") || action.equals("WHO")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.list")) { return true; }
}
sender.sendMessage(ChatColor.GREEN + "Players currently in hardcore worlds:");
boolean Playing = false;
for (String w : plugin.HardcoreWorlds.keySet()) {
World world = plugin.getServer().getWorld(w);
if ((world != null) && (world.getPlayers().size() > 0)) {
ArrayList<String> players = new ArrayList<String>();
for (Player p : world.getPlayers()) {
Playing = true;
players.add(p.getName());
}
sender.sendMessage(ChatColor.YELLOW + world.getName() + ": " + ChatColor.AQUA + StringUtils.join(players, ", "));
}
}
if (!Playing) {
sender.sendMessage(ChatColor.RED + "None");
}
}
else if (action.equals("STATS") || action.equals("KILLS")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
if (hcp == null) {
sender.sendMessage(ChatColor.RED + "You must be in the hardcore world to use this command");
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (!plugin.IsHardcoreWorld(player.getWorld())) {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
}
if (hcp != null) {
sender.sendMessage(ChatColor.GREEN + "Hardcore player statistics:");
sender.sendMessage(ChatColor.YELLOW + "Cow Kills : " + ChatColor.AQUA + hcp.getCowKills());
sender.sendMessage(ChatColor.YELLOW + "Pig Kills : " + ChatColor.AQUA + hcp.getPigKills());
sender.sendMessage(ChatColor.YELLOW + "Sheep Kills : " + ChatColor.AQUA + hcp.getSheepKills());
sender.sendMessage(ChatColor.YELLOW + "Chicken Kills : " + ChatColor.AQUA + hcp.getChickenKills());
sender.sendMessage(ChatColor.YELLOW + "Creeper Kills : " + ChatColor.AQUA + hcp.getCreeperKills());
sender.sendMessage(ChatColor.YELLOW + "Zombie Kills : " + ChatColor.AQUA + hcp.getZombieKills());
sender.sendMessage(ChatColor.YELLOW + "Skeleton Kills : " + ChatColor.AQUA + hcp.getSkeletonKills());
sender.sendMessage(ChatColor.YELLOW + "Spider Kills : " + ChatColor.AQUA + hcp.getSpiderKills());
sender.sendMessage(ChatColor.YELLOW + "Ender Kills : " + ChatColor.AQUA + hcp.getEnderKills());
sender.sendMessage(ChatColor.YELLOW + "Slime Kills : " + ChatColor.AQUA + hcp.getSlimeKills());
sender.sendMessage(ChatColor.YELLOW + "Moosh Kills : " + ChatColor.AQUA + hcp.getMooshKills());
sender.sendMessage(ChatColor.YELLOW + "Other Kills : " + ChatColor.AQUA + hcp.getOtherKills());
sender.sendMessage(ChatColor.YELLOW + "Player Kills : " + ChatColor.AQUA + hcp.getPlayerKills());
}
}
else if (action.equals("SAVE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.Debug("Saving buffered data...");
plugin.SaveAllPlayers();
}
else if (action.equals("RELOAD")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.LoadWhiteList();
}
else if (action.equals("DISABLE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.GameEnabled = false;
sender.sendMessage(ChatColor.RED + "TrueHardcore has been disabled.");
}
else if (action.equals("ENABLE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.GameEnabled = true;
sender.sendMessage(ChatColor.GREEN + "TrueHardcore has been enabled.");
}
else {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:");
sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game");
sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)");
sender.sendMessage(ChatColor.AQUA + "/th list " + ChatColor.YELLOW + ": List the current hardcore players");
sender.sendMessage(ChatColor.AQUA + "/th info " + ChatColor.YELLOW + ": Display your current game information");
sender.sendMessage(ChatColor.AQUA + "/th stats " + ChatColor.YELLOW + ": Display kill statistics");
}
return true;
}
| public boolean onCommand(CommandSender sender, Command cmd, String commandLabel, String[] args) {
String action = "";
if (args.length > 0) {
action = args[0].toUpperCase();
}
if (action.equals("PLAY")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.use")) { return true; }
}
if (args.length > 1) {
World world = plugin.getServer().getWorld(args[1]);
if (world == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown world!");
return true;
}
if (plugin.IsHardcoreWorld(world)) {
plugin.PlayGame(world.getName(), (Player) sender);
} else {
sender.sendMessage(ChatColor.RED + "Error: That is not a hardcore world!");
}
} else {
sender.sendMessage(ChatColor.YELLOW + "Usage: /th play <world>");
}
}
else if (action.equals("LEAVE")) {
plugin.LeaveGame((Player) sender);
}
else if (action.equals("INFO")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
if (hcp != null) {
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "You must be in the hardcore world to use this command");
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (plugin.IsHardcoreWorld(player.getWorld())) {
hcp.updatePlayer(player);
} else {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.info.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp != null) {
Player player = (Player) plugin.getServer().getPlayer(args[2]);
if (player != null) {
if (plugin.IsHardcoreWorld(player.getWorld())) {
if (args[1] == player.getWorld().getName()) {
hcp.updatePlayer(player);
}
}
}
} else {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
}
if (hcp != null) {
Integer gt;
if (hcp.getState() == PlayerState.IN_GAME) {
gt = (hcp.getGameTime() + hcp.TimeDiff(hcp.getLastJoin(), new Date()));
} else {
gt = hcp.getGameTime();
}
String gametime = Util.Long2Time(gt);
sender.sendMessage(ChatColor.GREEN + "Hardcore player information:");
sender.sendMessage(ChatColor.YELLOW + "Player: " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World: " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "State: " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "Game Time: " + ChatColor.AQUA + gametime);
sender.sendMessage(ChatColor.YELLOW + "Current Level: " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Total Score: " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "Total Deaths: " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Top Score: " + ChatColor.AQUA + hcp.getTopScore());
}
}
else if (action.equals("DUMP")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 1) {
for (String key : plugin.HCPlayers.AllRecords().keySet()) {
HardcorePlayer hcp = plugin.HCPlayers.Get(key);
sender.sendMessage(Util.padRight(key, 30) + " " + hcp.getState());
}
}
else if (args.length == 3) {
HardcorePlayer hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp != null) {
sender.sendMessage(ChatColor.YELLOW + "Player Name : " + ChatColor.AQUA + hcp.getPlayerName());
sender.sendMessage(ChatColor.YELLOW + "World : " + ChatColor.AQUA + hcp.getWorld());
sender.sendMessage(ChatColor.YELLOW + "LastPos : " + ChatColor.AQUA + hcp.getLastPos());
sender.sendMessage(ChatColor.YELLOW + "LastJoin : " + ChatColor.AQUA + hcp.getLastJoin());
sender.sendMessage(ChatColor.YELLOW + "LastQuit : " + ChatColor.AQUA + hcp.getLastQuit());
sender.sendMessage(ChatColor.YELLOW + "GameStart : " + ChatColor.AQUA + hcp.getGameStart());
sender.sendMessage(ChatColor.YELLOW + "GameEnd : " + ChatColor.AQUA + hcp.getGameEnd());
sender.sendMessage(ChatColor.YELLOW + "GameTime : " + ChatColor.AQUA + hcp.getGameTime());
sender.sendMessage(ChatColor.YELLOW + "Level : " + ChatColor.AQUA + hcp.getLevel());
sender.sendMessage(ChatColor.YELLOW + "Exp : " + ChatColor.AQUA + hcp.getExp());
sender.sendMessage(ChatColor.YELLOW + "Score : " + ChatColor.AQUA + hcp.getScore());
sender.sendMessage(ChatColor.YELLOW + "TopScore : " + ChatColor.AQUA + hcp.getTopScore());
sender.sendMessage(ChatColor.YELLOW + "State : " + ChatColor.AQUA + hcp.getState());
sender.sendMessage(ChatColor.YELLOW + "GodMode : " + ChatColor.AQUA + hcp.isGodMode());
sender.sendMessage(ChatColor.YELLOW + "DeathMsg : " + ChatColor.AQUA + hcp.getDeathMsg());
sender.sendMessage(ChatColor.YELLOW + "DeathPos : " + ChatColor.AQUA + hcp.getDeathPos());
sender.sendMessage(ChatColor.YELLOW + "Deaths : " + ChatColor.AQUA + hcp.getDeaths());
sender.sendMessage(ChatColor.YELLOW + "Modified : " + ChatColor.AQUA + hcp.isModified());
sender.sendMessage(ChatColor.YELLOW + "Cow Kills : " + ChatColor.AQUA + hcp.getCowKills());
sender.sendMessage(ChatColor.YELLOW + "Pig Kills : " + ChatColor.AQUA + hcp.getPigKills());
sender.sendMessage(ChatColor.YELLOW + "Sheep Kills : " + ChatColor.AQUA + hcp.getSheepKills());
sender.sendMessage(ChatColor.YELLOW + "Chicken Kills : " + ChatColor.AQUA + hcp.getChickenKills());
sender.sendMessage(ChatColor.YELLOW + "Creeper Kills : " + ChatColor.AQUA + hcp.getCreeperKills());
sender.sendMessage(ChatColor.YELLOW + "Zombie Kills : " + ChatColor.AQUA + hcp.getZombieKills());
sender.sendMessage(ChatColor.YELLOW + "Skeleton Kills : " + ChatColor.AQUA + hcp.getSkeletonKills());
sender.sendMessage(ChatColor.YELLOW + "Spider Kills : " + ChatColor.AQUA + hcp.getSpiderKills());
sender.sendMessage(ChatColor.YELLOW + "Ender Kills : " + ChatColor.AQUA + hcp.getEnderKills());
sender.sendMessage(ChatColor.YELLOW + "Slime Kills : " + ChatColor.AQUA + hcp.getSlimeKills());
sender.sendMessage(ChatColor.YELLOW + "Moosh Kills : " + ChatColor.AQUA + hcp.getMooshKills());
sender.sendMessage(ChatColor.YELLOW + "Other Kills : " + ChatColor.AQUA + hcp.getOtherKills());
sender.sendMessage(ChatColor.YELLOW + "Player Kills : " + ChatColor.AQUA + hcp.getPlayerKills());
}
}
}
else if (action.equals("DUMPWORLDS")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 1) {
for (String key : plugin.HardcoreWorlds.keySet()) {
HardcoreWorld hcw = plugin.HardcoreWorlds.get(key);
sender.sendMessage(ChatColor.YELLOW + "World Name : " + ChatColor.AQUA + hcw.getWorld().getName());
sender.sendMessage(ChatColor.YELLOW + "Greeting : " + ChatColor.AQUA + ChatColor.translateAlternateColorCodes('&', hcw.getGreeting()));
sender.sendMessage(ChatColor.YELLOW + "Ban Time : " + ChatColor.AQUA + hcw.getBantime());
sender.sendMessage(ChatColor.YELLOW + "Distance : " + ChatColor.AQUA + hcw.getSpawnDistance());
sender.sendMessage(ChatColor.YELLOW + "Protection : " + ChatColor.AQUA + hcw.getSpawnProtection());
sender.sendMessage(ChatColor.YELLOW + "ExitPos : " + ChatColor.AQUA + hcw.getExitPos());
}
}
}
else if (action.equals("SET")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
if (args.length == 3) {
if (args[1].toUpperCase().equals("EXIT")) {
World world = plugin.getServer().getWorld(args[2]);
if ((world != null) && (plugin.IsHardcoreWorld(world))) {
HardcoreWorld hcw = plugin.HardcoreWorlds.get(world.getName());
plugin.Debug("Setting ExitPos for " + hcw.getWorld().getName());
Player player = (Player) sender;
hcw.setExitPos(player.getLocation());
plugin.Config().set("worlds." + world.getName() + ".exitpos", Util.Loc2Str(player.getLocation(), true));
plugin.saveConfig();
} else {
sender.sendMessage(ChatColor.RED + "Not a valid hardcore world");
}
} else {
sender.sendMessage(ChatColor.RED + "Invalid option \"" + args[1] + "\"");
}
}
}
else if (action.equals("LIST") || action.equals("WHO")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.list")) { return true; }
}
sender.sendMessage(ChatColor.GREEN + "Players currently in hardcore worlds:");
boolean Playing = false;
for (String w : plugin.HardcoreWorlds.keySet()) {
World world = plugin.getServer().getWorld(w);
if ((world != null) && (world.getPlayers().size() > 0)) {
ArrayList<String> players = new ArrayList<String>();
for (Player p : world.getPlayers()) {
Playing = true;
players.add(p.getName());
}
sender.sendMessage(ChatColor.YELLOW + world.getName() + ": " + ChatColor.AQUA + StringUtils.join(players, ", "));
}
}
if (!Playing) {
sender.sendMessage(ChatColor.RED + "None");
}
}
else if (action.equals("STATS") || action.equals("KILLS")) {
HardcorePlayer hcp = null;
if (args.length == 1) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats")) { return true; }
Player player = (Player) sender;
hcp = plugin.HCPlayers.Get(player);
if (hcp == null) {
sender.sendMessage(ChatColor.RED + "You must be in the hardcore world to use this command");
}
} else {
sender.sendMessage(ChatColor.RED + "Usage: /th info <player> [world]");
}
}
else if (args.length == 2) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats.other")) { return true; }
}
Player player = (Player) plugin.getServer().getPlayer(args[1]);
if (player != null) {
hcp = plugin.HCPlayers.Get(player);
if (!plugin.IsHardcoreWorld(player.getWorld())) {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
} else {
sender.sendMessage(ChatColor.RED + "Unknown player");
}
}
else if (args.length == 3) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.stats.other")) { return true; }
}
hcp = plugin.HCPlayers.Get(args[2], args[1]);
if (hcp == null) {
sender.sendMessage(ChatColor.RED + "Error: Unknown player!");
}
}
if (hcp != null) {
sender.sendMessage(ChatColor.GREEN + "Hardcore player statistics:");
sender.sendMessage(ChatColor.YELLOW + "Cow Kills : " + ChatColor.AQUA + hcp.getCowKills());
sender.sendMessage(ChatColor.YELLOW + "Pig Kills : " + ChatColor.AQUA + hcp.getPigKills());
sender.sendMessage(ChatColor.YELLOW + "Sheep Kills : " + ChatColor.AQUA + hcp.getSheepKills());
sender.sendMessage(ChatColor.YELLOW + "Chicken Kills : " + ChatColor.AQUA + hcp.getChickenKills());
sender.sendMessage(ChatColor.YELLOW + "Creeper Kills : " + ChatColor.AQUA + hcp.getCreeperKills());
sender.sendMessage(ChatColor.YELLOW + "Zombie Kills : " + ChatColor.AQUA + hcp.getZombieKills());
sender.sendMessage(ChatColor.YELLOW + "Skeleton Kills : " + ChatColor.AQUA + hcp.getSkeletonKills());
sender.sendMessage(ChatColor.YELLOW + "Spider Kills : " + ChatColor.AQUA + hcp.getSpiderKills());
sender.sendMessage(ChatColor.YELLOW + "Ender Kills : " + ChatColor.AQUA + hcp.getEnderKills());
sender.sendMessage(ChatColor.YELLOW + "Slime Kills : " + ChatColor.AQUA + hcp.getSlimeKills());
sender.sendMessage(ChatColor.YELLOW + "Moosh Kills : " + ChatColor.AQUA + hcp.getMooshKills());
sender.sendMessage(ChatColor.YELLOW + "Other Kills : " + ChatColor.AQUA + hcp.getOtherKills());
sender.sendMessage(ChatColor.YELLOW + "Player Kills : " + ChatColor.AQUA + hcp.getPlayerKills());
}
}
else if (action.equals("SAVE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.Debug("Saving buffered data...");
plugin.SaveAllPlayers();
}
else if (action.equals("RELOAD")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.LoadWhiteList();
}
else if (action.equals("DISABLE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.GameEnabled = false;
sender.sendMessage(ChatColor.RED + "TrueHardcore has been disabled.");
}
else if (action.equals("ENABLE")) {
if (sender instanceof Player) {
if (!Util.RequirePermission((Player) sender, "truehardcore.admin")) { return true; }
}
plugin.GameEnabled = true;
sender.sendMessage(ChatColor.GREEN + "TrueHardcore has been enabled.");
}
else {
sender.sendMessage(ChatColor.LIGHT_PURPLE + "TrueHardcore Commands:");
sender.sendMessage(ChatColor.AQUA + "/th play " + ChatColor.YELLOW + ": Start or resume your hardcore game");
sender.sendMessage(ChatColor.AQUA + "/th leave " + ChatColor.YELLOW + ": Leave the hardcore game (progress is saved)");
sender.sendMessage(ChatColor.AQUA + "/th list " + ChatColor.YELLOW + ": List the current hardcore players");
sender.sendMessage(ChatColor.AQUA + "/th info " + ChatColor.YELLOW + ": Display your current game information");
sender.sendMessage(ChatColor.AQUA + "/th stats " + ChatColor.YELLOW + ": Display kill statistics");
}
return true;
}
|
diff --git a/src/com/modcrafting/diablodrops/listeners/TomeListener.java b/src/com/modcrafting/diablodrops/listeners/TomeListener.java
index d15b0ef..8890a4e 100644
--- a/src/com/modcrafting/diablodrops/listeners/TomeListener.java
+++ b/src/com/modcrafting/diablodrops/listeners/TomeListener.java
@@ -1,129 +1,129 @@
package com.modcrafting.diablodrops.listeners;
import java.util.Iterator;
import org.bukkit.ChatColor;
import org.bukkit.Material;
import org.bukkit.entity.Player;
import org.bukkit.event.Event.Result;
import org.bukkit.event.EventHandler;
import org.bukkit.event.EventPriority;
import org.bukkit.event.Listener;
import org.bukkit.event.block.Action;
import org.bukkit.event.inventory.CraftItemEvent;
import org.bukkit.event.player.PlayerInteractEvent;
import org.bukkit.inventory.ItemStack;
import org.bukkit.inventory.PlayerInventory;
import org.bukkit.inventory.meta.BookMeta;
import org.bukkit.inventory.meta.ItemMeta;
import com.modcrafting.diablodrops.DiabloDrops;
import com.modcrafting.diablodrops.events.IdentifyItemEvent;
import com.modcrafting.diablodrops.items.IdentifyTome;
public class TomeListener implements Listener
{
private final DiabloDrops plugin;
public TomeListener(final DiabloDrops plugin)
{
this.plugin = plugin;
}
public ChatColor findColor(final String s)
{
char[] c = s.toCharArray();
for (int i = 0; i < c.length; i++)
if ((c[i] == new Character((char) 167)) && ((i + 1) < c.length))
return ChatColor.getByChar(c[i + 1]);
return null;
}
@EventHandler
public void onCraftItem(final CraftItemEvent e)
{
ItemStack item = e.getCurrentItem();
if (item.getType().equals(Material.WRITTEN_BOOK))
{
if (e.isShiftClick())
{
e.setCancelled(true);
}
e.setCurrentItem(new IdentifyTome());
}
}
@SuppressWarnings("deprecation")
@EventHandler(priority = EventPriority.LOWEST)
public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
if (b.getTitle().contains("Identity Tome") && b.getAuthor().endsWith("AAAA"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.dropsAPI.canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta = tool.getItemMeta();
String name = meta.getDisplayName();
- if ((!ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.name())
- && !ChatColor.getLastColors(name).equalsIgnoreCase( ChatColor.MAGIC.toString()))
- && (!name.contains(ChatColor.MAGIC.name()) && !name
- .contains(ChatColor.MAGIC.toString())))
+ if ((ChatColor.getLastColors(name)==null||(
+ !ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.name())
+ && !ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.toString()))
+ && (!name.contains(ChatColor.MAGIC.name()) && !name.contains(ChatColor.MAGIC.toString()))))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.dropsAPI.getItem(tool);
while ((item == null)
|| item.getItemMeta().getDisplayName().contains(
ChatColor.MAGIC.toString()))
{
item = plugin.dropsAPI.getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
}
| true | true | public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
if (b.getTitle().contains("Identity Tome") && b.getAuthor().endsWith("AAAA"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.dropsAPI.canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta = tool.getItemMeta();
String name = meta.getDisplayName();
if ((!ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.name())
&& !ChatColor.getLastColors(name).equalsIgnoreCase( ChatColor.MAGIC.toString()))
&& (!name.contains(ChatColor.MAGIC.name()) && !name
.contains(ChatColor.MAGIC.toString())))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.dropsAPI.getItem(tool);
while ((item == null)
|| item.getItemMeta().getDisplayName().contains(
ChatColor.MAGIC.toString()))
{
item = plugin.dropsAPI.getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
| public void onRightClick(final PlayerInteractEvent e)
{
if ((e.getAction().equals(Action.RIGHT_CLICK_AIR) || e.getAction()
.equals(Action.RIGHT_CLICK_BLOCK))
&& e.getPlayer().getItemInHand().getType()
.equals(Material.WRITTEN_BOOK))
{
ItemStack inh = e.getPlayer().getItemInHand();
BookMeta b = (BookMeta) inh.getItemMeta();
if (b == null)
return;
if (b.getTitle().contains("Identity Tome") && b.getAuthor().endsWith("AAAA"))
{
Player p = e.getPlayer();
PlayerInventory pi = p.getInventory();
p.updateInventory();
Iterator<ItemStack> itis = pi.iterator();
while (itis.hasNext())
{
ItemStack tool = itis.next();
if ((tool == null)
|| !plugin.dropsAPI.canBeItem(tool.getType()))
{
continue;
}
ItemMeta meta = tool.getItemMeta();
String name = meta.getDisplayName();
if ((ChatColor.getLastColors(name)==null||(
!ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.name())
&& !ChatColor.getLastColors(name).equalsIgnoreCase(ChatColor.MAGIC.toString()))
&& (!name.contains(ChatColor.MAGIC.name()) && !name.contains(ChatColor.MAGIC.toString()))))
{
continue;
}
IdentifyItemEvent iie = new IdentifyItemEvent(tool);
plugin.getServer().getPluginManager().callEvent(iie);
if (iie.isCancelled())
{
p.sendMessage(ChatColor.RED
+ "You are unable to identify right now.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
pi.setItemInHand(null);
ItemStack item = plugin.dropsAPI.getItem(tool);
while ((item == null)
|| item.getItemMeta().getDisplayName().contains(
ChatColor.MAGIC.toString()))
{
item = plugin.dropsAPI.getItem(tool);
}
pi.removeItem(tool);
pi.addItem(item);
p.sendMessage(ChatColor.GREEN
+ "You have identified an item!");
p.updateInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
p.closeInventory();
return;
}
p.sendMessage(ChatColor.RED + "You have no items to identify.");
p.closeInventory();
e.setUseItemInHand(Result.DENY);
e.setCancelled(true);
return;
}
}
}
|
diff --git a/gsf-action/src/main/java/com/fatwire/gst/foundation/include/IncludeTemplate.java b/gsf-action/src/main/java/com/fatwire/gst/foundation/include/IncludeTemplate.java
index 1d7e1f1a..a9dd44f4 100644
--- a/gsf-action/src/main/java/com/fatwire/gst/foundation/include/IncludeTemplate.java
+++ b/gsf-action/src/main/java/com/fatwire/gst/foundation/include/IncludeTemplate.java
@@ -1,200 +1,200 @@
/*
* Copyright 2011 FatWire Corporation. All Rights Reserved.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.fatwire.gst.foundation.include;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;
import java.util.Locale;
import COM.FutureTense.Interfaces.ICS;
import com.fatwire.assetapi.data.AssetId;
import com.fatwire.gst.foundation.facade.runtag.render.CallTemplate;
import com.fatwire.gst.foundation.facade.runtag.render.CallTemplate.Style;
import com.fatwire.gst.foundation.facade.runtag.render.CallTemplate.Type;
import org.apache.commons.lang.StringUtils;
/**
* @author Dolf Dijkstra
* @since Apr 13, 2011
*/
public class IncludeTemplate implements Include {
public static final List<String> FORBIDDEN_VARS = Collections.unmodifiableList(Arrays.asList("c", "cid", "eid",
"seid", "packedargs", "variant", "context", "pagename", "childpagename", "site", "sitepfx", "tid",
"rendermode", "ft_ss"));
private final CallTemplate tag;
private final List<String> pc;
private final ICS ics;
/**
* @param ics Content Server context
* @param asset asset to render
* @param tname template name
*/
public IncludeTemplate(final ICS ics, final AssetId asset, final String tname) {
this.ics = ics;
tag = new CallTemplate();
tag.setTname(tname);
final String eid = ics.GetVar("eid");
if (eid != null) {
tag.setTid(eid);
tag.setTtype(Type.CSElement);
} else {
tag.setTid(ics.GetVar("tid"));
tag.setTtype(Type.Template);
}
tag.setContext("");
final String site = ics.GetVar("site");
tag.setSite(site);
final String packedargs = ics.GetVar("packedargs");
if (packedargs != null && packedargs.length() > 0) {
tag.setPackedargs(packedargs);
}
tag.setAsset(asset);
tag.setFixPageCriteria(false); // for some reason the check pagecriteria
// code in CallTemplate is not working.
tag.setSlotname("foo");
- final String target = tname.startsWith("/") ? site + "/" + tname : site + "/" + asset.getType() + "/" + tname;
+ final String target = tname.startsWith("/") ? site + tname : site + "/" + asset.getType() + "/" + tname;
final String[] keys = ics.pageCriteriaKeys(target);
if (keys == null) {
throw new IllegalArgumentException("Can't find page criteria for " + target
+ ". Please check if pagecriteria are set for " + target + ".");
}
pc = Arrays.asList(keys);
// copy the current available arguments
// developer can override later by calling arguments
for (final String k : keys) {
if (!FORBIDDEN_VARS.contains(k)) {
final String v = ics.GetVar(k);
if (StringUtils.isNotBlank(v)) {
argument(k, v);
}
}
}
}
/*
* (non-Javadoc)
*
* @see
* com.fatwire.gst.foundation.include.Include#include(COM.FutureTense.Interfaces
* .ICS)
*/
public void include(final ICS ics) {
final String s = tag.execute(ics);
if (s != null) {
ics.StreamText(s);
}
}
/**
* @param name
* @param value
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.CallTemplate#setArgument(java.lang.String,
* java.lang.String)
*/
public IncludeTemplate argument(final String name, final String value) {
if (StringUtils.isBlank(name)) {
return this;
}
if (FORBIDDEN_VARS.contains(name.toLowerCase(Locale.US))) {
throw new IllegalArgumentException("Can't deal with " + name
+ ". It is a forbidden argument to set as an argument. Forbidden arguments are: "
+ FORBIDDEN_VARS.toString());
}
if (pc.contains(name)) {
tag.setArgument(name, value);
} else {
throw new IllegalArgumentException("Can't deal with " + name
+ ". It not part of page criteria. PageCriteria are: " + pc.toString());
}
return this;
}
/**
* Copies the ics variables identified by the name array
*
* @param name
* @return this
*/
public IncludeTemplate copyArguments(final String... name) {
if (name == null) {
return this;
}
for (final String n : name) {
argument(n, ics.GetVar(n));
}
return this;
}
/**
* Adds packedargs.
*
* @param s packedargs
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.CallTemplate#setPackedargs(java.lang.String)
*/
public IncludeTemplate packedargs(final String s) {
tag.setPackedargs(s);
return this;
}
/**
* @param s style
* @return this
* @see com.fatwire.gst.foundation.facade.runtag.render.CallTemplate#setStyle(com.fatwire.gst.foundation.facade.runtag.render.CallTemplate.Style)
*/
public IncludeTemplate style(final Style s) {
tag.setStyle(s);
return this;
}
/**
* Sets Style to element
*
* @return this
*/
public IncludeTemplate element() {
return style(Style.element);
}
/**
* Sets Style to embedded
*
* @return this
*/
public IncludeTemplate embedded() {
return style(Style.embedded);
}
/**
* Sets Style to pagelet
*
* @return this
*/
public IncludeTemplate pagelet() {
return style(Style.pagelet);
}
}
| true | true | public IncludeTemplate(final ICS ics, final AssetId asset, final String tname) {
this.ics = ics;
tag = new CallTemplate();
tag.setTname(tname);
final String eid = ics.GetVar("eid");
if (eid != null) {
tag.setTid(eid);
tag.setTtype(Type.CSElement);
} else {
tag.setTid(ics.GetVar("tid"));
tag.setTtype(Type.Template);
}
tag.setContext("");
final String site = ics.GetVar("site");
tag.setSite(site);
final String packedargs = ics.GetVar("packedargs");
if (packedargs != null && packedargs.length() > 0) {
tag.setPackedargs(packedargs);
}
tag.setAsset(asset);
tag.setFixPageCriteria(false); // for some reason the check pagecriteria
// code in CallTemplate is not working.
tag.setSlotname("foo");
final String target = tname.startsWith("/") ? site + "/" + tname : site + "/" + asset.getType() + "/" + tname;
final String[] keys = ics.pageCriteriaKeys(target);
if (keys == null) {
throw new IllegalArgumentException("Can't find page criteria for " + target
+ ". Please check if pagecriteria are set for " + target + ".");
}
pc = Arrays.asList(keys);
// copy the current available arguments
// developer can override later by calling arguments
for (final String k : keys) {
if (!FORBIDDEN_VARS.contains(k)) {
final String v = ics.GetVar(k);
if (StringUtils.isNotBlank(v)) {
argument(k, v);
}
}
}
}
| public IncludeTemplate(final ICS ics, final AssetId asset, final String tname) {
this.ics = ics;
tag = new CallTemplate();
tag.setTname(tname);
final String eid = ics.GetVar("eid");
if (eid != null) {
tag.setTid(eid);
tag.setTtype(Type.CSElement);
} else {
tag.setTid(ics.GetVar("tid"));
tag.setTtype(Type.Template);
}
tag.setContext("");
final String site = ics.GetVar("site");
tag.setSite(site);
final String packedargs = ics.GetVar("packedargs");
if (packedargs != null && packedargs.length() > 0) {
tag.setPackedargs(packedargs);
}
tag.setAsset(asset);
tag.setFixPageCriteria(false); // for some reason the check pagecriteria
// code in CallTemplate is not working.
tag.setSlotname("foo");
final String target = tname.startsWith("/") ? site + tname : site + "/" + asset.getType() + "/" + tname;
final String[] keys = ics.pageCriteriaKeys(target);
if (keys == null) {
throw new IllegalArgumentException("Can't find page criteria for " + target
+ ". Please check if pagecriteria are set for " + target + ".");
}
pc = Arrays.asList(keys);
// copy the current available arguments
// developer can override later by calling arguments
for (final String k : keys) {
if (!FORBIDDEN_VARS.contains(k)) {
final String v = ics.GetVar(k);
if (StringUtils.isNotBlank(v)) {
argument(k, v);
}
}
}
}
|
diff --git a/juddi-core/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java b/juddi-core/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java
index 714ae685e..666f03027 100644
--- a/juddi-core/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java
+++ b/juddi-core/src/main/java/org/apache/juddi/api/impl/AuthenticatedService.java
@@ -1,111 +1,111 @@
/*
* Copyright 2001-2008 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.juddi.api.impl;
import java.util.Date;
import javax.persistence.EntityManager;
import org.apache.commons.configuration.ConfigurationException;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.apache.juddi.config.AppConfig;
import org.apache.juddi.config.Property;
import org.apache.juddi.model.UddiEntityPublisher;
import org.apache.juddi.v3.auth.Authenticator;
import org.apache.juddi.v3.auth.AuthenticatorFactory;
import org.apache.juddi.v3.error.AuthTokenRequiredException;
import org.apache.juddi.v3.error.ErrorMessage;
import org.uddi.v3_service.DispositionReportFaultMessage;
/**Although this class is abstract, it provides token validation
* @author <a href="mailto:[email protected]">Jeff Faath</a>
*
* @author Alex O'Ree - modified to include token expiration validation
*/
public abstract class AuthenticatedService {
public static final int AUTHTOKEN_ACTIVE = 1;
public static final int AUTHTOKEN_RETIRED = 0;
Log logger = LogFactory.getLog(this.getClass());
public UddiEntityPublisher getEntityPublisher(EntityManager em, String authInfo) throws DispositionReportFaultMessage {
if (authInfo == null || authInfo.length() == 0)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthRequired"));
org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, authInfo);
if (modelAuthToken == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
int allowedMinutesOfInactivity = 0;
try {
allowedMinutesOfInactivity = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_TIMEOUT, 0);
} catch (ConfigurationException ce) {
logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from "
+ "the application's configuration. No automatic timeout token invalidation will occur. "
+ ce.getMessage(), ce);
}
int maxMinutesOfAge = 0;
try {
maxMinutesOfAge = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_EXPIRATION, 0);
} catch (ConfigurationException ce) {
logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from "
+ "the application's configuration. No automatic timeout token invalidation will occur. "
+ ce.getMessage(), ce);
}
Date now = new Date();
// 0 or negative means token does not expire
if (allowedMinutesOfInactivity > 0) {
// expire tokens after # minutes of inactivity
// compare the time in milli-seconds
if (now.getTime() > modelAuthToken.getLastUsed().getTime() + allowedMinutesOfInactivity * 60000l) {
logger.debug("Token " + modelAuthToken.getAuthToken() + " expired due to inactivity");
modelAuthToken.setTokenState(AUTHTOKEN_RETIRED);
}
}
if (maxMinutesOfAge > 0) {
// expire tokens when max age is reached
// compare the time in milli-seconds
if (now.getTime() > modelAuthToken.getCreated().getTime() + maxMinutesOfAge * 60000l) {
logger.debug("Token " + modelAuthToken.getAuthToken() + " expired due to old age");
modelAuthToken.setTokenState(AUTHTOKEN_RETIRED);
}
}
if (modelAuthToken.getTokenState() == AUTHTOKEN_RETIRED)
- throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
+ throw new AuthTokenExpiredException(new ErrorMessage("errors.auth.AuthInvalid"));
Authenticator authenticator = AuthenticatorFactory.getAuthenticator();
UddiEntityPublisher entityPublisher = authenticator.identify(authInfo, modelAuthToken.getAuthorizedName());
// Must make sure the returned publisher has all the necessary fields filled
if (entityPublisher == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
if (entityPublisher.getAuthorizedName() == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
// Auth token is being used. Adjust appropriate values so that it's internal 'expiration clock' is reset.
modelAuthToken.setLastUsed(new Date());
modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1);
return entityPublisher;
}
}
| true | true | public UddiEntityPublisher getEntityPublisher(EntityManager em, String authInfo) throws DispositionReportFaultMessage {
if (authInfo == null || authInfo.length() == 0)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthRequired"));
org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, authInfo);
if (modelAuthToken == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
int allowedMinutesOfInactivity = 0;
try {
allowedMinutesOfInactivity = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_TIMEOUT, 0);
} catch (ConfigurationException ce) {
logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from "
+ "the application's configuration. No automatic timeout token invalidation will occur. "
+ ce.getMessage(), ce);
}
int maxMinutesOfAge = 0;
try {
maxMinutesOfAge = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_EXPIRATION, 0);
} catch (ConfigurationException ce) {
logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from "
+ "the application's configuration. No automatic timeout token invalidation will occur. "
+ ce.getMessage(), ce);
}
Date now = new Date();
// 0 or negative means token does not expire
if (allowedMinutesOfInactivity > 0) {
// expire tokens after # minutes of inactivity
// compare the time in milli-seconds
if (now.getTime() > modelAuthToken.getLastUsed().getTime() + allowedMinutesOfInactivity * 60000l) {
logger.debug("Token " + modelAuthToken.getAuthToken() + " expired due to inactivity");
modelAuthToken.setTokenState(AUTHTOKEN_RETIRED);
}
}
if (maxMinutesOfAge > 0) {
// expire tokens when max age is reached
// compare the time in milli-seconds
if (now.getTime() > modelAuthToken.getCreated().getTime() + maxMinutesOfAge * 60000l) {
logger.debug("Token " + modelAuthToken.getAuthToken() + " expired due to old age");
modelAuthToken.setTokenState(AUTHTOKEN_RETIRED);
}
}
if (modelAuthToken.getTokenState() == AUTHTOKEN_RETIRED)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
Authenticator authenticator = AuthenticatorFactory.getAuthenticator();
UddiEntityPublisher entityPublisher = authenticator.identify(authInfo, modelAuthToken.getAuthorizedName());
// Must make sure the returned publisher has all the necessary fields filled
if (entityPublisher == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
if (entityPublisher.getAuthorizedName() == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
// Auth token is being used. Adjust appropriate values so that it's internal 'expiration clock' is reset.
modelAuthToken.setLastUsed(new Date());
modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1);
return entityPublisher;
}
| public UddiEntityPublisher getEntityPublisher(EntityManager em, String authInfo) throws DispositionReportFaultMessage {
if (authInfo == null || authInfo.length() == 0)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthRequired"));
org.apache.juddi.model.AuthToken modelAuthToken = em.find(org.apache.juddi.model.AuthToken.class, authInfo);
if (modelAuthToken == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
int allowedMinutesOfInactivity = 0;
try {
allowedMinutesOfInactivity = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_TIMEOUT, 0);
} catch (ConfigurationException ce) {
logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from "
+ "the application's configuration. No automatic timeout token invalidation will occur. "
+ ce.getMessage(), ce);
}
int maxMinutesOfAge = 0;
try {
maxMinutesOfAge = AppConfig.getConfiguration().getInt(Property.JUDDI_AUTH_TOKEN_EXPIRATION, 0);
} catch (ConfigurationException ce) {
logger.error("Error reading property " + Property.JUDDI_AUTH_TOKEN_EXPIRATION + " from "
+ "the application's configuration. No automatic timeout token invalidation will occur. "
+ ce.getMessage(), ce);
}
Date now = new Date();
// 0 or negative means token does not expire
if (allowedMinutesOfInactivity > 0) {
// expire tokens after # minutes of inactivity
// compare the time in milli-seconds
if (now.getTime() > modelAuthToken.getLastUsed().getTime() + allowedMinutesOfInactivity * 60000l) {
logger.debug("Token " + modelAuthToken.getAuthToken() + " expired due to inactivity");
modelAuthToken.setTokenState(AUTHTOKEN_RETIRED);
}
}
if (maxMinutesOfAge > 0) {
// expire tokens when max age is reached
// compare the time in milli-seconds
if (now.getTime() > modelAuthToken.getCreated().getTime() + maxMinutesOfAge * 60000l) {
logger.debug("Token " + modelAuthToken.getAuthToken() + " expired due to old age");
modelAuthToken.setTokenState(AUTHTOKEN_RETIRED);
}
}
if (modelAuthToken.getTokenState() == AUTHTOKEN_RETIRED)
throw new AuthTokenExpiredException(new ErrorMessage("errors.auth.AuthInvalid"));
Authenticator authenticator = AuthenticatorFactory.getAuthenticator();
UddiEntityPublisher entityPublisher = authenticator.identify(authInfo, modelAuthToken.getAuthorizedName());
// Must make sure the returned publisher has all the necessary fields filled
if (entityPublisher == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
if (entityPublisher.getAuthorizedName() == null)
throw new AuthTokenRequiredException(new ErrorMessage("errors.auth.AuthInvalid"));
// Auth token is being used. Adjust appropriate values so that it's internal 'expiration clock' is reset.
modelAuthToken.setLastUsed(new Date());
modelAuthToken.setNumberOfUses(modelAuthToken.getNumberOfUses() + 1);
return entityPublisher;
}
|
diff --git a/BasicGame/src/mygame/States/Scenario/Scenario.java b/BasicGame/src/mygame/States/Scenario/Scenario.java
index 4882b3d..ffb2e1e 100755
--- a/BasicGame/src/mygame/States/Scenario/Scenario.java
+++ b/BasicGame/src/mygame/States/Scenario/Scenario.java
@@ -1,78 +1,78 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package mygame.States.Scenario;
import com.jme3.app.SimpleApplication;
import com.jme3.app.state.AbstractAppState;
import com.jme3.asset.AssetManager;
import com.jme3.bullet.BulletAppState;
import com.jme3.bullet.collision.shapes.CollisionShape;
import com.jme3.bullet.control.RigidBodyControl;
import com.jme3.bullet.util.CollisionShapeFactory;
import com.jme3.light.AmbientLight;
import com.jme3.light.DirectionalLight;
import com.jme3.math.ColorRGBA;
import com.jme3.math.Vector3f;
import com.jme3.renderer.ViewPort;
import com.jme3.scene.Node;
import com.jme3.scene.Spatial;
/**
*
* @author Harpo
*/
public class Scenario {
private final Node rootNode;
private final ViewPort viewPort;
private final AssetManager assetManager;
private final ColorRGBA backgroundColor = ColorRGBA.Blue;
private Spatial sceneModel;
private RigidBodyControl landscape;
private SimpleApplication app;
public Scenario(SimpleApplication app) {
this.rootNode = app.getRootNode();
this.viewPort = app.getViewPort();
this.assetManager = app.getAssetManager();
this.app = app;
//Ponemos el fondo en color azul
viewPort.setBackgroundColor(backgroundColor);
//Cargamos el escenario
sceneModel = assetManager.loadModel("Scenes/montextura.j3o");
sceneModel.setLocalScale(2f);
// We set up collision detection for the scene by creating a
// compound collision shape and a static RigidBodyControl with mass zero.
CollisionShape sceneShape =
CollisionShapeFactory.createMeshShape((Node) sceneModel);
landscape = new RigidBodyControl(sceneShape, 0);
sceneModel.addControl(landscape);
sceneModel.setName("Escenario");
- rootNode.attachChild(sceneModel);
+ //rootNode.attachChild(sceneModel);
this.app.getStateManager().getState(BulletAppState.class).getPhysicsSpace().add(landscape);
setUpLight();
}
public Spatial getEscenari(){
return this.sceneModel;
}
private void setUpLight() {
// We add light so we see the scene
AmbientLight al = new AmbientLight();
al.setColor(ColorRGBA.White.mult(1.3f));
rootNode.addLight(al);
DirectionalLight dl = new DirectionalLight();
dl.setColor(ColorRGBA.White);
dl.setDirection(new Vector3f(2.8f, -2.8f, -2.8f).normalizeLocal());
rootNode.addLight(dl);
}
}
| true | true | public Scenario(SimpleApplication app) {
this.rootNode = app.getRootNode();
this.viewPort = app.getViewPort();
this.assetManager = app.getAssetManager();
this.app = app;
//Ponemos el fondo en color azul
viewPort.setBackgroundColor(backgroundColor);
//Cargamos el escenario
sceneModel = assetManager.loadModel("Scenes/montextura.j3o");
sceneModel.setLocalScale(2f);
// We set up collision detection for the scene by creating a
// compound collision shape and a static RigidBodyControl with mass zero.
CollisionShape sceneShape =
CollisionShapeFactory.createMeshShape((Node) sceneModel);
landscape = new RigidBodyControl(sceneShape, 0);
sceneModel.addControl(landscape);
sceneModel.setName("Escenario");
rootNode.attachChild(sceneModel);
this.app.getStateManager().getState(BulletAppState.class).getPhysicsSpace().add(landscape);
setUpLight();
}
| public Scenario(SimpleApplication app) {
this.rootNode = app.getRootNode();
this.viewPort = app.getViewPort();
this.assetManager = app.getAssetManager();
this.app = app;
//Ponemos el fondo en color azul
viewPort.setBackgroundColor(backgroundColor);
//Cargamos el escenario
sceneModel = assetManager.loadModel("Scenes/montextura.j3o");
sceneModel.setLocalScale(2f);
// We set up collision detection for the scene by creating a
// compound collision shape and a static RigidBodyControl with mass zero.
CollisionShape sceneShape =
CollisionShapeFactory.createMeshShape((Node) sceneModel);
landscape = new RigidBodyControl(sceneShape, 0);
sceneModel.addControl(landscape);
sceneModel.setName("Escenario");
//rootNode.attachChild(sceneModel);
this.app.getStateManager().getState(BulletAppState.class).getPhysicsSpace().add(landscape);
setUpLight();
}
|
diff --git a/org.emftext.test/src/org/emftext/test/bug674/Bug674Test.java b/org.emftext.test/src/org/emftext/test/bug674/Bug674Test.java
index d1a077f43..62e49573f 100644
--- a/org.emftext.test/src/org/emftext/test/bug674/Bug674Test.java
+++ b/org.emftext.test/src/org/emftext/test/bug674/Bug674Test.java
@@ -1,58 +1,58 @@
/*******************************************************************************
* Copyright (c) 2006-2009
* Software Technology Group, Dresden University of Technology
*
* This program is free software; you can redistribute it and/or modify it under
* the terms of the GNU Lesser General Public License as published by the Free
* Software Foundation; either version 2 of the License, or (at your option) any
* later version. This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
*
* See the GNU Lesser General Public License for more details. You should have
* received a copy of the GNU Lesser General Public License along with this
* program; if not, write to the Free Software Foundation, Inc., 59 Temple Place,
* Suite 330, Boston, MA 02111-1307 USA
*
* Contributors:
* Software Technology Group - TU Dresden, Germany
* - initial API and implementation
******************************************************************************/
package org.emftext.test.bug674;
import static org.emftext.test.ConcreteSyntaxTestHelper.registerResourceFactories;
import java.io.File;
import junit.framework.TestCase;
import org.emftext.runtime.resource.ITextResource;
import org.emftext.runtime.resource.impl.TextResourceHelper;
import org.emftext.sdk.SDKOptionProvider;
import org.emftext.sdk.syntax_analysis.GenModelAnalyser;
import org.junit.Before;
import org.junit.Test;
/**
* A test case for bug 674.
*/
public class Bug674Test extends TestCase {
@Before
public void setUp() {
registerResourceFactories();
}
@Test
public void testBug674() {
final String filename = "YggdrasilComponents.cs";
final String path = "src" + File.separator + "org" + File.separator + "emftext" + File.separator + "test" + File.separator + "bug674" + File.separator;
File file = new File(path + filename);
ITextResource resource = new TextResourceHelper().getResource(file, new SDKOptionProvider().getOptions());
assertNotNull(resource);
assertEquals(1, resource.getErrors().size());
String errorMessage = resource.getErrors().get(0).getMessage();
- assertEquals(GenModelAnalyser.INVALID_GENMODEL_MESSAGE, errorMessage);
+ assertTrue(errorMessage.matches("The genmodel .* is invalid. Please reconcile it."));
}
}
| true | true | public void testBug674() {
final String filename = "YggdrasilComponents.cs";
final String path = "src" + File.separator + "org" + File.separator + "emftext" + File.separator + "test" + File.separator + "bug674" + File.separator;
File file = new File(path + filename);
ITextResource resource = new TextResourceHelper().getResource(file, new SDKOptionProvider().getOptions());
assertNotNull(resource);
assertEquals(1, resource.getErrors().size());
String errorMessage = resource.getErrors().get(0).getMessage();
assertEquals(GenModelAnalyser.INVALID_GENMODEL_MESSAGE, errorMessage);
}
| public void testBug674() {
final String filename = "YggdrasilComponents.cs";
final String path = "src" + File.separator + "org" + File.separator + "emftext" + File.separator + "test" + File.separator + "bug674" + File.separator;
File file = new File(path + filename);
ITextResource resource = new TextResourceHelper().getResource(file, new SDKOptionProvider().getOptions());
assertNotNull(resource);
assertEquals(1, resource.getErrors().size());
String errorMessage = resource.getErrors().get(0).getMessage();
assertTrue(errorMessage.matches("The genmodel .* is invalid. Please reconcile it."));
}
|
diff --git a/esmska/src/esmska/gui/EditContactPanel.java b/esmska/src/esmska/gui/EditContactPanel.java
index 48153ec8..62e36734 100644
--- a/esmska/src/esmska/gui/EditContactPanel.java
+++ b/esmska/src/esmska/gui/EditContactPanel.java
@@ -1,404 +1,404 @@
/*
* EditContactPanel.java
*
* Created on 26. červenec 2007, 11:50
*/
package esmska.gui;
import esmska.data.Config;
import esmska.data.Contact;
import esmska.data.Keyring;
import esmska.data.Links;
import esmska.data.Gateway;
import esmska.data.Gateways;
import esmska.data.event.AbstractDocumentListener;
import esmska.utils.L10N;
import java.awt.Color;
import java.awt.Component;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.ItemEvent;
import java.awt.event.ItemListener;
import java.text.MessageFormat;
import java.util.Collection;
import java.util.ResourceBundle;
import javax.swing.Action;
import javax.swing.BorderFactory;
import javax.swing.GroupLayout;
import javax.swing.GroupLayout.Alignment;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JTextField;
import javax.swing.LayoutStyle.ComponentPlacement;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.event.DocumentEvent;
import org.apache.commons.lang.StringUtils;
import org.openide.awt.Mnemonics;
/** Add new or edit current contact
*
* @author ripper
*/
public class EditContactPanel extends javax.swing.JPanel {
private static final ResourceBundle l10n = L10N.l10nBundle;
private static final Border fieldBorder = new JTextField().getBorder();
private static final Border lineRedBorder = BorderFactory.createLineBorder(Color.RED);
private Config config = Config.getInstance();
private Keyring keyring = Keyring.getInstance();
private boolean multiMode; //edit multiple contacts
private boolean userSet; //whether gateway was set by user or by program
private Action suggestGatewayAction;
/**
* Creates new form EditContactPanel
*/
public EditContactPanel() {
initComponents();
//if not Substance LaF, add clipboard popup menu to text components
if (!config.getLookAndFeel().equals(ThemeManager.LAF.SUBSTANCE)) {
ClipboardPopupMenu.register(nameTextField);
ClipboardPopupMenu.register(numberTextField);
}
//set up button for suggesting gateway
suggestGatewayAction = Actions.getSuggestGatewayAction(gatewayComboBox, numberTextField);
suggestGatewayButton.setAction(suggestGatewayAction);
//listen for changes in number and guess gateway
numberTextField.getDocument().addDocumentListener(new AbstractDocumentListener() {
@Override
public void onUpdate(DocumentEvent e) {
if (!userSet) {
gatewayComboBox.selectSuggestedGateway(numberTextField.getText());
userSet = false;
}
updateCountryInfoLabel();
}
});
//update components
gatewayComboBoxItemStateChanged(null);
}
/** This method is called from within the constructor to
* initialize the form.
* WARNING: Do NOT modify this code. The content of this method is
* always regenerated by the Form Editor.
*/
// <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
private void initComponents() {
nameTextField = new JTextField();
nameTextField.requestFocusInWindow();
numberTextField = new JTextField() {
@Override
public String getText() {
String text = super.getText();
if (StringUtils.isNotEmpty(text) && !text.startsWith("+"))
text = config.getCountryPrefix() + text;
return text;
}
}
;
gatewayComboBox = new GatewayComboBox();
nameLabel = new JLabel();
numberLabel = new JLabel();
gatewayLabel = new JLabel();
suggestGatewayButton = new JButton();
jPanel1 = new JPanel();
countryInfoLabel = new InfoLabel();
credentialsInfoLabel = new InfoLabel();
nameTextField.setToolTipText(l10n.getString("EditContactPanel.nameTextField.toolTipText")); // NOI18N
nameTextField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent evt) {
nameTextFieldFocusLost(evt);
}
});
numberTextField.setColumns(13);
numberTextField.setToolTipText(l10n.getString("EditContactPanel.numberTextField.toolTipText")); // NOI18N
numberTextField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent evt) {
numberTextFieldFocusLost(evt);
}
});
gatewayComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
gatewayComboBoxItemStateChanged(evt);
}
});
nameLabel.setLabelFor(nameTextField);
Mnemonics.setLocalizedText(nameLabel, l10n.getString("EditContactPanel.nameLabel.text")); // NOI18N
nameLabel.setToolTipText(nameTextField.getToolTipText());
numberLabel.setLabelFor(numberTextField);
Mnemonics.setLocalizedText(numberLabel, l10n.getString("EditContactPanel.numberLabel.text")); // NOI18N
numberLabel.setToolTipText(numberTextField.getToolTipText());
gatewayLabel.setLabelFor(gatewayComboBox);
Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("EditContactPanel.gatewayLabel.text")); // NOI18N
gatewayLabel.setToolTipText(gatewayComboBox.getToolTipText());
suggestGatewayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
suggestGatewayButtonActionPerformed(evt);
}
});
Mnemonics.setLocalizedText(countryInfoLabel, l10n.getString("EditContactPanel.countryInfoLabel.text")); // NOI18N
countryInfoLabel.setVisible(false);
Mnemonics.setLocalizedText(credentialsInfoLabel,l10n.getString(
"EditContactPanel.credentialsInfoLabel.text"));
credentialsInfoLabel.setText(MessageFormat.format(
l10n.getString("EditContactPanel.credentialsInfoLabel.text"), Links.CONFIG_CREDENTIALS));
credentialsInfoLabel.setVisible(false);
GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(Alignment.LEADING)
- .addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 733, Short.MAX_VALUE)
- .addComponent(countryInfoLabel)
+ .addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
+ .addComponent(countryInfoLabel, GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(credentialsInfoLabel)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(countryInfoLabel))
);
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(numberLabel)
.addComponent(nameLabel)
.addComponent(gatewayLabel))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
- .addComponent(gatewayComboBox, GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
+ .addComponent(gatewayComboBox, GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(suggestGatewayButton))
- .addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 622, Short.MAX_VALUE)
- .addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 622, Short.MAX_VALUE))))
+ .addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
+ .addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE))))
.addContainerGap())
);
layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, nameLabel, numberLabel});
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(nameLabel)
.addComponent(nameTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(numberLabel)
.addComponent(numberTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(gatewayLabel)
.addComponent(gatewayComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(suggestGatewayButton))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
- .addContainerGap(74, Short.MAX_VALUE))
+ .addContainerGap(84, Short.MAX_VALUE))
);
layout.linkSize(SwingConstants.VERTICAL, new Component[] {nameTextField, numberTextField});
}// </editor-fold>//GEN-END:initComponents
/** Check if the form is valid */
public boolean validateForm() {
boolean valid = true;
boolean focusTransfered = false;
JComponent[] comps;
if (multiMode) {
comps = new JComponent[] {};
} else {
comps = new JComponent[] {nameTextField, numberTextField};
}
for (JComponent c : comps) {
valid = checkValid(c) && valid;
if (!valid && !focusTransfered) {
c.requestFocusInWindow();
focusTransfered = true;
}
}
return valid;
}
/** checks if component's content is valid */
private boolean checkValid(JComponent c) {
boolean valid = true;
if (c == nameTextField) {
valid = StringUtils.isNotEmpty(nameTextField.getText());
updateBorder(c, valid);
} else if (c == numberTextField) {
valid = Contact.isValidNumber(numberTextField.getText());
updateBorder(c, valid);
}
return valid;
}
/** sets highlighted border on non-valid components and regular border on valid ones */
private void updateBorder(JComponent c, boolean valid) {
if (valid) {
c.setBorder(fieldBorder);
} else {
c.setBorder(lineRedBorder);
}
}
/** Enable or disable multi-editing mode */
private void setMultiMode(boolean multiMode) {
this.multiMode = multiMode;
nameTextField.setEnabled(!multiMode);
numberTextField.setEnabled(!multiMode);
suggestGatewayAction.setEnabled(!multiMode);
}
/** Show warning if user selected gateway can't send messages to a recipient
* number (based on supported prefixes list)
*/
private void updateCountryInfoLabel() {
countryInfoLabel.setVisible(false);
//ensure that fields are sufficiently filled in
Gateway gateway = gatewayComboBox.getSelectedGateway();
String number = numberTextField.getText();
if (gateway == null || !Contact.isValidNumber(number)) {
return;
}
boolean supported = Gateways.isNumberSupported(gateway, number);
if (!supported) {
String text = MessageFormat.format(l10n.getString("EditContactPanel.countryInfoLabel.text"),
StringUtils.join(gateway.getSupportedPrefixes(), ','));
countryInfoLabel.setText(text);
countryInfoLabel.setVisible(true);
}
}
private void nameTextFieldFocusLost(FocusEvent evt) {//GEN-FIRST:event_nameTextFieldFocusLost
checkValid(nameTextField);
}//GEN-LAST:event_nameTextFieldFocusLost
private void numberTextFieldFocusLost(FocusEvent evt) {//GEN-FIRST:event_numberTextFieldFocusLost
checkValid(numberTextField);
}//GEN-LAST:event_numberTextFieldFocusLost
private void suggestGatewayButtonActionPerformed(ActionEvent evt) {//GEN-FIRST:event_suggestGatewayButtonActionPerformed
userSet = false;
}//GEN-LAST:event_suggestGatewayButtonActionPerformed
private void gatewayComboBoxItemStateChanged(ItemEvent evt) {//GEN-FIRST:event_gatewayComboBoxItemStateChanged
userSet = true;
//show warning if user selected gateway requiring registration
//and no credentials are filled in
Gateway gateway = gatewayComboBox.getSelectedGateway();
if (gateway != null && gateway.isLoginRequired() &&
keyring.getKey(gateway.getName()) == null) {
credentialsInfoLabel.setVisible(true);
} else {
credentialsInfoLabel.setVisible(false);
}
//also update countryInfoLabel
updateCountryInfoLabel();
}//GEN-LAST:event_gatewayComboBoxItemStateChanged
/** Set contact to be edited or use null for new one */
public void setContact(Contact contact) {
setMultiMode(false);
if (contact == null) {
nameTextField.setText(null);
numberTextField.setText(config.getCountryPrefix());
gatewayComboBox.selectSuggestedGateway(numberTextField.getText());
} else {
nameTextField.setText(contact.getName());
numberTextField.setText(contact.getNumber());
gatewayComboBox.setSelectedGateway(contact.getGateway());
}
userSet = false;
}
/** Set contacts for collective editing. May not be null. */
public void setContacts(Collection<Contact> contacts) {
if (contacts.size() <= 1) {
setContact(contacts.size() <= 0 ? null : contacts.iterator().next());
return;
}
setMultiMode(true);
gatewayComboBox.setSelectedGateway(contacts.iterator().next().getGateway());
}
/** Get currently edited contact */
public Contact getContact() {
String name = nameTextField.getText();
String number = numberTextField.getText();
String gateway = gatewayComboBox.getSelectedGatewayName();
if (!multiMode && (StringUtils.isEmpty(name) || StringUtils.isEmpty(number) ||
StringUtils.isEmpty(gateway))) {
return null;
} else {
return new Contact(name, number, gateway);
}
}
/** Improve focus etc. before displaying panel */
public void prepareForShow() {
//no gateway, try to suggest one
if (gatewayComboBox.getSelectedGateway() == null) {
suggestGatewayAction.actionPerformed(null);
}
//give focus
if (multiMode) {
gatewayComboBox.requestFocusInWindow();
} else {
nameTextField.requestFocusInWindow();
nameTextField.selectAll();
}
}
// Variables declaration - do not modify//GEN-BEGIN:variables
private InfoLabel countryInfoLabel;
private InfoLabel credentialsInfoLabel;
private GatewayComboBox gatewayComboBox;
private JLabel gatewayLabel;
private JPanel jPanel1;
private JLabel nameLabel;
private JTextField nameTextField;
private JLabel numberLabel;
private JTextField numberTextField;
private JButton suggestGatewayButton;
// End of variables declaration//GEN-END:variables
}
| false | true | private void initComponents() {
nameTextField = new JTextField();
nameTextField.requestFocusInWindow();
numberTextField = new JTextField() {
@Override
public String getText() {
String text = super.getText();
if (StringUtils.isNotEmpty(text) && !text.startsWith("+"))
text = config.getCountryPrefix() + text;
return text;
}
}
;
gatewayComboBox = new GatewayComboBox();
nameLabel = new JLabel();
numberLabel = new JLabel();
gatewayLabel = new JLabel();
suggestGatewayButton = new JButton();
jPanel1 = new JPanel();
countryInfoLabel = new InfoLabel();
credentialsInfoLabel = new InfoLabel();
nameTextField.setToolTipText(l10n.getString("EditContactPanel.nameTextField.toolTipText")); // NOI18N
nameTextField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent evt) {
nameTextFieldFocusLost(evt);
}
});
numberTextField.setColumns(13);
numberTextField.setToolTipText(l10n.getString("EditContactPanel.numberTextField.toolTipText")); // NOI18N
numberTextField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent evt) {
numberTextFieldFocusLost(evt);
}
});
gatewayComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
gatewayComboBoxItemStateChanged(evt);
}
});
nameLabel.setLabelFor(nameTextField);
Mnemonics.setLocalizedText(nameLabel, l10n.getString("EditContactPanel.nameLabel.text")); // NOI18N
nameLabel.setToolTipText(nameTextField.getToolTipText());
numberLabel.setLabelFor(numberTextField);
Mnemonics.setLocalizedText(numberLabel, l10n.getString("EditContactPanel.numberLabel.text")); // NOI18N
numberLabel.setToolTipText(numberTextField.getToolTipText());
gatewayLabel.setLabelFor(gatewayComboBox);
Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("EditContactPanel.gatewayLabel.text")); // NOI18N
gatewayLabel.setToolTipText(gatewayComboBox.getToolTipText());
suggestGatewayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
suggestGatewayButtonActionPerformed(evt);
}
});
Mnemonics.setLocalizedText(countryInfoLabel, l10n.getString("EditContactPanel.countryInfoLabel.text")); // NOI18N
countryInfoLabel.setVisible(false);
Mnemonics.setLocalizedText(credentialsInfoLabel,l10n.getString(
"EditContactPanel.credentialsInfoLabel.text"));
credentialsInfoLabel.setText(MessageFormat.format(
l10n.getString("EditContactPanel.credentialsInfoLabel.text"), Links.CONFIG_CREDENTIALS));
credentialsInfoLabel.setVisible(false);
GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(Alignment.LEADING)
.addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 733, Short.MAX_VALUE)
.addComponent(countryInfoLabel)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(credentialsInfoLabel)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(countryInfoLabel))
);
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(numberLabel)
.addComponent(nameLabel)
.addComponent(gatewayLabel))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(gatewayComboBox, GroupLayout.DEFAULT_SIZE, 588, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(suggestGatewayButton))
.addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 622, Short.MAX_VALUE)
.addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 622, Short.MAX_VALUE))))
.addContainerGap())
);
layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, nameLabel, numberLabel});
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(nameLabel)
.addComponent(nameTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(numberLabel)
.addComponent(numberTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(gatewayLabel)
.addComponent(gatewayComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(suggestGatewayButton))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(74, Short.MAX_VALUE))
);
layout.linkSize(SwingConstants.VERTICAL, new Component[] {nameTextField, numberTextField});
}// </editor-fold>//GEN-END:initComponents
| private void initComponents() {
nameTextField = new JTextField();
nameTextField.requestFocusInWindow();
numberTextField = new JTextField() {
@Override
public String getText() {
String text = super.getText();
if (StringUtils.isNotEmpty(text) && !text.startsWith("+"))
text = config.getCountryPrefix() + text;
return text;
}
}
;
gatewayComboBox = new GatewayComboBox();
nameLabel = new JLabel();
numberLabel = new JLabel();
gatewayLabel = new JLabel();
suggestGatewayButton = new JButton();
jPanel1 = new JPanel();
countryInfoLabel = new InfoLabel();
credentialsInfoLabel = new InfoLabel();
nameTextField.setToolTipText(l10n.getString("EditContactPanel.nameTextField.toolTipText")); // NOI18N
nameTextField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent evt) {
nameTextFieldFocusLost(evt);
}
});
numberTextField.setColumns(13);
numberTextField.setToolTipText(l10n.getString("EditContactPanel.numberTextField.toolTipText")); // NOI18N
numberTextField.addFocusListener(new FocusAdapter() {
public void focusLost(FocusEvent evt) {
numberTextFieldFocusLost(evt);
}
});
gatewayComboBox.addItemListener(new ItemListener() {
public void itemStateChanged(ItemEvent evt) {
gatewayComboBoxItemStateChanged(evt);
}
});
nameLabel.setLabelFor(nameTextField);
Mnemonics.setLocalizedText(nameLabel, l10n.getString("EditContactPanel.nameLabel.text")); // NOI18N
nameLabel.setToolTipText(nameTextField.getToolTipText());
numberLabel.setLabelFor(numberTextField);
Mnemonics.setLocalizedText(numberLabel, l10n.getString("EditContactPanel.numberLabel.text")); // NOI18N
numberLabel.setToolTipText(numberTextField.getToolTipText());
gatewayLabel.setLabelFor(gatewayComboBox);
Mnemonics.setLocalizedText(gatewayLabel, l10n.getString("EditContactPanel.gatewayLabel.text")); // NOI18N
gatewayLabel.setToolTipText(gatewayComboBox.getToolTipText());
suggestGatewayButton.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent evt) {
suggestGatewayButtonActionPerformed(evt);
}
});
Mnemonics.setLocalizedText(countryInfoLabel, l10n.getString("EditContactPanel.countryInfoLabel.text")); // NOI18N
countryInfoLabel.setVisible(false);
Mnemonics.setLocalizedText(credentialsInfoLabel,l10n.getString(
"EditContactPanel.credentialsInfoLabel.text"));
credentialsInfoLabel.setText(MessageFormat.format(
l10n.getString("EditContactPanel.credentialsInfoLabel.text"), Links.CONFIG_CREDENTIALS));
credentialsInfoLabel.setVisible(false);
GroupLayout jPanel1Layout = new GroupLayout(jPanel1);
jPanel1.setLayout(jPanel1Layout);
jPanel1Layout.setHorizontalGroup(
jPanel1Layout.createParallelGroup(Alignment.LEADING)
.addComponent(credentialsInfoLabel, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
.addComponent(countryInfoLabel, GroupLayout.DEFAULT_SIZE, 470, Short.MAX_VALUE)
);
jPanel1Layout.setVerticalGroup(
jPanel1Layout.createParallelGroup(Alignment.LEADING)
.addGroup(jPanel1Layout.createSequentialGroup()
.addComponent(credentialsInfoLabel)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(countryInfoLabel))
);
GroupLayout layout = new GroupLayout(this);
this.setLayout(layout);
layout.setHorizontalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(jPanel1, GroupLayout.DEFAULT_SIZE, GroupLayout.DEFAULT_SIZE, Short.MAX_VALUE)
.addGroup(layout.createSequentialGroup()
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addComponent(numberLabel)
.addComponent(nameLabel)
.addComponent(gatewayLabel))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.LEADING)
.addGroup(Alignment.TRAILING, layout.createSequentialGroup()
.addComponent(gatewayComboBox, GroupLayout.DEFAULT_SIZE, 325, Short.MAX_VALUE)
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(suggestGatewayButton))
.addComponent(nameTextField, GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE)
.addComponent(numberTextField, Alignment.TRAILING, GroupLayout.DEFAULT_SIZE, 359, Short.MAX_VALUE))))
.addContainerGap())
);
layout.linkSize(SwingConstants.HORIZONTAL, new Component[] {gatewayLabel, nameLabel, numberLabel});
layout.setVerticalGroup(
layout.createParallelGroup(Alignment.LEADING)
.addGroup(layout.createSequentialGroup()
.addContainerGap()
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(nameLabel)
.addComponent(nameTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(numberLabel)
.addComponent(numberTextField, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addPreferredGap(ComponentPlacement.RELATED)
.addGroup(layout.createParallelGroup(Alignment.TRAILING)
.addGroup(layout.createParallelGroup(Alignment.BASELINE)
.addComponent(gatewayLabel)
.addComponent(gatewayComboBox, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE))
.addComponent(suggestGatewayButton))
.addPreferredGap(ComponentPlacement.RELATED)
.addComponent(jPanel1, GroupLayout.PREFERRED_SIZE, GroupLayout.DEFAULT_SIZE, GroupLayout.PREFERRED_SIZE)
.addContainerGap(84, Short.MAX_VALUE))
);
layout.linkSize(SwingConstants.VERTICAL, new Component[] {nameTextField, numberTextField});
}// </editor-fold>//GEN-END:initComponents
|
diff --git a/src/net/java/sip/communicator/impl/neomedia/RTPConnectorInputStream.java b/src/net/java/sip/communicator/impl/neomedia/RTPConnectorInputStream.java
index a2a13e381..7a5d6cbfc 100755
--- a/src/net/java/sip/communicator/impl/neomedia/RTPConnectorInputStream.java
+++ b/src/net/java/sip/communicator/impl/neomedia/RTPConnectorInputStream.java
@@ -1,326 +1,327 @@
/*
* SIP Communicator, the OpenSource Java VoIP and Instant Messaging client.
*
* Distributable under LGPL license.
* See terms of license at gnu.org.
*/
package net.java.sip.communicator.impl.neomedia;
import net.java.sip.communicator.service.packetlogging.*;
import java.io.*;
import java.net.*;
import javax.media.protocol.*;
/**
* @author Bing SU ([email protected])
* @author Lubomir Marinov
*/
public class RTPConnectorInputStream
implements PushSourceStream,
Runnable
{
/**
* The value of the property <tt>controls</tt> of
* <tt>RTPConnectorInputStream</tt> when there are no controls. Explicitly
* defined in order to reduce unnecessary allocations.
*/
private static final Object[] EMPTY_CONTROLS = new Object[0];
/**
* The size of the buffers receiving packets coming from network.
*/
private static final int PACKET_RECEIVE_BUFFER = 4000;
/**
* Packet receive buffer
*/
private final byte[] buffer = new byte[PACKET_RECEIVE_BUFFER];
/**
* Whether this stream is closed. Used to control the termination of worker
* thread.
*/
private boolean closed;
/**
* Caught an IO exception during read from socket
*/
protected boolean ioError = false;
/**
* The packet data to be read out of this instance through its
* {@link #read(byte[], int, int)} method.
*/
protected RawPacket pkt;
/**
* UDP socket used to receive data.
*/
private final DatagramSocket socket;
/**
* SourceTransferHandler object which is used to read packets.
*/
private SourceTransferHandler transferHandler;
/**
* The Thread receiving packets.
*/
private Thread receiverThread = null;
/**
* Used for debugging. As we don't log every packet
* we must count them and decide which to log.
*/
private long numberOfPackets = 0;
/**
* Initializes a new <tt>RTPConnectorInputStream</tt> which is to receive
* packet data from a specific UDP socket.
*
* @param socket the UDP socket the new instance is to receive data from
*/
public RTPConnectorInputStream(DatagramSocket socket)
{
this.socket = socket;
closed = false;
receiverThread = new Thread(this);
receiverThread.start();
}
/**
* Close this stream, stops the worker thread.
*/
public synchronized void close()
{
closed = true;
socket.close();
}
/**
* Creates a new <tt>RawPacket</tt> from a specific <tt>DatagramPacket</tt>
* in order to have this instance receive its packet data through its
* {@link #read(byte[], int, int)} method. Allows extenders to intercept the
* packet data and possibly filter and/or modify it.
*
* @param datagramPacket the <tt>DatagramPacket</tt> containing the packet
* data
* @return a new <tt>RawPacket</tt> containing the packet data of the
* specified <tt>DatagramPacket</tt> or possibly its modification;
* <tt>null</tt> to ignore the packet data of the specified
* <tt>DatagramPacket</tt> and not make it available to this instance
* through its {@link #read(byte[], int, int)} method
*/
protected RawPacket createRawPacket(DatagramPacket datagramPacket)
{
if (pkt == null)
{
return new RawPacket(
datagramPacket.getData(),
datagramPacket.getOffset(),
datagramPacket.getLength());
}
pkt.setBuffer(datagramPacket.getData());
pkt.setLength(datagramPacket.getLength());
pkt.setOffset(datagramPacket.getOffset());
return pkt;
}
/**
* Provides a dummy implementation to {@link
* RTPConnectorInputStream#endOfStream()} that always returns
* <tt>false</tt>.
*
* @return <tt>false</tt>, no matter what.
*/
public boolean endOfStream()
{
return false;
}
/**
* Provides a dummy implementation to {@link
* RTPConnectorInputStream#getContentDescriptor()} that always returns
* <tt>null</tt>.
*
* @return <tt>null</tt>, no matter what.
*/
public ContentDescriptor getContentDescriptor()
{
return null;
}
/**
* Provides a dummy implementation to {@link
* RTPConnectorInputStream#getContentLength()} that always returns
* <tt>LENGTH_UNKNOWN</tt>.
*
* @return <tt>LENGTH_UNKNOWN</tt>, no matter what.
*/
public long getContentLength()
{
return pkt.getLength();
}
/**
* Provides a dummy implementation to {@link
* RTPConnectorInputStream#getControl(String)} that always returns
* <tt>null</tt>.
*
* @param controlType ignored.
*
* @return <tt>null</tt>, no matter what.
*/
public Object getControl(String controlType)
{
return null;
}
/**
* Provides a dummy implementation to {@link
* RTPConnectorInputStream#getControls()} that always returns
* <tt>EMPTY_CONTROLS</tt>.
*
* @return <tt>EMPTY_CONTROLS</tt>, no matter what.
*/
public Object[] getControls()
{
return EMPTY_CONTROLS;
}
/**
* Provides a dummy implementation to {@link
* RTPConnectorInputStream#getMinimumTransferSize()} that always returns
* <tt>2 * 1024</tt>.
*
* @return <tt>2 * 1024</tt>, no matter what.
*/
public int getMinimumTransferSize()
{
return 2 * 1024; // twice the MTU size, just to be safe.
}
/**
* Copies the content of the most recently received packet into
* <tt>inBuffer</tt>.
*
* @param inBuffer the <tt>byte[]</tt> that we'd like to copy the content
* of the packet to.
* @param offset the position where we are supposed to start writing in
* <tt>inBuffer</tt>.
* @param length the number of <tt>byte</tt>s available for writing in
* <tt>inBuffer</tt>.
*
* @return the number of bytes read
*
* @throws IOException if <tt>length</tt> is less than the size of the
* packet.
*/
public int read(byte[] inBuffer, int offset, int length)
throws IOException
{
if (ioError)
return -1;
int pktLength = pkt.getLength();
if (length < pktLength)
throw
new IOException("Input buffer not big enough for " + pktLength);
System.arraycopy(
pkt.getBuffer(), pkt.getOffset(), inBuffer, offset, pktLength);
return pktLength;
}
/**
* Listens for incoming datagrams, stores them for reading by the
* <tt>read</tt> method and notifies the local <tt>transferHandler</tt>
* that there's data to be read.
*/
public void run()
{
try
{
socket.setReceiveBufferSize(65535);
}
catch(Throwable t)
{
}
while (!closed)
{
DatagramPacket p = new DatagramPacket(
buffer, 0, PACKET_RECEIVE_BUFFER);
try
{
socket.receive(p);
numberOfPackets++;
}
catch (IOException e)
{
ioError = true;
break;
}
if(RTPConnectorOutputStream.logPacket(numberOfPackets)
&& NeomediaActivator.getPacketLogging().isLoggingEnabled(
- PacketLoggingService.ProtocolName.RTP))
+ PacketLoggingService.ProtocolName.RTP) &&
+ socket.getLocalAddress() != null)
{
NeomediaActivator.getPacketLogging()
.logPacket(
PacketLoggingService.ProtocolName.RTP,
p.getAddress().getAddress(),
p.getPort(),
socket.getLocalAddress().getAddress(),
socket.getLocalPort(),
PacketLoggingService.TransportName.UDP,
false,
p.getData(),
p.getOffset(),
p.getLength());
}
pkt = createRawPacket(p);
/*
* If we got extended, the delivery of the packet may have been
* canceled.
*/
if ((pkt != null) && (transferHandler != null) && !closed)
transferHandler.transferData(this);
}
}
/**
* Sets the <tt>transferHandler</tt> that this connector should be notifying
* when new data is available for reading.
*
* @param transferHandler the <tt>transferHandler</tt> that this connector
* should be notifying when new data is available for reading.
*/
public void setTransferHandler(SourceTransferHandler transferHandler)
{
if (!closed)
this.transferHandler = transferHandler;
}
/**
* Changes current thread priority.
* @param priority the new priority.
*/
public void setPriority(int priority)
{
// currently no priority is set
// if(receiverThread != null)
// {
// receiverThread.setPriority(priority);
// }
}
}
| true | true | public void run()
{
try
{
socket.setReceiveBufferSize(65535);
}
catch(Throwable t)
{
}
while (!closed)
{
DatagramPacket p = new DatagramPacket(
buffer, 0, PACKET_RECEIVE_BUFFER);
try
{
socket.receive(p);
numberOfPackets++;
}
catch (IOException e)
{
ioError = true;
break;
}
if(RTPConnectorOutputStream.logPacket(numberOfPackets)
&& NeomediaActivator.getPacketLogging().isLoggingEnabled(
PacketLoggingService.ProtocolName.RTP))
{
NeomediaActivator.getPacketLogging()
.logPacket(
PacketLoggingService.ProtocolName.RTP,
p.getAddress().getAddress(),
p.getPort(),
socket.getLocalAddress().getAddress(),
socket.getLocalPort(),
PacketLoggingService.TransportName.UDP,
false,
p.getData(),
p.getOffset(),
p.getLength());
}
pkt = createRawPacket(p);
/*
* If we got extended, the delivery of the packet may have been
* canceled.
*/
if ((pkt != null) && (transferHandler != null) && !closed)
transferHandler.transferData(this);
}
}
| public void run()
{
try
{
socket.setReceiveBufferSize(65535);
}
catch(Throwable t)
{
}
while (!closed)
{
DatagramPacket p = new DatagramPacket(
buffer, 0, PACKET_RECEIVE_BUFFER);
try
{
socket.receive(p);
numberOfPackets++;
}
catch (IOException e)
{
ioError = true;
break;
}
if(RTPConnectorOutputStream.logPacket(numberOfPackets)
&& NeomediaActivator.getPacketLogging().isLoggingEnabled(
PacketLoggingService.ProtocolName.RTP) &&
socket.getLocalAddress() != null)
{
NeomediaActivator.getPacketLogging()
.logPacket(
PacketLoggingService.ProtocolName.RTP,
p.getAddress().getAddress(),
p.getPort(),
socket.getLocalAddress().getAddress(),
socket.getLocalPort(),
PacketLoggingService.TransportName.UDP,
false,
p.getData(),
p.getOffset(),
p.getLength());
}
pkt = createRawPacket(p);
/*
* If we got extended, the delivery of the packet may have been
* canceled.
*/
if ((pkt != null) && (transferHandler != null) && !closed)
transferHandler.transferData(this);
}
}
|
diff --git a/web/src/main/java/org/eurekastreams/web/client/ui/common/FooterComposite.java b/web/src/main/java/org/eurekastreams/web/client/ui/common/FooterComposite.java
index 487ba2242..631abeff3 100644
--- a/web/src/main/java/org/eurekastreams/web/client/ui/common/FooterComposite.java
+++ b/web/src/main/java/org/eurekastreams/web/client/ui/common/FooterComposite.java
@@ -1,103 +1,103 @@
/*
* Copyright (c) 2010-2011 Lockheed Martin Corporation
*
* 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.eurekastreams.web.client.ui.common;
import org.eurekastreams.server.domain.Page;
import org.eurekastreams.web.client.events.EventBus;
import org.eurekastreams.web.client.events.Observer;
import org.eurekastreams.web.client.events.data.GotSystemSettingsResponseEvent;
import org.eurekastreams.web.client.history.CreateUrlRequest;
import org.eurekastreams.web.client.model.SystemSettingsModel;
import org.eurekastreams.web.client.ui.Session;
import org.eurekastreams.web.client.ui.pages.master.StaticResourceBundle;
import com.google.gwt.user.client.ui.Anchor;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.FlowPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Label;
/**
* This class creates the Composite for the main footer displayed on the page.
*
*/
public class FooterComposite extends Composite
{
/**
* The Site Labeling Panel.
*/
FlowPanel siteLabelingContainer = new FlowPanel();
/**
* Primary constructor for the FooterComposite Widget.
*/
public FooterComposite()
{
FlowPanel panel = new FlowPanel();
initWidget(panel);
final FlowPanel navPanel = new FlowPanel();
EventBus.getInstance().addObserver(GotSystemSettingsResponseEvent.class,
new Observer<GotSystemSettingsResponseEvent>()
{
public void update(final GotSystemSettingsResponseEvent event)
{
- if (Session.getInstance().getHistoryHandler() != null && navPanel.getWidgetCount() == 1
+ if (Session.getInstance().getHistoryHandler() != null && navPanel.getWidgetCount() == 0
&& event.getResponse().getSupportStreamGroupShortName() != null
&& event.getResponse().getSupportStreamGroupShortName().length() > 0)
{
navPanel.add(new Hyperlink("HELP", Session.getInstance().generateUrl(
new CreateUrlRequest(Page.GROUPS, event.getResponse()
.getSupportStreamGroupShortName()))));
if (event.getResponse().getSupportStreamWebsite() != null
&& event.getResponse().getSupportStreamWebsite().length() > 0)
{
navPanel.add(new Label("|"));
navPanel.add(new Anchor("LEARN MORE", event.getResponse().getSupportStreamWebsite(),
"_blank"));
}
}
}
});
panel.add(navPanel);
panel.add(siteLabelingContainer);
navPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().footerNav());
siteLabelingContainer.addStyleName(StaticResourceBundle.INSTANCE.coreCss().siteLabeling());
panel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().footerBar());
SystemSettingsModel.getInstance().fetch(null, true);
}
/**
* Sets Site labeling.
*
* @param inTemplate
* HTML template content to insert in the footer.
* @param inSiteLabel
* The text for Site Labeling.
*/
public void setSiteLabelTemplate(final String inTemplate, final String inSiteLabel)
{
String siteLabel = inSiteLabel == null ? "" : inSiteLabel;
String template = inTemplate.replace("%SITELABEL%", siteLabel);
siteLabelingContainer.getElement().setInnerHTML(template);
}
}
| true | true | public FooterComposite()
{
FlowPanel panel = new FlowPanel();
initWidget(panel);
final FlowPanel navPanel = new FlowPanel();
EventBus.getInstance().addObserver(GotSystemSettingsResponseEvent.class,
new Observer<GotSystemSettingsResponseEvent>()
{
public void update(final GotSystemSettingsResponseEvent event)
{
if (Session.getInstance().getHistoryHandler() != null && navPanel.getWidgetCount() == 1
&& event.getResponse().getSupportStreamGroupShortName() != null
&& event.getResponse().getSupportStreamGroupShortName().length() > 0)
{
navPanel.add(new Hyperlink("HELP", Session.getInstance().generateUrl(
new CreateUrlRequest(Page.GROUPS, event.getResponse()
.getSupportStreamGroupShortName()))));
if (event.getResponse().getSupportStreamWebsite() != null
&& event.getResponse().getSupportStreamWebsite().length() > 0)
{
navPanel.add(new Label("|"));
navPanel.add(new Anchor("LEARN MORE", event.getResponse().getSupportStreamWebsite(),
"_blank"));
}
}
}
});
panel.add(navPanel);
panel.add(siteLabelingContainer);
navPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().footerNav());
siteLabelingContainer.addStyleName(StaticResourceBundle.INSTANCE.coreCss().siteLabeling());
panel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().footerBar());
SystemSettingsModel.getInstance().fetch(null, true);
}
| public FooterComposite()
{
FlowPanel panel = new FlowPanel();
initWidget(panel);
final FlowPanel navPanel = new FlowPanel();
EventBus.getInstance().addObserver(GotSystemSettingsResponseEvent.class,
new Observer<GotSystemSettingsResponseEvent>()
{
public void update(final GotSystemSettingsResponseEvent event)
{
if (Session.getInstance().getHistoryHandler() != null && navPanel.getWidgetCount() == 0
&& event.getResponse().getSupportStreamGroupShortName() != null
&& event.getResponse().getSupportStreamGroupShortName().length() > 0)
{
navPanel.add(new Hyperlink("HELP", Session.getInstance().generateUrl(
new CreateUrlRequest(Page.GROUPS, event.getResponse()
.getSupportStreamGroupShortName()))));
if (event.getResponse().getSupportStreamWebsite() != null
&& event.getResponse().getSupportStreamWebsite().length() > 0)
{
navPanel.add(new Label("|"));
navPanel.add(new Anchor("LEARN MORE", event.getResponse().getSupportStreamWebsite(),
"_blank"));
}
}
}
});
panel.add(navPanel);
panel.add(siteLabelingContainer);
navPanel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().footerNav());
siteLabelingContainer.addStyleName(StaticResourceBundle.INSTANCE.coreCss().siteLabeling());
panel.addStyleName(StaticResourceBundle.INSTANCE.coreCss().footerBar());
SystemSettingsModel.getInstance().fetch(null, true);
}
|
diff --git a/solr/src/java/org/apache/solr/handler/component/PivotFacetHelper.java b/solr/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
index b47be4fe6..c00add584 100644
--- a/solr/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
+++ b/solr/src/java/org/apache/solr/handler/component/PivotFacetHelper.java
@@ -1,258 +1,258 @@
/**
* 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.solr.handler.component;
import org.apache.lucene.util.BytesRef;
import org.apache.solr.schema.SchemaField;
import org.apache.solr.search.SolrIndexSearcher;
import org.apache.solr.search.DocSet;
import org.apache.solr.common.SolrException;
import org.apache.solr.common.util.NamedList;
import org.apache.solr.common.util.SimpleOrderedMap;
import org.apache.solr.common.SolrException.ErrorCode;
import org.apache.solr.common.params.SolrParams;
import org.apache.solr.common.params.FacetParams;
import org.apache.solr.request.SimpleFacets;
import org.apache.solr.request.SolrQueryRequest;
import org.apache.solr.schema.FieldType;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.TermQuery;
import org.apache.lucene.index.Term;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Deque;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
/**
* This is thread safe
* @since solr 4.0
*/
public class PivotFacetHelper
{
/**
* Designed to be overridden by subclasses that provide different faceting implementations.
* TODO: Currently this is returning a SimpleFacets object, but those capabilities would
* be better as an extracted abstract class or interface.
*/
protected SimpleFacets getFacetImplementation(SolrQueryRequest req, DocSet docs, SolrParams params) {
return new SimpleFacets(req, docs, params);
}
public SimpleOrderedMap<List<NamedList<Object>>> process(ResponseBuilder rb, SolrParams params, String[] pivots) throws IOException {
if (!rb.doFacets || pivots == null)
return null;
int minMatch = params.getInt( FacetParams.FACET_PIVOT_MINCOUNT, 1 );
SimpleOrderedMap<List<NamedList<Object>>> pivotResponse = new SimpleOrderedMap<List<NamedList<Object>>>();
for (String pivot : pivots) {
String[] fields = pivot.split(","); // only support two levels for now
if( fields.length < 2 ) {
throw new SolrException( ErrorCode.BAD_REQUEST,
"Pivot Facet needs at least two fields: "+pivot );
}
DocSet docs = rb.getResults().docSet;
String field = fields[0];
String subField = fields[1];
Deque<String> fnames = new LinkedList<String>();
for( int i=fields.length-1; i>1; i-- ) {
fnames.push( fields[i] );
}
SimpleFacets sf = getFacetImplementation(rb.req, rb.getResults().docSet, rb.req.getParams());
NamedList<Integer> superFacets = sf.getTermCounts(field);
pivotResponse.add(pivot, doPivots(superFacets, field, subField, fnames, rb, docs, minMatch));
}
return pivotResponse;
}
/**
* Recursive function to do all the pivots
*/
protected List<NamedList<Object>> doPivots( NamedList<Integer> superFacets, String field, String subField, Deque<String> fnames, ResponseBuilder rb, DocSet docs, int minMatch ) throws IOException
{
SolrIndexSearcher searcher = rb.req.getSearcher();
// TODO: optimize to avoid converting to an external string and then having to convert back to internal below
SchemaField sfield = searcher.getSchema().getField(field);
FieldType ftype = sfield.getType();
String nextField = fnames.poll();
List<NamedList<Object>> values = new ArrayList<NamedList<Object>>( superFacets.size() );
for (Map.Entry<String, Integer> kv : superFacets) {
// Only sub-facet if parent facet has positive count - still may not be any values for the sub-field though
- if (kv.getValue() > minMatch ) {
+ if (kv.getValue() >= minMatch ) {
// don't reuse the same BytesRef each time since we will be constructing Term
// objects that will most likely be cached.
BytesRef termval = new BytesRef();
ftype.readableToIndexed(kv.getKey(), termval);
SimpleOrderedMap<Object> pivot = new SimpleOrderedMap<Object>();
pivot.add( "field", field );
pivot.add( "value", ftype.toObject(sfield, termval) );
pivot.add( "count", kv.getValue() );
if( subField == null ) {
values.add( pivot );
}
else {
Query query = new TermQuery(new Term(field, termval));
DocSet subset = searcher.getDocSet(query, docs);
SimpleFacets sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Integer> nl = sf.getTermCounts(subField);
- if (nl.size() > minMatch ) {
+ if (nl.size() >= minMatch ) {
pivot.add( "pivot", doPivots( nl, subField, nextField, fnames, rb, subset, minMatch ) );
values.add( pivot ); // only add response if there are some counts
}
}
}
}
// put the field back on the list
fnames.push( nextField );
return values;
}
// TODO: This is code from various patches to support distributed search.
// Some parts may be helpful for whoever implements distributed search.
//
// @Override
// public int distributedProcess(ResponseBuilder rb) throws IOException {
// if (!rb.doFacets) {
// return ResponseBuilder.STAGE_DONE;
// }
//
// if (rb.stage == ResponseBuilder.STAGE_GET_FIELDS) {
// SolrParams params = rb.req.getParams();
// String[] pivots = params.getParams(FacetParams.FACET_PIVOT);
// for ( ShardRequest sreq : rb.outgoing ) {
// if (( sreq.purpose & ShardRequest.PURPOSE_GET_FIELDS ) != 0
// && sreq.shards != null && sreq.shards.length == 1 ) {
// sreq.params.set( FacetParams.FACET, "true" );
// sreq.params.set( FacetParams.FACET_PIVOT, pivots );
// sreq.params.set( FacetParams.FACET_PIVOT_MINCOUNT, 1 ); // keep this at 1 regardless so that it accumulates everything
// }
// }
// }
// return ResponseBuilder.STAGE_DONE;
// }
//
// @Override
// public void handleResponses(ResponseBuilder rb, ShardRequest sreq) {
// if (!rb.doFacets) return;
//
//
// if ((sreq.purpose & ShardRequest.PURPOSE_GET_FACETS)!=0) {
// SimpleOrderedMap<List<NamedList<Object>>> tf = rb._pivots;
// if ( null == tf ) {
// tf = new SimpleOrderedMap<List<NamedList<Object>>>();
// rb._pivots = tf;
// }
// for (ShardResponse srsp: sreq.responses) {
// int shardNum = rb.getShardNum(srsp.getShard());
//
// NamedList facet_counts = (NamedList)srsp.getSolrResponse().getResponse().get("facet_counts");
//
// // handle facet trees from shards
// SimpleOrderedMap<List<NamedList<Object>>> shard_pivots =
// (SimpleOrderedMap<List<NamedList<Object>>>)facet_counts.get( PIVOT_KEY );
//
// if ( shard_pivots != null ) {
// for (int j=0; j< shard_pivots.size(); j++) {
// // TODO -- accumulate the results from each shard
// // The following code worked to accumulate facets for an previous
// // two level patch... it is here for reference till someone can upgrade
// /**
// String shard_tree_name = (String) shard_pivots.getName( j );
// SimpleOrderedMap<NamedList> shard_tree = (SimpleOrderedMap<NamedList>)shard_pivots.getVal( j );
// SimpleOrderedMap<NamedList> facet_tree = tf.get( shard_tree_name );
// if ( null == facet_tree) {
// facet_tree = new SimpleOrderedMap<NamedList>();
// tf.add( shard_tree_name, facet_tree );
// }
//
// for( int o = 0; o < shard_tree.size() ; o++ ) {
// String shard_outer = (String) shard_tree.getName( o );
// NamedList shard_innerList = (NamedList) shard_tree.getVal( o );
// NamedList tree_innerList = (NamedList) facet_tree.get( shard_outer );
// if ( null == tree_innerList ) {
// tree_innerList = new NamedList();
// facet_tree.add( shard_outer, tree_innerList );
// }
//
// for ( int i = 0 ; i < shard_innerList.size() ; i++ ) {
// String shard_term = (String) shard_innerList.getName( i );
// long shard_count = ((Number) shard_innerList.getVal(i)).longValue();
// int tree_idx = tree_innerList.indexOf( shard_term, 0 );
//
// if ( -1 == tree_idx ) {
// tree_innerList.add( shard_term, shard_count );
// } else {
// long tree_count = ((Number) tree_innerList.getVal( tree_idx )).longValue();
// tree_innerList.setVal( tree_idx, shard_count + tree_count );
// }
// } // innerList loop
// } // outer loop
// **/
// } // each tree loop
// }
// }
// }
// return ;
// }
//
// @Override
// public void finishStage(ResponseBuilder rb) {
// if (!rb.doFacets || rb.stage != ResponseBuilder.STAGE_GET_FIELDS) return;
// // wait until STAGE_GET_FIELDS
// // so that "result" is already stored in the response (for aesthetics)
//
// SimpleOrderedMap<List<NamedList<Object>>> tf = rb._pivots;
//
// // get 'facet_counts' from the response
// NamedList facetCounts = (NamedList) rb.rsp.getValues().get("facet_counts");
// if (facetCounts == null) {
// facetCounts = new NamedList();
// rb.rsp.add("facet_counts", facetCounts);
// }
// facetCounts.add( PIVOT_KEY, tf );
// rb._pivots = null;
// }
//
// public String getDescription() {
// return "Handle Pivot (multi-level) Faceting";
// }
//
// public String getSourceId() {
// return "$Id$";
// }
//
// public String getSource() {
// return "$URL$";
// }
//
// public String getVersion() {
// return "$Revision$";
// }
}
| false | true | protected List<NamedList<Object>> doPivots( NamedList<Integer> superFacets, String field, String subField, Deque<String> fnames, ResponseBuilder rb, DocSet docs, int minMatch ) throws IOException
{
SolrIndexSearcher searcher = rb.req.getSearcher();
// TODO: optimize to avoid converting to an external string and then having to convert back to internal below
SchemaField sfield = searcher.getSchema().getField(field);
FieldType ftype = sfield.getType();
String nextField = fnames.poll();
List<NamedList<Object>> values = new ArrayList<NamedList<Object>>( superFacets.size() );
for (Map.Entry<String, Integer> kv : superFacets) {
// Only sub-facet if parent facet has positive count - still may not be any values for the sub-field though
if (kv.getValue() > minMatch ) {
// don't reuse the same BytesRef each time since we will be constructing Term
// objects that will most likely be cached.
BytesRef termval = new BytesRef();
ftype.readableToIndexed(kv.getKey(), termval);
SimpleOrderedMap<Object> pivot = new SimpleOrderedMap<Object>();
pivot.add( "field", field );
pivot.add( "value", ftype.toObject(sfield, termval) );
pivot.add( "count", kv.getValue() );
if( subField == null ) {
values.add( pivot );
}
else {
Query query = new TermQuery(new Term(field, termval));
DocSet subset = searcher.getDocSet(query, docs);
SimpleFacets sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Integer> nl = sf.getTermCounts(subField);
if (nl.size() > minMatch ) {
pivot.add( "pivot", doPivots( nl, subField, nextField, fnames, rb, subset, minMatch ) );
values.add( pivot ); // only add response if there are some counts
}
}
}
}
// put the field back on the list
fnames.push( nextField );
return values;
}
| protected List<NamedList<Object>> doPivots( NamedList<Integer> superFacets, String field, String subField, Deque<String> fnames, ResponseBuilder rb, DocSet docs, int minMatch ) throws IOException
{
SolrIndexSearcher searcher = rb.req.getSearcher();
// TODO: optimize to avoid converting to an external string and then having to convert back to internal below
SchemaField sfield = searcher.getSchema().getField(field);
FieldType ftype = sfield.getType();
String nextField = fnames.poll();
List<NamedList<Object>> values = new ArrayList<NamedList<Object>>( superFacets.size() );
for (Map.Entry<String, Integer> kv : superFacets) {
// Only sub-facet if parent facet has positive count - still may not be any values for the sub-field though
if (kv.getValue() >= minMatch ) {
// don't reuse the same BytesRef each time since we will be constructing Term
// objects that will most likely be cached.
BytesRef termval = new BytesRef();
ftype.readableToIndexed(kv.getKey(), termval);
SimpleOrderedMap<Object> pivot = new SimpleOrderedMap<Object>();
pivot.add( "field", field );
pivot.add( "value", ftype.toObject(sfield, termval) );
pivot.add( "count", kv.getValue() );
if( subField == null ) {
values.add( pivot );
}
else {
Query query = new TermQuery(new Term(field, termval));
DocSet subset = searcher.getDocSet(query, docs);
SimpleFacets sf = getFacetImplementation(rb.req, subset, rb.req.getParams());
NamedList<Integer> nl = sf.getTermCounts(subField);
if (nl.size() >= minMatch ) {
pivot.add( "pivot", doPivots( nl, subField, nextField, fnames, rb, subset, minMatch ) );
values.add( pivot ); // only add response if there are some counts
}
}
}
}
// put the field back on the list
fnames.push( nextField );
return values;
}
|
diff --git a/src/org/subethamail/smtp/io/ReceivedHeaderStream.java b/src/org/subethamail/smtp/io/ReceivedHeaderStream.java
index bee83f1..0bea8c9 100644
--- a/src/org/subethamail/smtp/io/ReceivedHeaderStream.java
+++ b/src/org/subethamail/smtp/io/ReceivedHeaderStream.java
@@ -1,127 +1,127 @@
/*
*
*/
package org.subethamail.smtp.io;
import java.io.ByteArrayInputStream;
import java.io.FilterInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.InetAddress;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Locale;
import org.subethamail.smtp.util.TextUtils;
/**
* Prepends a Received: header at the beginning of the input stream.
*/
public class ReceivedHeaderStream extends FilterInputStream
{
ByteArrayInputStream header;
/**
*/
public ReceivedHeaderStream(InputStream in, String heloHost, InetAddress host, String whoami)
{
super(in);
/* Looks like:
Received: from iamhelo (wasabi.infohazard.org [209.237.247.14])
by mx.google.com with SMTP id 32si2669129wfa.13.2009.05.27.18.27.31;
Wed, 27 May 2009 18:27:48 -0700 (PDT)
*/
- DateFormat fmt = new SimpleDateFormat("EEE, dd MM yyyy HH:mm:ss Z (z)", Locale.US);
+ DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z (z)", Locale.US);
String timestamp = fmt.format(new Date());
String header =
"Received: from " + heloHost + " (" + host.getCanonicalHostName() + " [" + host + "])\r\n" +
" by " + whoami + " with SMTP;\r\n" +
" " + timestamp + "\r\n";
this.header = new ByteArrayInputStream(TextUtils.getAsciiBytes(header));
}
/* */
@Override
public int available() throws IOException
{
return this.header.available() + super.available();
}
/* */
@Override
public void close() throws IOException
{
super.close();
}
/* */
@Override
public synchronized void mark(int readlimit)
{
throw new UnsupportedOperationException();
}
/* */
@Override
public boolean markSupported()
{
return false;
}
/* */
@Override
public int read() throws IOException
{
if (this.header.available() > 0)
return this.header.read();
else
return super.read();
}
/* */
@Override
public int read(byte[] b, int off, int len) throws IOException
{
if (this.header.available() > 0)
{
int countRead = this.header.read(b, off, len);
if (countRead < len)
{
// We need to add a little extra from the normal stream
int remainder = len - countRead;
int additionalRead = super.read(b, countRead, remainder);
return countRead + additionalRead;
}
else
return countRead;
}
else
return super.read(b, off, len);
}
/* */
@Override
public int read(byte[] b) throws IOException
{
return this.read(b, 0, b.length);
}
/* */
@Override
public synchronized void reset() throws IOException
{
throw new UnsupportedOperationException();
}
/* */
@Override
public long skip(long n) throws IOException
{
throw new UnsupportedOperationException();
}
}
| true | true | public ReceivedHeaderStream(InputStream in, String heloHost, InetAddress host, String whoami)
{
super(in);
/* Looks like:
Received: from iamhelo (wasabi.infohazard.org [209.237.247.14])
by mx.google.com with SMTP id 32si2669129wfa.13.2009.05.27.18.27.31;
Wed, 27 May 2009 18:27:48 -0700 (PDT)
*/
DateFormat fmt = new SimpleDateFormat("EEE, dd MM yyyy HH:mm:ss Z (z)", Locale.US);
String timestamp = fmt.format(new Date());
String header =
"Received: from " + heloHost + " (" + host.getCanonicalHostName() + " [" + host + "])\r\n" +
" by " + whoami + " with SMTP;\r\n" +
" " + timestamp + "\r\n";
this.header = new ByteArrayInputStream(TextUtils.getAsciiBytes(header));
}
| public ReceivedHeaderStream(InputStream in, String heloHost, InetAddress host, String whoami)
{
super(in);
/* Looks like:
Received: from iamhelo (wasabi.infohazard.org [209.237.247.14])
by mx.google.com with SMTP id 32si2669129wfa.13.2009.05.27.18.27.31;
Wed, 27 May 2009 18:27:48 -0700 (PDT)
*/
DateFormat fmt = new SimpleDateFormat("EEE, dd MMM yyyy HH:mm:ss Z (z)", Locale.US);
String timestamp = fmt.format(new Date());
String header =
"Received: from " + heloHost + " (" + host.getCanonicalHostName() + " [" + host + "])\r\n" +
" by " + whoami + " with SMTP;\r\n" +
" " + timestamp + "\r\n";
this.header = new ByteArrayInputStream(TextUtils.getAsciiBytes(header));
}
|
diff --git a/main/src/main/java/com/bloatit/web/html/pages/DemandsPage.java b/main/src/main/java/com/bloatit/web/html/pages/DemandsPage.java
index 9da33a4c2..0a0ca9ae8 100644
--- a/main/src/main/java/com/bloatit/web/html/pages/DemandsPage.java
+++ b/main/src/main/java/com/bloatit/web/html/pages/DemandsPage.java
@@ -1,85 +1,85 @@
/*
* Copyright (C) 2010 BloatIt.
*
* This file is part of BloatIt.
*
* BloatIt is free software: you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* BloatIt is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with BloatIt. If not, see <http://www.gnu.org/licenses/>.
*/
package com.bloatit.web.html.pages;
import com.bloatit.common.PageIterable;
import com.bloatit.framework.Demand;
import com.bloatit.framework.managers.DemandManager;
import com.bloatit.web.exceptions.RedirectException;
import com.bloatit.web.html.HtmlNode;
import com.bloatit.web.html.components.custom.HtmlPagedList;
import com.bloatit.web.html.components.standard.HtmlListItem;
import com.bloatit.web.html.components.standard.HtmlRenderer;
import com.bloatit.web.html.components.standard.HtmlTitleBlock;
import com.bloatit.web.html.pages.demand.DemandPage;
import com.bloatit.web.html.pages.master.Page;
import com.bloatit.web.utils.annotations.PageComponent;
import com.bloatit.web.utils.url.Request;
import com.bloatit.web.utils.url.UrlBuilder;
public class DemandsPage extends Page {
@PageComponent
HtmlPagedList<Demand> pagedMemberList;
public DemandsPage(final Request request) throws RedirectException {
super(request);
generateContent();
}
private void generateContent() {
final HtmlTitleBlock pageTitle = new HtmlTitleBlock(session.tr("Demands list"),2);
final PageIterable<Demand> demandList = DemandManager.getDemands();
final HtmlRenderer<Demand> demandItemRenderer = new HtmlRenderer<Demand>() {
UrlBuilder demandPageUrlBuilder = new UrlBuilder(DemandPage.class);
@Override
public HtmlNode generate(final Demand demand) {
- demandPageUrlBuilder.addParameter("idea", demand);
+ demandPageUrlBuilder.addParameter("id", demand);
return new HtmlListItem(demandPageUrlBuilder.getHtmlLink(demand.getTitle()));
}
};
pagedMemberList = new HtmlPagedList<Demand>(demandItemRenderer, demandList, request, session);
pageTitle.add(pagedMemberList);
add(pageTitle);
}
@Override
public String getTitle() {
return "View all demands - search demands";
}
@Override
public boolean isStable() {
return true;
}
public String isBancale() {
return "peut-être";
}
}
| true | true | private void generateContent() {
final HtmlTitleBlock pageTitle = new HtmlTitleBlock(session.tr("Demands list"),2);
final PageIterable<Demand> demandList = DemandManager.getDemands();
final HtmlRenderer<Demand> demandItemRenderer = new HtmlRenderer<Demand>() {
UrlBuilder demandPageUrlBuilder = new UrlBuilder(DemandPage.class);
@Override
public HtmlNode generate(final Demand demand) {
demandPageUrlBuilder.addParameter("idea", demand);
return new HtmlListItem(demandPageUrlBuilder.getHtmlLink(demand.getTitle()));
}
};
pagedMemberList = new HtmlPagedList<Demand>(demandItemRenderer, demandList, request, session);
pageTitle.add(pagedMemberList);
add(pageTitle);
}
| private void generateContent() {
final HtmlTitleBlock pageTitle = new HtmlTitleBlock(session.tr("Demands list"),2);
final PageIterable<Demand> demandList = DemandManager.getDemands();
final HtmlRenderer<Demand> demandItemRenderer = new HtmlRenderer<Demand>() {
UrlBuilder demandPageUrlBuilder = new UrlBuilder(DemandPage.class);
@Override
public HtmlNode generate(final Demand demand) {
demandPageUrlBuilder.addParameter("id", demand);
return new HtmlListItem(demandPageUrlBuilder.getHtmlLink(demand.getTitle()));
}
};
pagedMemberList = new HtmlPagedList<Demand>(demandItemRenderer, demandList, request, session);
pageTitle.add(pagedMemberList);
add(pageTitle);
}
|
diff --git a/src/com/bekvon/bukkit/residence/Residence.java b/src/com/bekvon/bukkit/residence/Residence.java
index e1568eb..137a26e 100644
--- a/src/com/bekvon/bukkit/residence/Residence.java
+++ b/src/com/bekvon/bukkit/residence/Residence.java
@@ -1,1928 +1,1932 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package com.bekvon.bukkit.residence;
import com.bekvon.bukkit.residence.chat.ChatChannel;
import com.bekvon.bukkit.residence.chat.ChatManager;
import com.bekvon.bukkit.residence.economy.BOSEAdapter;
import com.bekvon.bukkit.residence.protection.CuboidArea;
import com.bekvon.bukkit.residence.protection.LeaseManager;
import com.bekvon.bukkit.residence.listeners.ResidenceBlockListener;
import com.bekvon.bukkit.residence.listeners.ResidencePlayerListener;
import com.bekvon.bukkit.residence.listeners.ResidenceEntityListener;
import com.bekvon.bukkit.residence.economy.EconomyInterface;
import com.bekvon.bukkit.residence.economy.EssentialsEcoAdapter;
import com.bekvon.bukkit.residence.economy.IConomy4Adapter;
import com.bekvon.bukkit.residence.economy.IConomyAdapter;
import com.bekvon.bukkit.residence.economy.MineConomyAdapter;
import com.bekvon.bukkit.residence.economy.RealShopEconomy;
import com.bekvon.bukkit.residence.economy.rent.RentManager;
import com.bekvon.bukkit.residence.economy.TransactionManager;
import com.bekvon.bukkit.residence.event.ResidenceCommandEvent;
import com.bekvon.bukkit.residence.itemlist.WorldItemManager;
import com.bekvon.bukkit.residence.permissions.PermissionGroup;
import com.bekvon.bukkit.residence.protection.PermissionListManager;
import com.bekvon.bukkit.residence.selection.SelectionManager;
import com.bekvon.bukkit.residence.permissions.PermissionManager;
import com.bekvon.bukkit.residence.persistance.YMLSaveHelper;
import com.bekvon.bukkit.residence.protection.ResidenceManager;
import com.bekvon.bukkit.residence.protection.ClaimedResidence;
import com.bekvon.bukkit.residence.protection.FlagPermissions;
import com.bekvon.bukkit.residence.protection.WorldFlagManager;
import com.bekvon.bukkit.residence.text.Language;
import com.bekvon.bukkit.residence.text.help.HelpEntry;
import com.bekvon.bukkit.residence.text.help.InformationPager;
import com.earth2me.essentials.Essentials;
import com.iConomy.iConomy;
import com.spikensbror.bukkit.mineconomy.MineConomy;
import cosine.boseconomy.BOSEconomy;
import fr.crafter.tickleman.RealShop.RealShopPlugin;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
import java.util.jar.JarEntry;
import java.util.jar.JarFile;
import java.util.logging.Level;
import java.util.logging.Logger;
import net.minecraft.server.FontAllowedCharacters;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.Server;
import org.bukkit.command.Command;
import org.bukkit.command.CommandSender;
import org.bukkit.command.ConsoleCommandSender;
import org.bukkit.entity.Player;
import org.bukkit.event.Event;
import org.bukkit.event.Event.Priority;
import org.bukkit.plugin.Plugin;
import org.bukkit.plugin.PluginManager;
import org.bukkit.plugin.java.JavaPlugin;
import org.bukkit.util.config.Configuration;
/**
*
* @author Gary Smoak - bekvon
*
*/
public class Residence extends JavaPlugin {
private static ResidenceManager rmanager;
private static SelectionManager smanager;
private static PermissionManager gmanager;
private static ConfigManager cmanager;
private static ResidenceBlockListener blistener;
private static ResidencePlayerListener plistener;
private static ResidenceEntityListener elistener;
private static TransactionManager tmanager;
private static PermissionListManager pmanager;
private static LeaseManager leasemanager;
private static WorldItemManager imanager;
private static WorldFlagManager wmanager;
private static RentManager rentmanager;
private static ChatManager chatmanager;
private static Server server;
private static HelpEntry helppages;
private static Language language;
private boolean firstenable = true;
private static EconomyInterface economy;
private final static int saveVersion = 1;
private static File ymlSaveLoc;
private static int leaseBukkitId=-1;
private static int rentBukkitId=-1;
private static int healBukkitId=-1;
private static int autosaveBukkitId=-1;
private static boolean initsuccess = false;
private Map<String,String> deleteConfirm;
private Runnable doHeals = new Runnable() {
public void run() {
plistener.doHeals();
}
};
private Runnable rentExpire = new Runnable()
{
public void run() {
rentmanager.checkCurrentRents();
if(cmanager.showIntervalMessages())
System.out.println("[Residence] - Rent Expirations checked!");
}
};
private Runnable leaseExpire = new Runnable() {
public void run() {
leasemanager.doExpirations();
if(cmanager.showIntervalMessages())
System.out.println("[Residence] - Lease Expirations checked!");
}
};
private Runnable autoSave = new Runnable() {
public void run() {
saveYml();
}
};
public Residence() {
}
public void reloadPlugin()
{
this.setEnabled(false);
this.setEnabled(true);
}
public void onDisable() {
server.getScheduler().cancelTask(autosaveBukkitId);
server.getScheduler().cancelTask(healBukkitId);
if (cmanager.useLeases()) {
server.getScheduler().cancelTask(leaseBukkitId);
}
if(cmanager.enabledRentSystem())
{
server.getScheduler().cancelTask(rentBukkitId);
}
if(initsuccess)
{
saveYml();
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Disabled!");
}
}
public void onEnable() {
try {
initsuccess = false;
deleteConfirm = new HashMap<String, String>();
server = this.getServer();
if (!new File(this.getDataFolder(), "config.yml").isFile()) {
this.writeDefaultConfigFromJar();
}
this.getConfiguration().load();
if(this.getConfiguration().getInt("ResidenceVersion", 0) == 0)
{
this.writeDefaultConfigFromJar();
this.getConfiguration().load();
System.out.println("[Residence] Config Invalid, wrote default...");
}
cmanager = new ConfigManager(this.getConfiguration());
String multiworld = cmanager.getMultiworldPlugin();
if (multiworld != null) {
Plugin plugin = server.getPluginManager().getPlugin(multiworld);
if (plugin != null) {
if (!plugin.isEnabled()) {
server.getPluginManager().enablePlugin(plugin);
System.out.println("[Residence] - Enabling multiworld plugin: " + multiworld);
}
}
}
gmanager = new PermissionManager(this.getConfiguration());
imanager = new WorldItemManager(this.getConfiguration());
wmanager = new WorldFlagManager(this.getConfiguration());
chatmanager = new ChatManager();
rentmanager = new RentManager();
try
{
File langFile = new File(new File(this.getDataFolder(),"Language"), cmanager.getLanguage() + ".yml");
if(this.checkNewLanguageVersion())
this.writeDefaultLanguageFile();
if(langFile.isFile())
{
Configuration langconfig = new Configuration(langFile);
langconfig.load();
helppages = HelpEntry.parseHelp(langconfig, "CommandHelp");
HelpEntry.setLinesPerPage(langconfig.getInt("HelpLinesPerPage", 7));
InformationPager.setLinesPerPage(langconfig.getInt("HelpLinesPerPage", 7));
language = Language.parseText(langconfig, "Language");
}
else
System.out.println("[Residence] Language file does not exist...");
}
catch (Exception ex)
{
System.out.println("[Residence] Failed to load language file: " + cmanager.getLanguage() + ".yml, Error: " + ex.getMessage());
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
helppages = new HelpEntry("");
language = new Language();
}
ymlSaveLoc = new File(this.getDataFolder(), "res.yml");
economy = null;
if (!this.getDataFolder().isDirectory()) {
this.getDataFolder().mkdirs();
}
String econsys = cmanager.getEconomySystem();
if (this.getConfiguration().getBoolean("Global.EnableEconomy", false) && econsys != null) {
if (econsys.toLowerCase().equals("iconomy")) {
this.loadIConomy();
} else if (econsys.toLowerCase().equals("mineconomy")) {
this.loadMineConomy();
} else if (econsys.toLowerCase().equals("boseconomy")) {
this.loadBOSEconomy();
} else if (econsys.toLowerCase().equals("essentials")) {
this.loadEssentialsEconomy();
} else if (econsys.toLowerCase().equals("realeconomy")) {
this.loadRealEconomy();
} else {
System.out.println("[Residence] Unknown economy system: " + econsys);
}
}
this.loadYml();
if (rmanager == null) {
rmanager = new ResidenceManager();
}
if (leasemanager == null) {
leasemanager = new LeaseManager(rmanager);
}
if (tmanager == null) {
tmanager = new TransactionManager(rmanager, gmanager);
}
if (pmanager == null) {
pmanager = new PermissionListManager();
}
if (firstenable) {
if(!this.isEnabled())
return;
FlagPermissions.initValidFlags();
smanager = new SelectionManager();
blistener = new ResidenceBlockListener();
plistener = new ResidencePlayerListener();
elistener = new ResidenceEntityListener();
PluginManager pm = getServer().getPluginManager();
pm.registerEvent(Event.Type.BLOCK_BREAK, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PLACE, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_IGNITE, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_BURN, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_FROMTO, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_INTERACT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_MOVE, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_QUIT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_EMPTY, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_BUCKET_FILL, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.PLAYER_CHAT, plistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.CREATURE_SPAWN, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_DAMAGE, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.ENTITY_EXPLODE, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.EXPLOSION_PRIME, elistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_SPREAD, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_EXTEND, blistener, Priority.Lowest, this);
pm.registerEvent(Event.Type.BLOCK_PISTON_RETRACT, blistener, Priority.Lowest, this);
firstenable = false;
}
else
{
plistener.reload();
}
int autosaveInt = cmanager.getAutoSaveInterval();
if (autosaveInt < 1) {
autosaveInt = 1;
}
autosaveInt = (autosaveInt * 60) * 20;
autosaveBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, autoSave, autosaveInt, autosaveInt);
healBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, doHeals, 20, 20);
if (cmanager.useLeases()) {
int leaseInterval = cmanager.getLeaseCheckInterval();
if (leaseInterval < 1) {
leaseInterval = 1;
}
leaseInterval = (leaseInterval * 60) * 20;
leaseBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, leaseExpire, leaseInterval, leaseInterval);
}
if(cmanager.enabledRentSystem())
{
int rentint = cmanager.getRentCheckInterval();
if(rentint < 1)
rentint = 1;
rentint = (rentint * 60) * 20;
rentBukkitId = server.getScheduler().scheduleSyncRepeatingTask(this, rentExpire, rentint, rentint);
}
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Enabled! Version " + this.getDescription().getVersion() + " by bekvon");
initsuccess = true;
} catch (Exception ex) {
initsuccess = false;
getServer().getPluginManager().disablePlugin(this);
System.out.println("[Residence] - FAILED INITIALIZATION! DISABLED! ERROR:");
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
}
}
public static boolean validName(String name)
{
if(name.contains(":") || name.contains("."))
return false;
String namecheck = name.replaceAll(cmanager.getResidenceNameRegex(), "");
if(!name.equals(namecheck))
return false;
return Residence.validString(name);
}
public static boolean validString(String string)
{
for(int i = 0; i < string.length(); i++)
{
if(FontAllowedCharacters.allowedCharacters.indexOf(string.charAt(i)) < 0)
{
return false;
}
}
return true;
}
public static ResidenceManager getResidenceManager() {
return rmanager;
}
@Deprecated
public static ResidenceManager getResidenceManger()
{
return rmanager;
}
public static SelectionManager getSelectionManager() {
return smanager;
}
public static PermissionManager getPermissionManager() {
return gmanager;
}
public static EconomyInterface getEconomyManager() {
return economy;
}
public static Server getServ() {
return server;
}
public static LeaseManager getLeaseManager() {
return leasemanager;
}
public static ConfigManager getConfig() {
return cmanager;
}
public static TransactionManager getTransactionManager() {
return tmanager;
}
public static WorldItemManager getItemManager()
{
return imanager;
}
public static WorldFlagManager getWorldFlags()
{
return wmanager;
}
public static RentManager getRentManager()
{
return rentmanager;
}
public static ResidencePlayerListener getPlayerListener()
{
return plistener;
}
public static ResidenceBlockListener getBlockListener()
{
return blistener;
}
public static ResidenceEntityListener getEntityListener()
{
return elistener;
}
public static ChatManager getChatManager()
{
return chatmanager;
}
public static Language getLanguage()
{
if(language==null)
language = new Language();
return language;
}
public static FlagPermissions getPermsByLoc(Location loc)
{
ClaimedResidence res = rmanager.getByLoc(loc);
if(res!=null)
return res.getPermissions();
else
return wmanager.getPerms(loc.getWorld().getName());
}
private void loadIConomy()
{
Plugin p = getServer().getPluginManager().getPlugin("iConomy");
if (p != null) {
if(p.getDescription().getVersion().startsWith("5"))
{
economy = new IConomyAdapter((iConomy)p);
}
else
{
economy = new IConomy4Adapter((com.nijiko.coelho.iConomy.iConomy)p);
}
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Successfully linked with iConomy!");
} else {
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] iConomy NOT found!");
}
}
private void loadMineConomy()
{
Plugin p = getServer().getPluginManager().getPlugin("MineConomy");
if (p != null) {
economy = new MineConomyAdapter((MineConomy)p);
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Successfully linked with MineConomy!");
} else {
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] MineConomy NOT found!");
}
}
private void loadBOSEconomy()
{
Plugin p = getServer().getPluginManager().getPlugin("BOSEconomy");
if (p != null) {
economy = new BOSEAdapter((BOSEconomy)p);
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Successfully linked with BOSEconomy!");
} else {
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] BOSEconomy NOT found!");
}
}
private void loadEssentialsEconomy()
{
Plugin p = getServer().getPluginManager().getPlugin("Essentials");
if (p != null) {
economy = new EssentialsEcoAdapter((Essentials)p);
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Successfully linked with Essentials Economy!");
} else {
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Essentials Economy NOT found!");
}
}
private void loadRealEconomy()
{
Plugin p = getServer().getPluginManager().getPlugin("RealShop");
if (p != null) {
economy = new RealShopEconomy(((RealShopPlugin)p).realEconomy);
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] Successfully linked with RealShop Economy!");
} else {
Logger.getLogger("Minecraft").log(Level.INFO, "[Residence] RealShop Economy NOT found!");
}
}
@Override
public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
ResidenceCommandEvent cevent = new ResidenceCommandEvent(command.getName(),args,sender);
server.getPluginManager().callEvent(cevent);
if(cevent.isCancelled())
return true;
if(command.getName().equals("resreload") && args.length==0)
{
if(sender instanceof Player)
{
Player player = (Player) sender;
if(gmanager.isResidenceAdmin(player))
{
this.setEnabled(false);
this.setEnabled(true);
System.out.println("[Residence] Reloaded by "+player.getName()+".");
}
}
else
{
this.setEnabled(false);
this.setEnabled(true);
System.out.println("[Residence] Reloaded by console.");
}
return true;
}
if(command.getName().equals("resload"))
{
if(!(sender instanceof Player) || (sender instanceof Player && gmanager.isResidenceAdmin((Player) sender)))
{
try {
this.loadYMLSave(ymlSaveLoc);
sender.sendMessage("§a[Residence] Reloaded save file...");
} catch (Exception ex) {
sender.sendMessage("§c[Residence] Unable to reload the save file, exception occured!");
sender.sendMessage("§c"+ex.getMessage());
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
}
}
return true;
}
else if(command.getName().equals("resworld"))
{
if(args.length == 2 && args[0].equalsIgnoreCase("remove"))
{
if(sender instanceof ConsoleCommandSender)
{
rmanager.removeAllFromWorld(sender, args[1]);
return true;
}
else
sender.sendMessage("§cMUST be run from console.");
}
return false;
}
else if(command.getName().equals("rc"))
{
if (sender instanceof Player) {
Player player = (Player) sender;
String pname = player.getName();
if(cmanager.chatEnabled())
{
if(args.length==0)
{
plistener.tooglePlayerResidenceChat(player);
}
else
{
String area = plistener.getLastAreaName(pname);
if(area!=null)
{
ChatChannel channel = chatmanager.getChannel(area);
if(channel!=null)
{
String message="";
for(String arg : args)
{
message = message + " " + arg;
}
channel.chat(pname, message);
}
else
{
player.sendMessage("§c"+language.getPhrase("InvalidChannel"));
}
}
else
{
player.sendMessage("§c" + language.getPhrase("NotInResidence"));
}
}
}
else
player.sendMessage("§c" + language.getPhrase("ChatDisabled"));
}
return true;
}
else if(command.getName().equals("res") || command.getName().equals("residence") || command.getName().equals("resadmin")) {
if ((args.length > 0 && args[args.length - 1].equalsIgnoreCase("?")) || (args.length > 1 && args[args.length - 2].equals("?"))) {
if (helppages != null) {
String helppath = "res";
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("?")) {
break;
}
helppath = helppath + "." + args[i];
}
int page = 1;
if (!args[args.length - 1].equalsIgnoreCase("?")) {
try {
page = Integer.parseInt(args[args.length - 1]);
} catch (Exception ex) {
sender.sendMessage("§c"+language.getPhrase("InvalidHelp"));
}
}
if (helppages.containesEntry(helppath)) {
helppages.printHelp(sender, page, helppath);
return true;
}
}
}
int page = 1;
try{
if(args.length>0)
page = Integer.parseInt(args[args.length-1]);
}catch(Exception ex){}
if (sender instanceof Player) {
Player player = (Player) sender;
PermissionGroup group = Residence.getPermissionManager().getGroup(player);
String pname = player.getName();
boolean resadmin = false;
if(command.getName().equals("resadmin"))
{
resadmin = gmanager.isResidenceAdmin(player);
if(!resadmin)
{
player.sendMessage("§c" + language.getPhrase("NonAdmin"));
return true;
}
}
if (cmanager.allowAdminsOnly()) {
if (!resadmin) {
player.sendMessage("§c"+language.getPhrase("AdminOnly"));
return true;
}
}
if(args.length==0)
return false;
if (args.length == 0) {
args = new String[1];
args[0] = "?";
}
if (args[0].equals("select")) {
if (!group.selectCommandAccess() && !resadmin) {
player.sendMessage("§c" + language.getPhrase("SelectDiabled"));
return true;
}
if (!group.canCreateResidences() && group.getMaxSubzoneDepth() <= 0 && !resadmin) {
player.sendMessage("§c" + language.getPhrase("SelectDiabled"));
return true;
}
if (args.length == 2) {
if (args[1].equals("size") || args[1].equals("cost")) {
if (smanager.hasPlacedBoth(pname)) {
try {
smanager.showSelectionInfo(player);
return true;
} catch (Exception ex) {
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
return true;
}
}
} else if (args[1].equals("vert")) {
smanager.vert(player, resadmin);
return true;
} else if (args[1].equals("sky")) {
smanager.sky(player, resadmin);
return true;
} else if (args[1].equals("bedrock")) {
smanager.bedrock(player, resadmin);
return true;
} else if (args[1].equals("coords")) {
Location playerLoc1 = smanager.getPlayerLoc1(pname);
if (playerLoc1 != null) {
player.sendMessage("§a" + language.getPhrase("Primary.Selection") + ":§b (" + playerLoc1.getBlockX() + ", " + playerLoc1.getBlockY() + ", " + playerLoc1.getBlockZ() + ")");
}
Location playerLoc2 = smanager.getPlayerLoc2(pname);
if (playerLoc2 != null) {
player.sendMessage("§a" + language.getPhrase("Secondary.Selection") + ":§b (" + playerLoc2.getBlockX() + ", " + playerLoc2.getBlockY() + ", " + playerLoc2.getBlockZ() + ")");
}
return true;
} else if (args[1].equals("chunk")) {
smanager.selectChunk(player);
return true;
}
} else if (args.length == 3) {
if (args[1].equals("expand")) {
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidAmount"));
return true;
}
smanager.modify(player, false, amount);
return true;
} else if (args[1].equals("shift")) {
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidAmount"));
return true;
}
smanager.modify(player, true, amount);
return true;
}
}
if(args.length>1 && args[1].equals("residence")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if (res == null) {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
return true;
}
CuboidArea area = res.getArea(args[3]);
if (area != null) {
smanager.placeLoc1(pname, area.getHighLoc());
smanager.placeLoc2(pname, area.getLowLoc());
player.sendMessage("§a" + language.getPhrase("SelectionArea", "§6" + args[3] + "§a.§6" + args[2] + "§a"));
} else {
player.sendMessage("§c" + language.getPhrase("AreaNonExist"));
}
return true;
} else {
try {
smanager.selectBySize(player, Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3]));
return true;
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("SelectionFail"));
return true;
}
}
} else if (args[0].equals("create")) {
if (args.length != 2) {
return false;
}
if (smanager.hasPlacedBoth(pname)) {
rmanager.addResidence(player, args[1], smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname), resadmin);
return true;
} else {
player.sendMessage("§c" + language.getPhrase("SelectPoints"));
return true;
}
} else if (args[0].equals("subzone") || args[0].equals("sz")) {
if (args.length != 2 && args.length != 3) {
return false;
}
String zname;
String parent;
if (args.length == 2) {
parent = rmanager.getNameByLoc(player.getLocation());
zname = args[1];
} else {
parent = args[1];
zname = args[2];
}
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(parent);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.addSubzone(player, smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname), zname, resadmin);
return true;
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
return true;
}
} else if (args[0].equals("sublist")) {
if(args.length==1 || args.length == 2 || args.length == 3)
{
ClaimedResidence res;
if(args.length==1)
res = rmanager.getByLoc(player.getLocation());
else
res = rmanager.getByName(args[1]);
if(res!=null)
res.printSubzoneList(player, page);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
}
else if (args[0].equals("remove") || args[0].equals("delete")) {
if (args.length == 1) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
if (!deleteConfirm.containsKey(player.getName()) || !area.equalsIgnoreCase(deleteConfirm.get(player.getName()))) {
player.sendMessage("§c" + language.getPhrase("DeleteConfirm", "§e" + area + "§c"));
deleteConfirm.put(player.getName(), area);
} else {
rmanager.removeResidence(player, area, resadmin);
}
return true;
}
return false;
}
if (args.length != 2) {
return false;
}
if (!deleteConfirm.containsKey(player.getName()) || !args[1].equalsIgnoreCase(deleteConfirm.get(player.getName()))) {
player.sendMessage("§c" + language.getPhrase("DeleteConfirm", "§e" + args[1] + "§c"));
deleteConfirm.put(player.getName(), args[1]);
} else {
rmanager.removeResidence(player, args[1], resadmin);
}
return true;
}
else if(args[0].equalsIgnoreCase("confirm"))
{
if(args.length == 1)
{
String area = deleteConfirm.get(player.getName());
if(area==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else
{
rmanager.removeResidence(player, area, resadmin);
deleteConfirm.remove(player.getName());
}
}
return true;
}
else if (args[0].equalsIgnoreCase("removeall"))
{
if(args.length!=2)
return false;
if(resadmin || args[1].endsWith(pname))
{
rmanager.removeAllByOwner(args[1]);
player.sendMessage("§a"+language.getPhrase("RemovePlayersResidences","§e"+args[1]+"§a"));
}
else
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
}
return true;
}
else if (args[0].equals("area")) {
if (args.length == 4) {
if (args[1].equals("remove")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res!=null)
res.removeArea(player, args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
} else if (args[1].equals("add")) {
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res != null)
res.addArea(player, new CuboidArea(smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname)),args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
}
return true;
} else if (args[1].equals("replace")) {
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res != null)
res.replaceArea(player, new CuboidArea(smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname)),args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
}
return true;
}
}
if ((args.length == 3 || args.length == 4) && args[1].equals("list")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if (res != null) {
res.printAreaList(player, page);
} else {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
}
return true;
}
else if((args.length == 3 || args.length == 4) && args[1].equals("listall"))
{
ClaimedResidence res = rmanager.getByName(args[2]);
if (res != null) {
res.printAdvancedAreaList(player, page);
} else {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
}
return true;
}
} else if (args[0].equals("lists")) {
if(args.length==2)
{
if(args[1].equals("list"))
{
pmanager.printLists(player);
return true;
}
}
else if(args.length == 3) {
if (args[1].equals("view")) {
pmanager.printList(player, args[2]);
return true;
} else if (args[1].equals("remove")) {
pmanager.removeList(player, args[2]);
return true;
} else if (args[1].equals("add")) {
pmanager.makeList(player, args[2]);
return true;
}
} else if (args.length == 4) {
if (args[1].equals("apply")) {
pmanager.applyListToResidence(player, args[2], args[3], resadmin);
return true;
}
}
else if (args.length==5)
{
if(args[1].equals("set"))
{
pmanager.getList(pname, args[2]).setFlag(args[3], FlagPermissions.stringToFlagState(args[4]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
}
else if(args.length==6)
{
if(args[1].equals("gset"))
{
pmanager.getList(pname, args[2]).setGroupFlag(args[3], args[4], FlagPermissions.stringToFlagState(args[5]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
else if(args[1].equals("pset"))
{
pmanager.getList(pname, args[2]).setPlayerFlag(args[3], args[4], FlagPermissions.stringToFlagState(args[5]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
}
} else if (args[0].equals("default")) {
if (args.length == 2) {
ClaimedResidence res = rmanager.getByName(args[1]);
res.getPermissions().applyDefaultFlags(player, resadmin);
return true;
}
} else if (args[0].equals("limits")) {
if (args.length == 1) {
gmanager.getGroup(player).printLimits(player);
return true;
}
} else if (args[0].equals("info")) {
if (args.length == 1) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
rmanager.printAreaInfo(area, player);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 2) {
rmanager.printAreaInfo(args[1], player);
return true;
}
}
else if(args[0].equals("check"))
{
if(args.length == 3 || args.length == 4)
{
if(args.length == 4)
{
pname = args[3];
}
ClaimedResidence res = rmanager.getByName(args[1]);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
if(!res.getPermissions().hasApplicableFlag(pname, args[2]))
player.sendMessage(language.getPhrase("FlagCheckFalse","§e" + args[2] + "§c.§e" + pname +"§c.§e"+args[1]+"§c"));
else
player.sendMessage(language.getPhrase("FlagCheckTrue","§a"+args[2]+"§e.§a"+pname+"§e.§e"+args[1]+"§c."+(res.getPermissions().playerHas(pname, res.getPermissions().getWorld(), args[2], false) ? "§aTRUE" : "§cFALSE")));
return true;
}
}
else if (args[0].equals("current")) {
if(args.length!=1)
return false;
String res = rmanager.getNameByLoc(player.getLocation());
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
}
else
{
player.sendMessage("§a"+language.getPhrase("InResidence","§e" + res + "§a"));
}
return true;
} else if (args[0].equals("set")) {
if (args.length == 3) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
rmanager.getByName(area).getPermissions().setFlag(player, args[1], args[2], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 4) {
ClaimedResidence area = rmanager.getByName(args[1]);
if(area!=null)
{
area.getPermissions().setFlag(player, args[2], args[3], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
} else if (args[0].equals("pset")) {
if (args.length == 3 && args[2].equalsIgnoreCase("removeall"))
{
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if(area!=null)
area.getPermissions().removeAllPlayerFlags(player, args[1], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
else if(args.length == 4 && args[3].equalsIgnoreCase("removeall"))
{
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().removeAllPlayerFlags(player, args[2], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
else if(args.length == 4) {
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if (area != null) {
area.getPermissions().setPlayerFlag(player, args[1], args[2], args[3], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 5) {
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setPlayerFlag(player, args[2], args[3], args[4], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
} else if (args[0].equals("gset")) {
if (args.length == 4) {
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if (area != null) {
area.getPermissions().setGroupFlag(player, args[1], args[2], args[3], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
}
return true;
} else if (args.length == 5) {
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setGroupFlag(player, args[2], args[3], args[4], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
}
else if(args[0].equals("lset"))
{
ClaimedResidence res = null;
Material mat = null;
String listtype = null;
boolean showinfo = false;
if (args.length == 2 && args[1].equals("info")) {
res = rmanager.getByLoc(player.getLocation());
showinfo = true;
}
else if(args.length == 3 && args[2].equals("info")) {
res = rmanager.getByName(args[1]);
showinfo = true;
}
if (showinfo) {
if (res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
player.sendMessage("§cBlacklist:");
res.getItemBlacklist().printList(player);
player.sendMessage("§aIgnorelist:");
res.getItemIgnoreList().printList(player);
return true;
}
else if(args.length == 4)
{
res = rmanager.getByName(args[1]);
listtype = args[2];
try
{
mat = Material.valueOf(args[3].toUpperCase());
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
return true;
}
}
else if(args.length==3)
{
res = rmanager.getByLoc(player.getLocation());
listtype = args[1];
try
{
mat = Material.valueOf(args[2].toUpperCase());
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
return true;
}
}
if(res!=null)
{
if(listtype.equalsIgnoreCase("blacklist"))
{
res.getItemBlacklist().playerListChange(player, mat, resadmin);
}
else if(listtype.equalsIgnoreCase("ignorelist"))
{
res.getItemIgnoreList().playerListChange(player, mat, resadmin);
}
else
{
player.sendMessage("§c"+language.getPhrase("InvalidList"));
}
return true;
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else if (args[0].equals("list")) {
if(args.length == 1)
{
rmanager.listResidences(player);
return true;
}
else if (args.length == 2) {
try {
Integer.parseInt(args[1]);
rmanager.listResidences(player, page);
} catch (Exception ex) {
rmanager.listResidences(player, args[1]);
}
return true;
}
else if(args.length == 3)
{
rmanager.listResidences(player, args[1], page);
return true;
}
}
else if(args[0].equals("rename"))
{
if(args.length==3)
{
rmanager.renameResidence(player, args[1], args[2], resadmin);
return true;
}
}
else if(args[0].equals("renamearea"))
{
if(args.length==4)
{
ClaimedResidence res = rmanager.getByName(args[1]);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.renameArea(player, args[2], args[3], resadmin);
return true;
}
}
else if (args[0].equals("unstuck")) {
if (args.length != 1) {
return false;
}
group = gmanager.getGroup(player);
if(!group.hasUnstuckAccess())
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence res = rmanager.getByLoc(player.getLocation());
if (res == null) {
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
} else {
player.sendMessage("§e"+language.getPhrase("Moved")+"...");
player.teleport(res.getOutsideFreeLoc(player.getLocation()));
}
return true;
} else if (args[0].equals("mirror")) {
if (args.length != 3) {
return false;
}
rmanager.mirrorPerms(player, args[1], args[2], resadmin);
return true;
} else if (args[0].equals("listall")) {
if (args.length == 1) {
rmanager.listAllResidences(player, 1);
} else if (args.length == 2) {
try {
rmanager.listAllResidences(player, page);
} catch (Exception ex) {
}
} else {
return false;
}
return true;
} else if (args[0].equals("version")) {
player.sendMessage("§7------------------------------------");
player.sendMessage("§cThis server running §6Residence§c version: §9" + this.getDescription().getVersion());
player.sendMessage("§aCreated by: §ebekvon");
player.sendMessage("§3For a command list, and help, see the wiki:");
player.sendMessage("§ahttp://residencebukkitmod.wikispaces.com/");
player.sendMessage("§bVisit the Residence thread at:");
player.sendMessage("§9http://forums.bukkit.org/");
player.sendMessage("§7------------------------------------");
return true;
}
else if(args[0].equals("material"))
{
if(args.length!=2)
return false;
try
{
player.sendMessage("§a"+language.getPhrase("GetMaterial","§6" + args[1] + "§a.§c" + Material.getMaterial(Integer.parseInt(args[1])).name()+"§a"));
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
}
return true;
}
else if (args[0].equals("tpset")) {
ClaimedResidence res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setTpLoc(player, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args[0].equals("tp")) {
if (args.length != 2) {
return false;
}
ClaimedResidence res = rmanager.getByName(args[1]);
if (res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.tpToResidence(player, player, resadmin);
return true;
} else if (args[0].equals("lease")) {
if (args.length == 2 || args.length == 3) {
if (args[1].equals("renew")) {
if (args.length == 3) {
leasemanager.renewArea(args[2], player);
} else {
leasemanager.renewArea(rmanager.getNameByLoc(player.getLocation()), player);
}
return true;
} else if (args[1].equals("cost")) {
if (args.length == 3) {
ClaimedResidence res = Residence.getResidenceManager().getByName(args[2]);
if (res == null || leasemanager.leaseExpires(args[2])) {
int cost = leasemanager.getRenewCost(res);
player.sendMessage("§e"+language.getPhrase("LeaseRenewalCost","§c" + args[2] + "§e.§c" + cost + "§e"));
} else {
player.sendMessage("§c"+language.getPhrase("LeaseNotExpire"));
}
return true;
} else {
String area = rmanager.getNameByLoc(player.getLocation());
ClaimedResidence res = rmanager.getByName(area);
if (area == null || res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
return true;
}
if (leasemanager.leaseExpires(area)) {
int cost = leasemanager.getRenewCost(res);
player.sendMessage("§e"+language.getPhrase("LeaseRenewalCost","§c" + area + "§e.§c" + cost + "§e"));
} else {
player.sendMessage("§c"+language.getPhrase("LeaseNotExpire"));
}
return true;
}
}
} else if (args.length == 4) {
if (args[1].equals("set")) {
if (!resadmin) {
player.sendMessage("§c" + language.getPhrase("NoPermission"));
return true;
}
if (args[3].equals("infinite")) {
if (leasemanager.leaseExpires(args[2])) {
leasemanager.removeExpireTime(args[2]);
player.sendMessage("§a" + language.getPhrase("LeaseInfinite"));
} else {
player.sendMessage("§c" + language.getPhrase("LeaseNotExpire"));
}
return true;
} else {
int days;
try {
days = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidDays"));
return true;
}
leasemanager.setExpireTime(player, args[2], days);
return true;
}
}
}
return false;
} else if(args[0].equals("bank")) {
if(args.length!=3)
return false;
ClaimedResidence res = rmanager.getByName(plistener.getLastAreaName(pname));
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
return true;
}
int amount = 0;
try
{
amount = Integer.parseInt(args[2]);
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidAmount"));
return true;
}
if(args[1].equals("deposit"))
{
res.getBank().deposit(player, amount, resadmin);
}
else if(args[1].equals("withdraw"))
{
res.getBank().withdraw(player, amount, resadmin);
}
else
return false;
return true;
} else if (args[0].equals("market")) {
if(args.length == 1)
return false;
if(args[1].equals("list"))
{
if(!cmanager.enableEconomy())
{
player.sendMessage("§c"+language.getPhrase("MarketDisabled"));
return true;
}
player.sendMessage("§9---"+language.getPhrase("MarketList")+"---");
tmanager.printForSaleResidences(player);
if(cmanager.enabledRentSystem())
{
rentmanager.printRentableResidences(player);
}
return true;
}
else if (args[1].equals("autorenew")) {
if (!cmanager.enableEconomy()) {
player.sendMessage("§c"+language.getPhrase("MarketDisabled"));
return true;
}
if (args.length != 4) {
return false;
}
boolean value;
if (args[3].equalsIgnoreCase("true") || args[3].equalsIgnoreCase("t")) {
value = true;
} else if (args[3].equalsIgnoreCase("false") || args[3].equalsIgnoreCase("f")) {
value = false;
} else {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
if(rentmanager.isRented(args[2]) && rentmanager.getRentingPlayer(args[2]).equalsIgnoreCase(pname))
{
rentmanager.setRentedRepeatable(player, args[2], value, resadmin);
}
else if(rentmanager.isForRent(args[2]))
{
rentmanager.setRentRepeatable(player, args[2], value, resadmin);
}
else
{
player.sendMessage("§c"+language.getPhrase("RentReleaseInvalid","§e" + args[2] + "§c"));
}
return true;
}
else if(args[1].equals("rentable")) {
if (args.length < 5 || args.length > 6) {
return false;
}
if (!cmanager.enabledRentSystem()) {
player.sendMessage("§c" + language.getPhrase("RentDisabled"));
return true;
}
int days;
int cost;
try {
cost = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidCost"));
return true;
}
try {
days = Integer.parseInt(args[4]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidDays"));
return true;
}
boolean repeat = false;
if (args.length == 6) {
if (args[5].equalsIgnoreCase("t") || args[5].equalsIgnoreCase("true")) {
repeat = true;
} else if (!args[5].equalsIgnoreCase("f") && !args[5].equalsIgnoreCase("false")) {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
}
rentmanager.setForRent(player, args[2], cost, days, repeat, resadmin);
return true;
}
else if(args[1].equals("rent"))
{
if(args.length<3 || args.length>4)
return false;
boolean repeat = false;
if (args.length == 4) {
if (args[3].equalsIgnoreCase("t") || args[3].equalsIgnoreCase("true")) {
repeat = true;
} else if (!args[3].equalsIgnoreCase("f") && !args[3].equalsIgnoreCase("false")) {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
}
rentmanager.rent(player, args[2], repeat, resadmin);
return true;
}
else if(args[1].equals("release"))
{
if(args.length!=3)
return false;
if(rentmanager.isRented(args[2]))
{
rentmanager.removeFromForRent(player, args[2], resadmin);
}
else
{
rentmanager.unrent(player, args[2], resadmin);
}
return true;
}
else if(args.length == 2)
{
if (args[1].equals("info")) {
String areaname = rmanager.getNameByLoc(player.getLocation());
tmanager.viewSaleInfo(areaname, player);
if(cmanager.enabledRentSystem() && rentmanager.isForRent(areaname))
{
rentmanager.printRentInfo(player, areaname);
}
return true;
}
}
else if(args.length == 3) {
if (args[1].equals("buy")) {
tmanager.buyPlot(args[2], player, resadmin);
return true;
} else if (args[1].equals("info")) {
tmanager.viewSaleInfo(args[2], player);
if(cmanager.enabledRentSystem() && rentmanager.isForRent(args[2]))
{
rentmanager.printRentInfo(player, args[2]);
}
return true;
} else if (args[1].equals("unsell")) {
tmanager.removeFromSale(player, args[2], resadmin);
return true;
}
}
else if(args.length == 4) {
if (args[1].equals("sell")) {
int amount;
try {
amount = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidAmount"));
return true;
}
tmanager.putForSale(args[2], player, amount, resadmin);
return true;
}
}
return false;
} else if (args[0].equals("message")) {
ClaimedResidence res = null;
int start = 0;
boolean enter = false;
+ if(args.length<2)
+ return false;
if (args[1].equals("enter")) {
enter = true;
res = rmanager.getByLoc(player.getLocation());
start = 2;
} else if (args[1].equals("leave")) {
res = rmanager.getByLoc(player.getLocation());
start = 2;
- } else if (args[2].equals("enter")) {
+ } else if (args.length>2 && args[2].equals("enter")) {
enter = true;
res = rmanager.getByName(args[1]);
start = 3;
- } else if (args[2].equals("leave")) {
+ } else if (args.length>2 && args[2].equals("leave")) {
res = rmanager.getByName(args[1]);
start = 3;
- } else if (args[1].equals("remove")) {
+ } else if (args.length>2 && args[1].equals("remove")) {
if (args[2].equals("enter")) {
res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setEnterLeaveMessage(player, null, true, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args[2].equals("leave")) {
res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setEnterLeaveMessage(player, null, false, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
- } else if (args[2].equals("remove")) {
+ } else if (args.length>2 && args[2].equals("remove")) {
res = rmanager.getByName(args[1]);
if (args.length != 4) {
return false;
}
if (args[3].equals("enter")) {
if (res != null) {
res.setEnterLeaveMessage(player, null, true, resadmin);
}
return true;
} else if (args[3].equals("leave")) {
if (res != null) {
res.setEnterLeaveMessage(player, null, false, resadmin);
}
return true;
}
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
} else {
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
}
+ if(start == 0)
+ return false;
String message = "";
for (int i = start; i < args.length; i++) {
message = message + args[i] + " ";
}
if (res != null) {
res.setEnterLeaveMessage(player, message, enter, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
}
return true;
}
else if(args[0].equals("give"))
{
rmanager.giveResidence(player, args[2], args[1], resadmin);
return true;
}
else if (args[0].equals("setowner")) {
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setOwner(args[2], true);
player.sendMessage("§a"+language.getPhrase("ResidenceOwnerChange","§e " + args[1] + " §a.§e"+args[2]+"§a"));
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
else if(args[0].equals("server"))
{
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
if(args.length==2)
{
ClaimedResidence res = rmanager.getByName(args[1]);
if(res == null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.getPermissions().setOwner("Server Land", false);
player.sendMessage("§a"+language.getPhrase("ResidenceOwnerChange","§e " + args[1] + " §a.§eServer Land§a"));
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else if(args[0].equals("clearflags"))
{
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().clearFlags();
player.sendMessage("§a"+language.getPhrase("FlagsCleared"));
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
else if(args[0].equals("tool"))
{
player.sendMessage("§e"+language.getPhrase("SelectionTool")+":§a" + Material.getMaterial(cmanager.getSelectionTooldID()));
player.sendMessage("§e"+language.getPhrase("InfoTool")+": §a" + Material.getMaterial(cmanager.getInfoToolID()));
return true;
}
}
return false;
}
return super.onCommand(sender, command, label, args);
}
@Override
public void setEnabled(boolean enabled) {
super.setEnabled(enabled);
}
private void saveYml() {
YMLSaveHelper yml = new YMLSaveHelper(ymlSaveLoc);
yml.getRoot().put("SaveVersion", saveVersion);
yml.addMap("Residences", rmanager.save());
yml.addMap("Economy", tmanager.save());
yml.addMap("Leases", leasemanager.save());
yml.addMap("PermissionLists", pmanager.save());
yml.addMap("RentSystem", rentmanager.save());
File backupFile = new File(ymlSaveLoc.getParentFile(), ymlSaveLoc.getName() + ".bak");
if(ymlSaveLoc.isFile())
{
if(backupFile.isFile())
backupFile.delete();
ymlSaveLoc.renameTo(backupFile);
}
yml.save();
System.out.println("[Residence] - Saved Residences...");
}
private void loadYml() throws Exception {
try
{
if(ymlSaveLoc.isFile())
this.loadYMLSave(ymlSaveLoc);
else
{
File bakfile = new File(ymlSaveLoc.getParentFile(), ymlSaveLoc.getName() + ".bak");
if(bakfile.isFile())
this.loadYMLSave(bakfile);
else
System.out.println("[Residence] No save file found...");
}
}
catch (Exception ex)
{
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
File erroredfile;
if(ymlSaveLoc.isFile())
erroredfile = new File(ymlSaveLoc.getParent(), ymlSaveLoc.getName() + "-ERRORED.yml");
else
{
File bakfile = new File(ymlSaveLoc.getParentFile(), ymlSaveLoc.getName() + ".bak");
erroredfile = new File(bakfile.getParent(), bakfile.getName() + "-ERRORED.yml");
}
if(erroredfile.isFile())
erroredfile.delete();
ymlSaveLoc.renameTo(erroredfile);
try {
System.out.println("[Residence] - Main Save Corrupt, Loading Backup...");
this.loadYMLSave(new File(ymlSaveLoc.getParentFile(), ymlSaveLoc.getName() + ".bak"));
this.saveYml();
} catch (Exception ex1) {
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex1);
if(cmanager.stopOnSaveError())
{
this.setEnabled(false);
System.out.print("[Residence] - Save corrupted, disabling Residence!");
throw ex1;
}
}
}
}
private boolean loadYMLSave(File saveLoc) throws Exception {
if (saveLoc.isFile()) {
YMLSaveHelper yml = new YMLSaveHelper(saveLoc);
yml.load();
int sv = yml.getInt("SaveVersion", 0);
if (sv == 0) {
saveLoc.renameTo(new File(saveLoc.getParentFile(), "pre-upgrade-res.yml"));
yml = upgradeSave(yml);
}
rmanager = ResidenceManager.load(yml.getMap("Residences"));
tmanager = TransactionManager.load(yml.getMap("Economy"), gmanager, rmanager);
leasemanager = LeaseManager.load(yml.getMap("Leases"), rmanager);
pmanager = PermissionListManager.load(yml.getMap("PermissionLists"));
rentmanager = RentManager.load(yml.getMap("RentSystem"));
System.out.print("[Residence] Loaded Residences...");
return true;
} else {
System.out.println("[Residence] Save File not found...");
return false;
}
}
private void writeDefaultConfigFromJar()
{
if(this.writeDefaultFileFromJar(new File(this.getDataFolder(), "config.yml"), "config.yml", true))
System.out.println("[Residence] Wrote default config...");
}
private void writeDefaultLanguageFile()
{
String lang = cmanager.getLanguage();
File outFile = new File(new File(this.getDataFolder(),"Language"), lang+".yml");
outFile.getParentFile().mkdirs();
if(this.writeDefaultFileFromJar(outFile, "languagefiles/"+lang+".yml", true))
{
System.out.println("[Residence] Wrote default Language file...");
}
}
private boolean checkNewLanguageVersion()
{
String lang = cmanager.getLanguage();
File outFile = new File(new File(this.getDataFolder(),"Language"), lang+".yml");
File checkFile = new File(new File(this.getDataFolder(),"Language"), "temp-"+lang+".yml");
if(outFile.isFile())
{
Configuration testconfig = new Configuration(outFile);
testconfig.load();
int oldversion = testconfig.getInt("Version", 0);
if(!this.writeDefaultFileFromJar(checkFile, "languagefiles/"+lang+".yml", false))
return false;
Configuration testconfig2 = new Configuration(checkFile);
testconfig2.load();
int newversion = testconfig2.getInt("Version", oldversion);
if(checkFile.isFile())
checkFile.delete();
if(newversion>oldversion)
return true;
return false;
}
return true;
}
private boolean writeDefaultFileFromJar(File writeName, String jarPath, boolean backupOld)
{
try {
File fileBackup = new File(this.getDataFolder(),"backup-" + writeName);
File jarloc = new File(getClass().getProtectionDomain().getCodeSource().getLocation().toURI()).getCanonicalFile();
if(jarloc.isFile())
{
JarFile jar = new JarFile(jarloc);
JarEntry entry = jar.getJarEntry(jarPath);
if(entry!=null && !entry.isDirectory())
{
InputStream in = jar.getInputStream(entry);
if(writeName.isFile())
{
if(backupOld)
{
if(fileBackup.isFile())
fileBackup.delete();
writeName.renameTo(fileBackup);
}
else
writeName.delete();
}
FileOutputStream out = new FileOutputStream(writeName);
byte[] tempbytes = new byte[512];
int readbytes = in.read(tempbytes,0,512);
while(readbytes>-1)
{
out.write(tempbytes,0,readbytes);
readbytes = in.read(tempbytes,0,512);
}
out.close();
in.close();
return true;
}
}
return false;
} catch (Exception ex) {
System.out.println("[Residence] Failed to write file: " + writeName + " from the Residence jar file, Error:" + ex);
return false;
}
}
public YMLSaveHelper upgradeSave(YMLSaveHelper yml) throws Exception {
try {
Map<String, Object> root = yml.getRoot();
Map<String, Object> resmap = (Map<String, Object>) root.get("residences");
Map<String, Object> newmap = new HashMap<String, Object>();
for (Entry<String, Object> entry : resmap.entrySet()) {
Map<String, Object> resvals = (Map<String, Object>) entry.getValue();
newmap.put(entry.getKey(), upgradeResidence(resvals));
}
Map<String,Object> newroot = new HashMap<String,Object>();
newroot.put("Residences", newmap);
newroot.put("Leases", root.get("leasetimes"));
newroot.put("Economy", root.get("forsale"));
newroot.put("PermissionLists", new HashMap<String,Object>());
newroot.put("SaveVersion", 1);
yml.setRoot(newroot);
yml.save();
System.out.print("[Residence] Upgraded Save File!");
return yml;
} catch (Exception ex) {
System.out.println("[Residence] FAILED to upgrade save file...");
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
throw ex;
}
}
public Map<String,Object> upgradeResidence(Map<String, Object> resvals) {
Map<String,Object> newmap = new HashMap<String,Object>();
Map<String, Object> areas = new HashMap<String, Object>();
Map<String, Object> mainarea = new HashMap<String, Object>();
mainarea.put("X1", resvals.get("x1"));
mainarea.put("Y1", resvals.get("y1"));
mainarea.put("Z1", resvals.get("z1"));
mainarea.put("X2", resvals.get("x2"));
mainarea.put("Y2", resvals.get("y2"));
mainarea.put("Z2", resvals.get("z2"));
areas.put("main", mainarea);
newmap.put("Areas", areas);
Map<String,Object> oldperms = (Map<String, Object>) resvals.get("permissions");
Map<String,Object> perms = new HashMap<String,Object>();
perms.put("AreaFlags", upgradeFlags((Map<String, Object>) oldperms.get("areaflags")));
Map<String,Object> pflags = (Map<String, Object>) oldperms.get("playerflags");
Map<String,Object> newpflags = new HashMap<String,Object>();
for(Entry<String, Object> player : pflags.entrySet())
{
newpflags.put(player.getKey(), upgradeFlags((Map<String, Object>) player.getValue()));
}
perms.put("PlayerFlags", newpflags);
Map<String,Object> gflags = (Map<String, Object>) oldperms.get("groupflags");
Map<String,Object> newgflags = new HashMap<String,Object>();
for(Entry<String, Object> group : gflags.entrySet())
{
newpflags.put(group.getKey(), upgradeFlags((Map<String, Object>) group.getValue()));
}
perms.put("GroupFlags", newgflags);
perms.put("Owner", oldperms.get("owner"));
perms.put("World", resvals.get("world"));
newmap.put("Permissions", perms);
newmap.put("EnterMessage", resvals.get("entermessage"));
newmap.put("LeaveMessage", resvals.get("leavemessage"));
Map<String,Object> sz = (Map<String, Object>) resvals.get("subzones");
Map<String,Object> newsz = new HashMap<String,Object>();
for(Entry<String, Object> entry : sz.entrySet())
{
newsz.put(entry.getKey(),upgradeResidence((Map<String, Object>) entry.getValue()));
}
newmap.put("Subzones", newsz);
return newmap;
}
public Map<String,Object> upgradeFlags(Map<String,Object> inflags)
{
Map<String,Object> newmap = new HashMap<String,Object>();
for(Entry<String, Object> flag : inflags.entrySet())
{
String flagname = flag.getKey();
boolean flagval = (Boolean)flag.getValue();
if(flagname.equals("fire"))
{
newmap.put("ignite", flagval);
newmap.put("firespread", flagval);
}
else if(flagname.equals("explosions"))
{
newmap.put("creeper", flagval);
newmap.put("tnt", flagval);
}
else if(flagname.equals("use"))
{
newmap.put("use", flagval);
newmap.put("container", flagval);
}
else
{
newmap.put(flagname, flagval);
}
}
return newmap;
}
}
| false | true | public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
ResidenceCommandEvent cevent = new ResidenceCommandEvent(command.getName(),args,sender);
server.getPluginManager().callEvent(cevent);
if(cevent.isCancelled())
return true;
if(command.getName().equals("resreload") && args.length==0)
{
if(sender instanceof Player)
{
Player player = (Player) sender;
if(gmanager.isResidenceAdmin(player))
{
this.setEnabled(false);
this.setEnabled(true);
System.out.println("[Residence] Reloaded by "+player.getName()+".");
}
}
else
{
this.setEnabled(false);
this.setEnabled(true);
System.out.println("[Residence] Reloaded by console.");
}
return true;
}
if(command.getName().equals("resload"))
{
if(!(sender instanceof Player) || (sender instanceof Player && gmanager.isResidenceAdmin((Player) sender)))
{
try {
this.loadYMLSave(ymlSaveLoc);
sender.sendMessage("§a[Residence] Reloaded save file...");
} catch (Exception ex) {
sender.sendMessage("§c[Residence] Unable to reload the save file, exception occured!");
sender.sendMessage("§c"+ex.getMessage());
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
}
}
return true;
}
else if(command.getName().equals("resworld"))
{
if(args.length == 2 && args[0].equalsIgnoreCase("remove"))
{
if(sender instanceof ConsoleCommandSender)
{
rmanager.removeAllFromWorld(sender, args[1]);
return true;
}
else
sender.sendMessage("§cMUST be run from console.");
}
return false;
}
else if(command.getName().equals("rc"))
{
if (sender instanceof Player) {
Player player = (Player) sender;
String pname = player.getName();
if(cmanager.chatEnabled())
{
if(args.length==0)
{
plistener.tooglePlayerResidenceChat(player);
}
else
{
String area = plistener.getLastAreaName(pname);
if(area!=null)
{
ChatChannel channel = chatmanager.getChannel(area);
if(channel!=null)
{
String message="";
for(String arg : args)
{
message = message + " " + arg;
}
channel.chat(pname, message);
}
else
{
player.sendMessage("§c"+language.getPhrase("InvalidChannel"));
}
}
else
{
player.sendMessage("§c" + language.getPhrase("NotInResidence"));
}
}
}
else
player.sendMessage("§c" + language.getPhrase("ChatDisabled"));
}
return true;
}
else if(command.getName().equals("res") || command.getName().equals("residence") || command.getName().equals("resadmin")) {
if ((args.length > 0 && args[args.length - 1].equalsIgnoreCase("?")) || (args.length > 1 && args[args.length - 2].equals("?"))) {
if (helppages != null) {
String helppath = "res";
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("?")) {
break;
}
helppath = helppath + "." + args[i];
}
int page = 1;
if (!args[args.length - 1].equalsIgnoreCase("?")) {
try {
page = Integer.parseInt(args[args.length - 1]);
} catch (Exception ex) {
sender.sendMessage("§c"+language.getPhrase("InvalidHelp"));
}
}
if (helppages.containesEntry(helppath)) {
helppages.printHelp(sender, page, helppath);
return true;
}
}
}
int page = 1;
try{
if(args.length>0)
page = Integer.parseInt(args[args.length-1]);
}catch(Exception ex){}
if (sender instanceof Player) {
Player player = (Player) sender;
PermissionGroup group = Residence.getPermissionManager().getGroup(player);
String pname = player.getName();
boolean resadmin = false;
if(command.getName().equals("resadmin"))
{
resadmin = gmanager.isResidenceAdmin(player);
if(!resadmin)
{
player.sendMessage("§c" + language.getPhrase("NonAdmin"));
return true;
}
}
if (cmanager.allowAdminsOnly()) {
if (!resadmin) {
player.sendMessage("§c"+language.getPhrase("AdminOnly"));
return true;
}
}
if(args.length==0)
return false;
if (args.length == 0) {
args = new String[1];
args[0] = "?";
}
if (args[0].equals("select")) {
if (!group.selectCommandAccess() && !resadmin) {
player.sendMessage("§c" + language.getPhrase("SelectDiabled"));
return true;
}
if (!group.canCreateResidences() && group.getMaxSubzoneDepth() <= 0 && !resadmin) {
player.sendMessage("§c" + language.getPhrase("SelectDiabled"));
return true;
}
if (args.length == 2) {
if (args[1].equals("size") || args[1].equals("cost")) {
if (smanager.hasPlacedBoth(pname)) {
try {
smanager.showSelectionInfo(player);
return true;
} catch (Exception ex) {
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
return true;
}
}
} else if (args[1].equals("vert")) {
smanager.vert(player, resadmin);
return true;
} else if (args[1].equals("sky")) {
smanager.sky(player, resadmin);
return true;
} else if (args[1].equals("bedrock")) {
smanager.bedrock(player, resadmin);
return true;
} else if (args[1].equals("coords")) {
Location playerLoc1 = smanager.getPlayerLoc1(pname);
if (playerLoc1 != null) {
player.sendMessage("§a" + language.getPhrase("Primary.Selection") + ":§b (" + playerLoc1.getBlockX() + ", " + playerLoc1.getBlockY() + ", " + playerLoc1.getBlockZ() + ")");
}
Location playerLoc2 = smanager.getPlayerLoc2(pname);
if (playerLoc2 != null) {
player.sendMessage("§a" + language.getPhrase("Secondary.Selection") + ":§b (" + playerLoc2.getBlockX() + ", " + playerLoc2.getBlockY() + ", " + playerLoc2.getBlockZ() + ")");
}
return true;
} else if (args[1].equals("chunk")) {
smanager.selectChunk(player);
return true;
}
} else if (args.length == 3) {
if (args[1].equals("expand")) {
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidAmount"));
return true;
}
smanager.modify(player, false, amount);
return true;
} else if (args[1].equals("shift")) {
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidAmount"));
return true;
}
smanager.modify(player, true, amount);
return true;
}
}
if(args.length>1 && args[1].equals("residence")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if (res == null) {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
return true;
}
CuboidArea area = res.getArea(args[3]);
if (area != null) {
smanager.placeLoc1(pname, area.getHighLoc());
smanager.placeLoc2(pname, area.getLowLoc());
player.sendMessage("§a" + language.getPhrase("SelectionArea", "§6" + args[3] + "§a.§6" + args[2] + "§a"));
} else {
player.sendMessage("§c" + language.getPhrase("AreaNonExist"));
}
return true;
} else {
try {
smanager.selectBySize(player, Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3]));
return true;
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("SelectionFail"));
return true;
}
}
} else if (args[0].equals("create")) {
if (args.length != 2) {
return false;
}
if (smanager.hasPlacedBoth(pname)) {
rmanager.addResidence(player, args[1], smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname), resadmin);
return true;
} else {
player.sendMessage("§c" + language.getPhrase("SelectPoints"));
return true;
}
} else if (args[0].equals("subzone") || args[0].equals("sz")) {
if (args.length != 2 && args.length != 3) {
return false;
}
String zname;
String parent;
if (args.length == 2) {
parent = rmanager.getNameByLoc(player.getLocation());
zname = args[1];
} else {
parent = args[1];
zname = args[2];
}
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(parent);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.addSubzone(player, smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname), zname, resadmin);
return true;
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
return true;
}
} else if (args[0].equals("sublist")) {
if(args.length==1 || args.length == 2 || args.length == 3)
{
ClaimedResidence res;
if(args.length==1)
res = rmanager.getByLoc(player.getLocation());
else
res = rmanager.getByName(args[1]);
if(res!=null)
res.printSubzoneList(player, page);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
}
else if (args[0].equals("remove") || args[0].equals("delete")) {
if (args.length == 1) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
if (!deleteConfirm.containsKey(player.getName()) || !area.equalsIgnoreCase(deleteConfirm.get(player.getName()))) {
player.sendMessage("§c" + language.getPhrase("DeleteConfirm", "§e" + area + "§c"));
deleteConfirm.put(player.getName(), area);
} else {
rmanager.removeResidence(player, area, resadmin);
}
return true;
}
return false;
}
if (args.length != 2) {
return false;
}
if (!deleteConfirm.containsKey(player.getName()) || !args[1].equalsIgnoreCase(deleteConfirm.get(player.getName()))) {
player.sendMessage("§c" + language.getPhrase("DeleteConfirm", "§e" + args[1] + "§c"));
deleteConfirm.put(player.getName(), args[1]);
} else {
rmanager.removeResidence(player, args[1], resadmin);
}
return true;
}
else if(args[0].equalsIgnoreCase("confirm"))
{
if(args.length == 1)
{
String area = deleteConfirm.get(player.getName());
if(area==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else
{
rmanager.removeResidence(player, area, resadmin);
deleteConfirm.remove(player.getName());
}
}
return true;
}
else if (args[0].equalsIgnoreCase("removeall"))
{
if(args.length!=2)
return false;
if(resadmin || args[1].endsWith(pname))
{
rmanager.removeAllByOwner(args[1]);
player.sendMessage("§a"+language.getPhrase("RemovePlayersResidences","§e"+args[1]+"§a"));
}
else
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
}
return true;
}
else if (args[0].equals("area")) {
if (args.length == 4) {
if (args[1].equals("remove")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res!=null)
res.removeArea(player, args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
} else if (args[1].equals("add")) {
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res != null)
res.addArea(player, new CuboidArea(smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname)),args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
}
return true;
} else if (args[1].equals("replace")) {
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res != null)
res.replaceArea(player, new CuboidArea(smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname)),args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
}
return true;
}
}
if ((args.length == 3 || args.length == 4) && args[1].equals("list")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if (res != null) {
res.printAreaList(player, page);
} else {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
}
return true;
}
else if((args.length == 3 || args.length == 4) && args[1].equals("listall"))
{
ClaimedResidence res = rmanager.getByName(args[2]);
if (res != null) {
res.printAdvancedAreaList(player, page);
} else {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
}
return true;
}
} else if (args[0].equals("lists")) {
if(args.length==2)
{
if(args[1].equals("list"))
{
pmanager.printLists(player);
return true;
}
}
else if(args.length == 3) {
if (args[1].equals("view")) {
pmanager.printList(player, args[2]);
return true;
} else if (args[1].equals("remove")) {
pmanager.removeList(player, args[2]);
return true;
} else if (args[1].equals("add")) {
pmanager.makeList(player, args[2]);
return true;
}
} else if (args.length == 4) {
if (args[1].equals("apply")) {
pmanager.applyListToResidence(player, args[2], args[3], resadmin);
return true;
}
}
else if (args.length==5)
{
if(args[1].equals("set"))
{
pmanager.getList(pname, args[2]).setFlag(args[3], FlagPermissions.stringToFlagState(args[4]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
}
else if(args.length==6)
{
if(args[1].equals("gset"))
{
pmanager.getList(pname, args[2]).setGroupFlag(args[3], args[4], FlagPermissions.stringToFlagState(args[5]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
else if(args[1].equals("pset"))
{
pmanager.getList(pname, args[2]).setPlayerFlag(args[3], args[4], FlagPermissions.stringToFlagState(args[5]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
}
} else if (args[0].equals("default")) {
if (args.length == 2) {
ClaimedResidence res = rmanager.getByName(args[1]);
res.getPermissions().applyDefaultFlags(player, resadmin);
return true;
}
} else if (args[0].equals("limits")) {
if (args.length == 1) {
gmanager.getGroup(player).printLimits(player);
return true;
}
} else if (args[0].equals("info")) {
if (args.length == 1) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
rmanager.printAreaInfo(area, player);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 2) {
rmanager.printAreaInfo(args[1], player);
return true;
}
}
else if(args[0].equals("check"))
{
if(args.length == 3 || args.length == 4)
{
if(args.length == 4)
{
pname = args[3];
}
ClaimedResidence res = rmanager.getByName(args[1]);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
if(!res.getPermissions().hasApplicableFlag(pname, args[2]))
player.sendMessage(language.getPhrase("FlagCheckFalse","§e" + args[2] + "§c.§e" + pname +"§c.§e"+args[1]+"§c"));
else
player.sendMessage(language.getPhrase("FlagCheckTrue","§a"+args[2]+"§e.§a"+pname+"§e.§e"+args[1]+"§c."+(res.getPermissions().playerHas(pname, res.getPermissions().getWorld(), args[2], false) ? "§aTRUE" : "§cFALSE")));
return true;
}
}
else if (args[0].equals("current")) {
if(args.length!=1)
return false;
String res = rmanager.getNameByLoc(player.getLocation());
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
}
else
{
player.sendMessage("§a"+language.getPhrase("InResidence","§e" + res + "§a"));
}
return true;
} else if (args[0].equals("set")) {
if (args.length == 3) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
rmanager.getByName(area).getPermissions().setFlag(player, args[1], args[2], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 4) {
ClaimedResidence area = rmanager.getByName(args[1]);
if(area!=null)
{
area.getPermissions().setFlag(player, args[2], args[3], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
} else if (args[0].equals("pset")) {
if (args.length == 3 && args[2].equalsIgnoreCase("removeall"))
{
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if(area!=null)
area.getPermissions().removeAllPlayerFlags(player, args[1], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
else if(args.length == 4 && args[3].equalsIgnoreCase("removeall"))
{
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().removeAllPlayerFlags(player, args[2], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
else if(args.length == 4) {
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if (area != null) {
area.getPermissions().setPlayerFlag(player, args[1], args[2], args[3], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 5) {
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setPlayerFlag(player, args[2], args[3], args[4], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
} else if (args[0].equals("gset")) {
if (args.length == 4) {
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if (area != null) {
area.getPermissions().setGroupFlag(player, args[1], args[2], args[3], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
}
return true;
} else if (args.length == 5) {
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setGroupFlag(player, args[2], args[3], args[4], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
}
else if(args[0].equals("lset"))
{
ClaimedResidence res = null;
Material mat = null;
String listtype = null;
boolean showinfo = false;
if (args.length == 2 && args[1].equals("info")) {
res = rmanager.getByLoc(player.getLocation());
showinfo = true;
}
else if(args.length == 3 && args[2].equals("info")) {
res = rmanager.getByName(args[1]);
showinfo = true;
}
if (showinfo) {
if (res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
player.sendMessage("§cBlacklist:");
res.getItemBlacklist().printList(player);
player.sendMessage("§aIgnorelist:");
res.getItemIgnoreList().printList(player);
return true;
}
else if(args.length == 4)
{
res = rmanager.getByName(args[1]);
listtype = args[2];
try
{
mat = Material.valueOf(args[3].toUpperCase());
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
return true;
}
}
else if(args.length==3)
{
res = rmanager.getByLoc(player.getLocation());
listtype = args[1];
try
{
mat = Material.valueOf(args[2].toUpperCase());
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
return true;
}
}
if(res!=null)
{
if(listtype.equalsIgnoreCase("blacklist"))
{
res.getItemBlacklist().playerListChange(player, mat, resadmin);
}
else if(listtype.equalsIgnoreCase("ignorelist"))
{
res.getItemIgnoreList().playerListChange(player, mat, resadmin);
}
else
{
player.sendMessage("§c"+language.getPhrase("InvalidList"));
}
return true;
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else if (args[0].equals("list")) {
if(args.length == 1)
{
rmanager.listResidences(player);
return true;
}
else if (args.length == 2) {
try {
Integer.parseInt(args[1]);
rmanager.listResidences(player, page);
} catch (Exception ex) {
rmanager.listResidences(player, args[1]);
}
return true;
}
else if(args.length == 3)
{
rmanager.listResidences(player, args[1], page);
return true;
}
}
else if(args[0].equals("rename"))
{
if(args.length==3)
{
rmanager.renameResidence(player, args[1], args[2], resadmin);
return true;
}
}
else if(args[0].equals("renamearea"))
{
if(args.length==4)
{
ClaimedResidence res = rmanager.getByName(args[1]);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.renameArea(player, args[2], args[3], resadmin);
return true;
}
}
else if (args[0].equals("unstuck")) {
if (args.length != 1) {
return false;
}
group = gmanager.getGroup(player);
if(!group.hasUnstuckAccess())
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence res = rmanager.getByLoc(player.getLocation());
if (res == null) {
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
} else {
player.sendMessage("§e"+language.getPhrase("Moved")+"...");
player.teleport(res.getOutsideFreeLoc(player.getLocation()));
}
return true;
} else if (args[0].equals("mirror")) {
if (args.length != 3) {
return false;
}
rmanager.mirrorPerms(player, args[1], args[2], resadmin);
return true;
} else if (args[0].equals("listall")) {
if (args.length == 1) {
rmanager.listAllResidences(player, 1);
} else if (args.length == 2) {
try {
rmanager.listAllResidences(player, page);
} catch (Exception ex) {
}
} else {
return false;
}
return true;
} else if (args[0].equals("version")) {
player.sendMessage("§7------------------------------------");
player.sendMessage("§cThis server running §6Residence§c version: §9" + this.getDescription().getVersion());
player.sendMessage("§aCreated by: §ebekvon");
player.sendMessage("§3For a command list, and help, see the wiki:");
player.sendMessage("§ahttp://residencebukkitmod.wikispaces.com/");
player.sendMessage("§bVisit the Residence thread at:");
player.sendMessage("§9http://forums.bukkit.org/");
player.sendMessage("§7------------------------------------");
return true;
}
else if(args[0].equals("material"))
{
if(args.length!=2)
return false;
try
{
player.sendMessage("§a"+language.getPhrase("GetMaterial","§6" + args[1] + "§a.§c" + Material.getMaterial(Integer.parseInt(args[1])).name()+"§a"));
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
}
return true;
}
else if (args[0].equals("tpset")) {
ClaimedResidence res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setTpLoc(player, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args[0].equals("tp")) {
if (args.length != 2) {
return false;
}
ClaimedResidence res = rmanager.getByName(args[1]);
if (res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.tpToResidence(player, player, resadmin);
return true;
} else if (args[0].equals("lease")) {
if (args.length == 2 || args.length == 3) {
if (args[1].equals("renew")) {
if (args.length == 3) {
leasemanager.renewArea(args[2], player);
} else {
leasemanager.renewArea(rmanager.getNameByLoc(player.getLocation()), player);
}
return true;
} else if (args[1].equals("cost")) {
if (args.length == 3) {
ClaimedResidence res = Residence.getResidenceManager().getByName(args[2]);
if (res == null || leasemanager.leaseExpires(args[2])) {
int cost = leasemanager.getRenewCost(res);
player.sendMessage("§e"+language.getPhrase("LeaseRenewalCost","§c" + args[2] + "§e.§c" + cost + "§e"));
} else {
player.sendMessage("§c"+language.getPhrase("LeaseNotExpire"));
}
return true;
} else {
String area = rmanager.getNameByLoc(player.getLocation());
ClaimedResidence res = rmanager.getByName(area);
if (area == null || res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
return true;
}
if (leasemanager.leaseExpires(area)) {
int cost = leasemanager.getRenewCost(res);
player.sendMessage("§e"+language.getPhrase("LeaseRenewalCost","§c" + area + "§e.§c" + cost + "§e"));
} else {
player.sendMessage("§c"+language.getPhrase("LeaseNotExpire"));
}
return true;
}
}
} else if (args.length == 4) {
if (args[1].equals("set")) {
if (!resadmin) {
player.sendMessage("§c" + language.getPhrase("NoPermission"));
return true;
}
if (args[3].equals("infinite")) {
if (leasemanager.leaseExpires(args[2])) {
leasemanager.removeExpireTime(args[2]);
player.sendMessage("§a" + language.getPhrase("LeaseInfinite"));
} else {
player.sendMessage("§c" + language.getPhrase("LeaseNotExpire"));
}
return true;
} else {
int days;
try {
days = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidDays"));
return true;
}
leasemanager.setExpireTime(player, args[2], days);
return true;
}
}
}
return false;
} else if(args[0].equals("bank")) {
if(args.length!=3)
return false;
ClaimedResidence res = rmanager.getByName(plistener.getLastAreaName(pname));
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
return true;
}
int amount = 0;
try
{
amount = Integer.parseInt(args[2]);
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidAmount"));
return true;
}
if(args[1].equals("deposit"))
{
res.getBank().deposit(player, amount, resadmin);
}
else if(args[1].equals("withdraw"))
{
res.getBank().withdraw(player, amount, resadmin);
}
else
return false;
return true;
} else if (args[0].equals("market")) {
if(args.length == 1)
return false;
if(args[1].equals("list"))
{
if(!cmanager.enableEconomy())
{
player.sendMessage("§c"+language.getPhrase("MarketDisabled"));
return true;
}
player.sendMessage("§9---"+language.getPhrase("MarketList")+"---");
tmanager.printForSaleResidences(player);
if(cmanager.enabledRentSystem())
{
rentmanager.printRentableResidences(player);
}
return true;
}
else if (args[1].equals("autorenew")) {
if (!cmanager.enableEconomy()) {
player.sendMessage("§c"+language.getPhrase("MarketDisabled"));
return true;
}
if (args.length != 4) {
return false;
}
boolean value;
if (args[3].equalsIgnoreCase("true") || args[3].equalsIgnoreCase("t")) {
value = true;
} else if (args[3].equalsIgnoreCase("false") || args[3].equalsIgnoreCase("f")) {
value = false;
} else {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
if(rentmanager.isRented(args[2]) && rentmanager.getRentingPlayer(args[2]).equalsIgnoreCase(pname))
{
rentmanager.setRentedRepeatable(player, args[2], value, resadmin);
}
else if(rentmanager.isForRent(args[2]))
{
rentmanager.setRentRepeatable(player, args[2], value, resadmin);
}
else
{
player.sendMessage("§c"+language.getPhrase("RentReleaseInvalid","§e" + args[2] + "§c"));
}
return true;
}
else if(args[1].equals("rentable")) {
if (args.length < 5 || args.length > 6) {
return false;
}
if (!cmanager.enabledRentSystem()) {
player.sendMessage("§c" + language.getPhrase("RentDisabled"));
return true;
}
int days;
int cost;
try {
cost = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidCost"));
return true;
}
try {
days = Integer.parseInt(args[4]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidDays"));
return true;
}
boolean repeat = false;
if (args.length == 6) {
if (args[5].equalsIgnoreCase("t") || args[5].equalsIgnoreCase("true")) {
repeat = true;
} else if (!args[5].equalsIgnoreCase("f") && !args[5].equalsIgnoreCase("false")) {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
}
rentmanager.setForRent(player, args[2], cost, days, repeat, resadmin);
return true;
}
else if(args[1].equals("rent"))
{
if(args.length<3 || args.length>4)
return false;
boolean repeat = false;
if (args.length == 4) {
if (args[3].equalsIgnoreCase("t") || args[3].equalsIgnoreCase("true")) {
repeat = true;
} else if (!args[3].equalsIgnoreCase("f") && !args[3].equalsIgnoreCase("false")) {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
}
rentmanager.rent(player, args[2], repeat, resadmin);
return true;
}
else if(args[1].equals("release"))
{
if(args.length!=3)
return false;
if(rentmanager.isRented(args[2]))
{
rentmanager.removeFromForRent(player, args[2], resadmin);
}
else
{
rentmanager.unrent(player, args[2], resadmin);
}
return true;
}
else if(args.length == 2)
{
if (args[1].equals("info")) {
String areaname = rmanager.getNameByLoc(player.getLocation());
tmanager.viewSaleInfo(areaname, player);
if(cmanager.enabledRentSystem() && rentmanager.isForRent(areaname))
{
rentmanager.printRentInfo(player, areaname);
}
return true;
}
}
else if(args.length == 3) {
if (args[1].equals("buy")) {
tmanager.buyPlot(args[2], player, resadmin);
return true;
} else if (args[1].equals("info")) {
tmanager.viewSaleInfo(args[2], player);
if(cmanager.enabledRentSystem() && rentmanager.isForRent(args[2]))
{
rentmanager.printRentInfo(player, args[2]);
}
return true;
} else if (args[1].equals("unsell")) {
tmanager.removeFromSale(player, args[2], resadmin);
return true;
}
}
else if(args.length == 4) {
if (args[1].equals("sell")) {
int amount;
try {
amount = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidAmount"));
return true;
}
tmanager.putForSale(args[2], player, amount, resadmin);
return true;
}
}
return false;
} else if (args[0].equals("message")) {
ClaimedResidence res = null;
int start = 0;
boolean enter = false;
if (args[1].equals("enter")) {
enter = true;
res = rmanager.getByLoc(player.getLocation());
start = 2;
} else if (args[1].equals("leave")) {
res = rmanager.getByLoc(player.getLocation());
start = 2;
} else if (args[2].equals("enter")) {
enter = true;
res = rmanager.getByName(args[1]);
start = 3;
} else if (args[2].equals("leave")) {
res = rmanager.getByName(args[1]);
start = 3;
} else if (args[1].equals("remove")) {
if (args[2].equals("enter")) {
res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setEnterLeaveMessage(player, null, true, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args[2].equals("leave")) {
res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setEnterLeaveMessage(player, null, false, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
} else if (args[2].equals("remove")) {
res = rmanager.getByName(args[1]);
if (args.length != 4) {
return false;
}
if (args[3].equals("enter")) {
if (res != null) {
res.setEnterLeaveMessage(player, null, true, resadmin);
}
return true;
} else if (args[3].equals("leave")) {
if (res != null) {
res.setEnterLeaveMessage(player, null, false, resadmin);
}
return true;
}
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
} else {
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
}
String message = "";
for (int i = start; i < args.length; i++) {
message = message + args[i] + " ";
}
if (res != null) {
res.setEnterLeaveMessage(player, message, enter, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
}
return true;
}
else if(args[0].equals("give"))
{
rmanager.giveResidence(player, args[2], args[1], resadmin);
return true;
}
else if (args[0].equals("setowner")) {
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setOwner(args[2], true);
player.sendMessage("§a"+language.getPhrase("ResidenceOwnerChange","§e " + args[1] + " §a.§e"+args[2]+"§a"));
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
else if(args[0].equals("server"))
{
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
if(args.length==2)
{
ClaimedResidence res = rmanager.getByName(args[1]);
if(res == null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.getPermissions().setOwner("Server Land", false);
player.sendMessage("§a"+language.getPhrase("ResidenceOwnerChange","§e " + args[1] + " §a.§eServer Land§a"));
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else if(args[0].equals("clearflags"))
{
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().clearFlags();
player.sendMessage("§a"+language.getPhrase("FlagsCleared"));
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
else if(args[0].equals("tool"))
{
player.sendMessage("§e"+language.getPhrase("SelectionTool")+":§a" + Material.getMaterial(cmanager.getSelectionTooldID()));
player.sendMessage("§e"+language.getPhrase("InfoTool")+": §a" + Material.getMaterial(cmanager.getInfoToolID()));
return true;
}
}
return false;
}
return super.onCommand(sender, command, label, args);
}
| public boolean onCommand(CommandSender sender, Command command, String label, String[] args) {
ResidenceCommandEvent cevent = new ResidenceCommandEvent(command.getName(),args,sender);
server.getPluginManager().callEvent(cevent);
if(cevent.isCancelled())
return true;
if(command.getName().equals("resreload") && args.length==0)
{
if(sender instanceof Player)
{
Player player = (Player) sender;
if(gmanager.isResidenceAdmin(player))
{
this.setEnabled(false);
this.setEnabled(true);
System.out.println("[Residence] Reloaded by "+player.getName()+".");
}
}
else
{
this.setEnabled(false);
this.setEnabled(true);
System.out.println("[Residence] Reloaded by console.");
}
return true;
}
if(command.getName().equals("resload"))
{
if(!(sender instanceof Player) || (sender instanceof Player && gmanager.isResidenceAdmin((Player) sender)))
{
try {
this.loadYMLSave(ymlSaveLoc);
sender.sendMessage("§a[Residence] Reloaded save file...");
} catch (Exception ex) {
sender.sendMessage("§c[Residence] Unable to reload the save file, exception occured!");
sender.sendMessage("§c"+ex.getMessage());
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
}
}
return true;
}
else if(command.getName().equals("resworld"))
{
if(args.length == 2 && args[0].equalsIgnoreCase("remove"))
{
if(sender instanceof ConsoleCommandSender)
{
rmanager.removeAllFromWorld(sender, args[1]);
return true;
}
else
sender.sendMessage("§cMUST be run from console.");
}
return false;
}
else if(command.getName().equals("rc"))
{
if (sender instanceof Player) {
Player player = (Player) sender;
String pname = player.getName();
if(cmanager.chatEnabled())
{
if(args.length==0)
{
plistener.tooglePlayerResidenceChat(player);
}
else
{
String area = plistener.getLastAreaName(pname);
if(area!=null)
{
ChatChannel channel = chatmanager.getChannel(area);
if(channel!=null)
{
String message="";
for(String arg : args)
{
message = message + " " + arg;
}
channel.chat(pname, message);
}
else
{
player.sendMessage("§c"+language.getPhrase("InvalidChannel"));
}
}
else
{
player.sendMessage("§c" + language.getPhrase("NotInResidence"));
}
}
}
else
player.sendMessage("§c" + language.getPhrase("ChatDisabled"));
}
return true;
}
else if(command.getName().equals("res") || command.getName().equals("residence") || command.getName().equals("resadmin")) {
if ((args.length > 0 && args[args.length - 1].equalsIgnoreCase("?")) || (args.length > 1 && args[args.length - 2].equals("?"))) {
if (helppages != null) {
String helppath = "res";
for (int i = 0; i < args.length; i++) {
if (args[i].equalsIgnoreCase("?")) {
break;
}
helppath = helppath + "." + args[i];
}
int page = 1;
if (!args[args.length - 1].equalsIgnoreCase("?")) {
try {
page = Integer.parseInt(args[args.length - 1]);
} catch (Exception ex) {
sender.sendMessage("§c"+language.getPhrase("InvalidHelp"));
}
}
if (helppages.containesEntry(helppath)) {
helppages.printHelp(sender, page, helppath);
return true;
}
}
}
int page = 1;
try{
if(args.length>0)
page = Integer.parseInt(args[args.length-1]);
}catch(Exception ex){}
if (sender instanceof Player) {
Player player = (Player) sender;
PermissionGroup group = Residence.getPermissionManager().getGroup(player);
String pname = player.getName();
boolean resadmin = false;
if(command.getName().equals("resadmin"))
{
resadmin = gmanager.isResidenceAdmin(player);
if(!resadmin)
{
player.sendMessage("§c" + language.getPhrase("NonAdmin"));
return true;
}
}
if (cmanager.allowAdminsOnly()) {
if (!resadmin) {
player.sendMessage("§c"+language.getPhrase("AdminOnly"));
return true;
}
}
if(args.length==0)
return false;
if (args.length == 0) {
args = new String[1];
args[0] = "?";
}
if (args[0].equals("select")) {
if (!group.selectCommandAccess() && !resadmin) {
player.sendMessage("§c" + language.getPhrase("SelectDiabled"));
return true;
}
if (!group.canCreateResidences() && group.getMaxSubzoneDepth() <= 0 && !resadmin) {
player.sendMessage("§c" + language.getPhrase("SelectDiabled"));
return true;
}
if (args.length == 2) {
if (args[1].equals("size") || args[1].equals("cost")) {
if (smanager.hasPlacedBoth(pname)) {
try {
smanager.showSelectionInfo(player);
return true;
} catch (Exception ex) {
Logger.getLogger(Residence.class.getName()).log(Level.SEVERE, null, ex);
return true;
}
}
} else if (args[1].equals("vert")) {
smanager.vert(player, resadmin);
return true;
} else if (args[1].equals("sky")) {
smanager.sky(player, resadmin);
return true;
} else if (args[1].equals("bedrock")) {
smanager.bedrock(player, resadmin);
return true;
} else if (args[1].equals("coords")) {
Location playerLoc1 = smanager.getPlayerLoc1(pname);
if (playerLoc1 != null) {
player.sendMessage("§a" + language.getPhrase("Primary.Selection") + ":§b (" + playerLoc1.getBlockX() + ", " + playerLoc1.getBlockY() + ", " + playerLoc1.getBlockZ() + ")");
}
Location playerLoc2 = smanager.getPlayerLoc2(pname);
if (playerLoc2 != null) {
player.sendMessage("§a" + language.getPhrase("Secondary.Selection") + ":§b (" + playerLoc2.getBlockX() + ", " + playerLoc2.getBlockY() + ", " + playerLoc2.getBlockZ() + ")");
}
return true;
} else if (args[1].equals("chunk")) {
smanager.selectChunk(player);
return true;
}
} else if (args.length == 3) {
if (args[1].equals("expand")) {
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidAmount"));
return true;
}
smanager.modify(player, false, amount);
return true;
} else if (args[1].equals("shift")) {
int amount;
try {
amount = Integer.parseInt(args[2]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidAmount"));
return true;
}
smanager.modify(player, true, amount);
return true;
}
}
if(args.length>1 && args[1].equals("residence")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if (res == null) {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
return true;
}
CuboidArea area = res.getArea(args[3]);
if (area != null) {
smanager.placeLoc1(pname, area.getHighLoc());
smanager.placeLoc2(pname, area.getLowLoc());
player.sendMessage("§a" + language.getPhrase("SelectionArea", "§6" + args[3] + "§a.§6" + args[2] + "§a"));
} else {
player.sendMessage("§c" + language.getPhrase("AreaNonExist"));
}
return true;
} else {
try {
smanager.selectBySize(player, Integer.parseInt(args[1]), Integer.parseInt(args[2]), Integer.parseInt(args[3]));
return true;
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("SelectionFail"));
return true;
}
}
} else if (args[0].equals("create")) {
if (args.length != 2) {
return false;
}
if (smanager.hasPlacedBoth(pname)) {
rmanager.addResidence(player, args[1], smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname), resadmin);
return true;
} else {
player.sendMessage("§c" + language.getPhrase("SelectPoints"));
return true;
}
} else if (args[0].equals("subzone") || args[0].equals("sz")) {
if (args.length != 2 && args.length != 3) {
return false;
}
String zname;
String parent;
if (args.length == 2) {
parent = rmanager.getNameByLoc(player.getLocation());
zname = args[1];
} else {
parent = args[1];
zname = args[2];
}
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(parent);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.addSubzone(player, smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname), zname, resadmin);
return true;
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
return true;
}
} else if (args[0].equals("sublist")) {
if(args.length==1 || args.length == 2 || args.length == 3)
{
ClaimedResidence res;
if(args.length==1)
res = rmanager.getByLoc(player.getLocation());
else
res = rmanager.getByName(args[1]);
if(res!=null)
res.printSubzoneList(player, page);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
}
else if (args[0].equals("remove") || args[0].equals("delete")) {
if (args.length == 1) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
if (!deleteConfirm.containsKey(player.getName()) || !area.equalsIgnoreCase(deleteConfirm.get(player.getName()))) {
player.sendMessage("§c" + language.getPhrase("DeleteConfirm", "§e" + area + "§c"));
deleteConfirm.put(player.getName(), area);
} else {
rmanager.removeResidence(player, area, resadmin);
}
return true;
}
return false;
}
if (args.length != 2) {
return false;
}
if (!deleteConfirm.containsKey(player.getName()) || !args[1].equalsIgnoreCase(deleteConfirm.get(player.getName()))) {
player.sendMessage("§c" + language.getPhrase("DeleteConfirm", "§e" + args[1] + "§c"));
deleteConfirm.put(player.getName(), args[1]);
} else {
rmanager.removeResidence(player, args[1], resadmin);
}
return true;
}
else if(args[0].equalsIgnoreCase("confirm"))
{
if(args.length == 1)
{
String area = deleteConfirm.get(player.getName());
if(area==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else
{
rmanager.removeResidence(player, area, resadmin);
deleteConfirm.remove(player.getName());
}
}
return true;
}
else if (args[0].equalsIgnoreCase("removeall"))
{
if(args.length!=2)
return false;
if(resadmin || args[1].endsWith(pname))
{
rmanager.removeAllByOwner(args[1]);
player.sendMessage("§a"+language.getPhrase("RemovePlayersResidences","§e"+args[1]+"§a"));
}
else
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
}
return true;
}
else if (args[0].equals("area")) {
if (args.length == 4) {
if (args[1].equals("remove")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res!=null)
res.removeArea(player, args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
} else if (args[1].equals("add")) {
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res != null)
res.addArea(player, new CuboidArea(smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname)),args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
}
return true;
} else if (args[1].equals("replace")) {
if (smanager.hasPlacedBoth(pname)) {
ClaimedResidence res = rmanager.getByName(args[2]);
if(res != null)
res.replaceArea(player, new CuboidArea(smanager.getPlayerLoc1(pname), smanager.getPlayerLoc2(pname)),args[3], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
} else {
player.sendMessage("§c"+language.getPhrase("SelectPoints"));
}
return true;
}
}
if ((args.length == 3 || args.length == 4) && args[1].equals("list")) {
ClaimedResidence res = rmanager.getByName(args[2]);
if (res != null) {
res.printAreaList(player, page);
} else {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
}
return true;
}
else if((args.length == 3 || args.length == 4) && args[1].equals("listall"))
{
ClaimedResidence res = rmanager.getByName(args[2]);
if (res != null) {
res.printAdvancedAreaList(player, page);
} else {
player.sendMessage("§c" + language.getPhrase("InvalidResidence"));
}
return true;
}
} else if (args[0].equals("lists")) {
if(args.length==2)
{
if(args[1].equals("list"))
{
pmanager.printLists(player);
return true;
}
}
else if(args.length == 3) {
if (args[1].equals("view")) {
pmanager.printList(player, args[2]);
return true;
} else if (args[1].equals("remove")) {
pmanager.removeList(player, args[2]);
return true;
} else if (args[1].equals("add")) {
pmanager.makeList(player, args[2]);
return true;
}
} else if (args.length == 4) {
if (args[1].equals("apply")) {
pmanager.applyListToResidence(player, args[2], args[3], resadmin);
return true;
}
}
else if (args.length==5)
{
if(args[1].equals("set"))
{
pmanager.getList(pname, args[2]).setFlag(args[3], FlagPermissions.stringToFlagState(args[4]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
}
else if(args.length==6)
{
if(args[1].equals("gset"))
{
pmanager.getList(pname, args[2]).setGroupFlag(args[3], args[4], FlagPermissions.stringToFlagState(args[5]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
else if(args[1].equals("pset"))
{
pmanager.getList(pname, args[2]).setPlayerFlag(args[3], args[4], FlagPermissions.stringToFlagState(args[5]));
player.sendMessage("§a"+language.getPhrase("FlagSet"));
return true;
}
}
} else if (args[0].equals("default")) {
if (args.length == 2) {
ClaimedResidence res = rmanager.getByName(args[1]);
res.getPermissions().applyDefaultFlags(player, resadmin);
return true;
}
} else if (args[0].equals("limits")) {
if (args.length == 1) {
gmanager.getGroup(player).printLimits(player);
return true;
}
} else if (args[0].equals("info")) {
if (args.length == 1) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
rmanager.printAreaInfo(area, player);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 2) {
rmanager.printAreaInfo(args[1], player);
return true;
}
}
else if(args[0].equals("check"))
{
if(args.length == 3 || args.length == 4)
{
if(args.length == 4)
{
pname = args[3];
}
ClaimedResidence res = rmanager.getByName(args[1]);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
if(!res.getPermissions().hasApplicableFlag(pname, args[2]))
player.sendMessage(language.getPhrase("FlagCheckFalse","§e" + args[2] + "§c.§e" + pname +"§c.§e"+args[1]+"§c"));
else
player.sendMessage(language.getPhrase("FlagCheckTrue","§a"+args[2]+"§e.§a"+pname+"§e.§e"+args[1]+"§c."+(res.getPermissions().playerHas(pname, res.getPermissions().getWorld(), args[2], false) ? "§aTRUE" : "§cFALSE")));
return true;
}
}
else if (args[0].equals("current")) {
if(args.length!=1)
return false;
String res = rmanager.getNameByLoc(player.getLocation());
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
}
else
{
player.sendMessage("§a"+language.getPhrase("InResidence","§e" + res + "§a"));
}
return true;
} else if (args[0].equals("set")) {
if (args.length == 3) {
String area = rmanager.getNameByLoc(player.getLocation());
if (area != null) {
rmanager.getByName(area).getPermissions().setFlag(player, args[1], args[2], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 4) {
ClaimedResidence area = rmanager.getByName(args[1]);
if(area!=null)
{
area.getPermissions().setFlag(player, args[2], args[3], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
} else if (args[0].equals("pset")) {
if (args.length == 3 && args[2].equalsIgnoreCase("removeall"))
{
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if(area!=null)
area.getPermissions().removeAllPlayerFlags(player, args[1], resadmin);
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
else if(args.length == 4 && args[3].equalsIgnoreCase("removeall"))
{
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().removeAllPlayerFlags(player, args[2], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
else if(args.length == 4) {
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if (area != null) {
area.getPermissions().setPlayerFlag(player, args[1], args[2], args[3], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args.length == 5) {
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setPlayerFlag(player, args[2], args[3], args[4], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
} else if (args[0].equals("gset")) {
if (args.length == 4) {
ClaimedResidence area = rmanager.getByLoc(player.getLocation());
if (area != null) {
area.getPermissions().setGroupFlag(player, args[1], args[2], args[3], resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
}
return true;
} else if (args.length == 5) {
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setGroupFlag(player, args[2], args[3], args[4], resadmin);
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
}
else if(args[0].equals("lset"))
{
ClaimedResidence res = null;
Material mat = null;
String listtype = null;
boolean showinfo = false;
if (args.length == 2 && args[1].equals("info")) {
res = rmanager.getByLoc(player.getLocation());
showinfo = true;
}
else if(args.length == 3 && args[2].equals("info")) {
res = rmanager.getByName(args[1]);
showinfo = true;
}
if (showinfo) {
if (res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
player.sendMessage("§cBlacklist:");
res.getItemBlacklist().printList(player);
player.sendMessage("§aIgnorelist:");
res.getItemIgnoreList().printList(player);
return true;
}
else if(args.length == 4)
{
res = rmanager.getByName(args[1]);
listtype = args[2];
try
{
mat = Material.valueOf(args[3].toUpperCase());
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
return true;
}
}
else if(args.length==3)
{
res = rmanager.getByLoc(player.getLocation());
listtype = args[1];
try
{
mat = Material.valueOf(args[2].toUpperCase());
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
return true;
}
}
if(res!=null)
{
if(listtype.equalsIgnoreCase("blacklist"))
{
res.getItemBlacklist().playerListChange(player, mat, resadmin);
}
else if(listtype.equalsIgnoreCase("ignorelist"))
{
res.getItemIgnoreList().playerListChange(player, mat, resadmin);
}
else
{
player.sendMessage("§c"+language.getPhrase("InvalidList"));
}
return true;
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else if (args[0].equals("list")) {
if(args.length == 1)
{
rmanager.listResidences(player);
return true;
}
else if (args.length == 2) {
try {
Integer.parseInt(args[1]);
rmanager.listResidences(player, page);
} catch (Exception ex) {
rmanager.listResidences(player, args[1]);
}
return true;
}
else if(args.length == 3)
{
rmanager.listResidences(player, args[1], page);
return true;
}
}
else if(args[0].equals("rename"))
{
if(args.length==3)
{
rmanager.renameResidence(player, args[1], args[2], resadmin);
return true;
}
}
else if(args[0].equals("renamearea"))
{
if(args.length==4)
{
ClaimedResidence res = rmanager.getByName(args[1]);
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.renameArea(player, args[2], args[3], resadmin);
return true;
}
}
else if (args[0].equals("unstuck")) {
if (args.length != 1) {
return false;
}
group = gmanager.getGroup(player);
if(!group.hasUnstuckAccess())
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence res = rmanager.getByLoc(player.getLocation());
if (res == null) {
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
} else {
player.sendMessage("§e"+language.getPhrase("Moved")+"...");
player.teleport(res.getOutsideFreeLoc(player.getLocation()));
}
return true;
} else if (args[0].equals("mirror")) {
if (args.length != 3) {
return false;
}
rmanager.mirrorPerms(player, args[1], args[2], resadmin);
return true;
} else if (args[0].equals("listall")) {
if (args.length == 1) {
rmanager.listAllResidences(player, 1);
} else if (args.length == 2) {
try {
rmanager.listAllResidences(player, page);
} catch (Exception ex) {
}
} else {
return false;
}
return true;
} else if (args[0].equals("version")) {
player.sendMessage("§7------------------------------------");
player.sendMessage("§cThis server running §6Residence§c version: §9" + this.getDescription().getVersion());
player.sendMessage("§aCreated by: §ebekvon");
player.sendMessage("§3For a command list, and help, see the wiki:");
player.sendMessage("§ahttp://residencebukkitmod.wikispaces.com/");
player.sendMessage("§bVisit the Residence thread at:");
player.sendMessage("§9http://forums.bukkit.org/");
player.sendMessage("§7------------------------------------");
return true;
}
else if(args[0].equals("material"))
{
if(args.length!=2)
return false;
try
{
player.sendMessage("§a"+language.getPhrase("GetMaterial","§6" + args[1] + "§a.§c" + Material.getMaterial(Integer.parseInt(args[1])).name()+"§a"));
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidMaterial"));
}
return true;
}
else if (args[0].equals("tpset")) {
ClaimedResidence res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setTpLoc(player, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args[0].equals("tp")) {
if (args.length != 2) {
return false;
}
ClaimedResidence res = rmanager.getByName(args[1]);
if (res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.tpToResidence(player, player, resadmin);
return true;
} else if (args[0].equals("lease")) {
if (args.length == 2 || args.length == 3) {
if (args[1].equals("renew")) {
if (args.length == 3) {
leasemanager.renewArea(args[2], player);
} else {
leasemanager.renewArea(rmanager.getNameByLoc(player.getLocation()), player);
}
return true;
} else if (args[1].equals("cost")) {
if (args.length == 3) {
ClaimedResidence res = Residence.getResidenceManager().getByName(args[2]);
if (res == null || leasemanager.leaseExpires(args[2])) {
int cost = leasemanager.getRenewCost(res);
player.sendMessage("§e"+language.getPhrase("LeaseRenewalCost","§c" + args[2] + "§e.§c" + cost + "§e"));
} else {
player.sendMessage("§c"+language.getPhrase("LeaseNotExpire"));
}
return true;
} else {
String area = rmanager.getNameByLoc(player.getLocation());
ClaimedResidence res = rmanager.getByName(area);
if (area == null || res == null) {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
return true;
}
if (leasemanager.leaseExpires(area)) {
int cost = leasemanager.getRenewCost(res);
player.sendMessage("§e"+language.getPhrase("LeaseRenewalCost","§c" + area + "§e.§c" + cost + "§e"));
} else {
player.sendMessage("§c"+language.getPhrase("LeaseNotExpire"));
}
return true;
}
}
} else if (args.length == 4) {
if (args[1].equals("set")) {
if (!resadmin) {
player.sendMessage("§c" + language.getPhrase("NoPermission"));
return true;
}
if (args[3].equals("infinite")) {
if (leasemanager.leaseExpires(args[2])) {
leasemanager.removeExpireTime(args[2]);
player.sendMessage("§a" + language.getPhrase("LeaseInfinite"));
} else {
player.sendMessage("§c" + language.getPhrase("LeaseNotExpire"));
}
return true;
} else {
int days;
try {
days = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c" + language.getPhrase("InvalidDays"));
return true;
}
leasemanager.setExpireTime(player, args[2], days);
return true;
}
}
}
return false;
} else if(args[0].equals("bank")) {
if(args.length!=3)
return false;
ClaimedResidence res = rmanager.getByName(plistener.getLastAreaName(pname));
if(res==null)
{
player.sendMessage("§c"+language.getPhrase("NotInResidence"));
return true;
}
int amount = 0;
try
{
amount = Integer.parseInt(args[2]);
}
catch (Exception ex)
{
player.sendMessage("§c"+language.getPhrase("InvalidAmount"));
return true;
}
if(args[1].equals("deposit"))
{
res.getBank().deposit(player, amount, resadmin);
}
else if(args[1].equals("withdraw"))
{
res.getBank().withdraw(player, amount, resadmin);
}
else
return false;
return true;
} else if (args[0].equals("market")) {
if(args.length == 1)
return false;
if(args[1].equals("list"))
{
if(!cmanager.enableEconomy())
{
player.sendMessage("§c"+language.getPhrase("MarketDisabled"));
return true;
}
player.sendMessage("§9---"+language.getPhrase("MarketList")+"---");
tmanager.printForSaleResidences(player);
if(cmanager.enabledRentSystem())
{
rentmanager.printRentableResidences(player);
}
return true;
}
else if (args[1].equals("autorenew")) {
if (!cmanager.enableEconomy()) {
player.sendMessage("§c"+language.getPhrase("MarketDisabled"));
return true;
}
if (args.length != 4) {
return false;
}
boolean value;
if (args[3].equalsIgnoreCase("true") || args[3].equalsIgnoreCase("t")) {
value = true;
} else if (args[3].equalsIgnoreCase("false") || args[3].equalsIgnoreCase("f")) {
value = false;
} else {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
if(rentmanager.isRented(args[2]) && rentmanager.getRentingPlayer(args[2]).equalsIgnoreCase(pname))
{
rentmanager.setRentedRepeatable(player, args[2], value, resadmin);
}
else if(rentmanager.isForRent(args[2]))
{
rentmanager.setRentRepeatable(player, args[2], value, resadmin);
}
else
{
player.sendMessage("§c"+language.getPhrase("RentReleaseInvalid","§e" + args[2] + "§c"));
}
return true;
}
else if(args[1].equals("rentable")) {
if (args.length < 5 || args.length > 6) {
return false;
}
if (!cmanager.enabledRentSystem()) {
player.sendMessage("§c" + language.getPhrase("RentDisabled"));
return true;
}
int days;
int cost;
try {
cost = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidCost"));
return true;
}
try {
days = Integer.parseInt(args[4]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidDays"));
return true;
}
boolean repeat = false;
if (args.length == 6) {
if (args[5].equalsIgnoreCase("t") || args[5].equalsIgnoreCase("true")) {
repeat = true;
} else if (!args[5].equalsIgnoreCase("f") && !args[5].equalsIgnoreCase("false")) {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
}
rentmanager.setForRent(player, args[2], cost, days, repeat, resadmin);
return true;
}
else if(args[1].equals("rent"))
{
if(args.length<3 || args.length>4)
return false;
boolean repeat = false;
if (args.length == 4) {
if (args[3].equalsIgnoreCase("t") || args[3].equalsIgnoreCase("true")) {
repeat = true;
} else if (!args[3].equalsIgnoreCase("f") && !args[3].equalsIgnoreCase("false")) {
player.sendMessage("§c"+language.getPhrase("InvalidBoolean"));
return true;
}
}
rentmanager.rent(player, args[2], repeat, resadmin);
return true;
}
else if(args[1].equals("release"))
{
if(args.length!=3)
return false;
if(rentmanager.isRented(args[2]))
{
rentmanager.removeFromForRent(player, args[2], resadmin);
}
else
{
rentmanager.unrent(player, args[2], resadmin);
}
return true;
}
else if(args.length == 2)
{
if (args[1].equals("info")) {
String areaname = rmanager.getNameByLoc(player.getLocation());
tmanager.viewSaleInfo(areaname, player);
if(cmanager.enabledRentSystem() && rentmanager.isForRent(areaname))
{
rentmanager.printRentInfo(player, areaname);
}
return true;
}
}
else if(args.length == 3) {
if (args[1].equals("buy")) {
tmanager.buyPlot(args[2], player, resadmin);
return true;
} else if (args[1].equals("info")) {
tmanager.viewSaleInfo(args[2], player);
if(cmanager.enabledRentSystem() && rentmanager.isForRent(args[2]))
{
rentmanager.printRentInfo(player, args[2]);
}
return true;
} else if (args[1].equals("unsell")) {
tmanager.removeFromSale(player, args[2], resadmin);
return true;
}
}
else if(args.length == 4) {
if (args[1].equals("sell")) {
int amount;
try {
amount = Integer.parseInt(args[3]);
} catch (Exception ex) {
player.sendMessage("§c"+language.getPhrase("InvalidAmount"));
return true;
}
tmanager.putForSale(args[2], player, amount, resadmin);
return true;
}
}
return false;
} else if (args[0].equals("message")) {
ClaimedResidence res = null;
int start = 0;
boolean enter = false;
if(args.length<2)
return false;
if (args[1].equals("enter")) {
enter = true;
res = rmanager.getByLoc(player.getLocation());
start = 2;
} else if (args[1].equals("leave")) {
res = rmanager.getByLoc(player.getLocation());
start = 2;
} else if (args.length>2 && args[2].equals("enter")) {
enter = true;
res = rmanager.getByName(args[1]);
start = 3;
} else if (args.length>2 && args[2].equals("leave")) {
res = rmanager.getByName(args[1]);
start = 3;
} else if (args.length>2 && args[1].equals("remove")) {
if (args[2].equals("enter")) {
res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setEnterLeaveMessage(player, null, true, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
} else if (args[2].equals("leave")) {
res = rmanager.getByLoc(player.getLocation());
if (res != null) {
res.setEnterLeaveMessage(player, null, false, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
} else if (args.length>2 && args[2].equals("remove")) {
res = rmanager.getByName(args[1]);
if (args.length != 4) {
return false;
}
if (args[3].equals("enter")) {
if (res != null) {
res.setEnterLeaveMessage(player, null, true, resadmin);
}
return true;
} else if (args[3].equals("leave")) {
if (res != null) {
res.setEnterLeaveMessage(player, null, false, resadmin);
}
return true;
}
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
} else {
player.sendMessage("§c"+language.getPhrase("InvalidMessageType"));
return true;
}
if(start == 0)
return false;
String message = "";
for (int i = start; i < args.length; i++) {
message = message + args[i] + " ";
}
if (res != null) {
res.setEnterLeaveMessage(player, message, enter, resadmin);
} else {
player.sendMessage("§c"+language.getPhrase("InvalidArea"));
}
return true;
}
else if(args[0].equals("give"))
{
rmanager.giveResidence(player, args[2], args[1], resadmin);
return true;
}
else if (args[0].equals("setowner")) {
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().setOwner(args[2], true);
player.sendMessage("§a"+language.getPhrase("ResidenceOwnerChange","§e " + args[1] + " §a.§e"+args[2]+"§a"));
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
else if(args[0].equals("server"))
{
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
if(args.length==2)
{
ClaimedResidence res = rmanager.getByName(args[1]);
if(res == null)
{
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
return true;
}
res.getPermissions().setOwner("Server Land", false);
player.sendMessage("§a"+language.getPhrase("ResidenceOwnerChange","§e " + args[1] + " §a.§eServer Land§a"));
}
else
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
else if(args[0].equals("clearflags"))
{
if(!resadmin)
{
player.sendMessage("§c"+language.getPhrase("NoPermission"));
return true;
}
ClaimedResidence area = rmanager.getByName(args[1]);
if (area != null) {
area.getPermissions().clearFlags();
player.sendMessage("§a"+language.getPhrase("FlagsCleared"));
} else {
player.sendMessage("§c"+language.getPhrase("InvalidResidence"));
}
return true;
}
else if(args[0].equals("tool"))
{
player.sendMessage("§e"+language.getPhrase("SelectionTool")+":§a" + Material.getMaterial(cmanager.getSelectionTooldID()));
player.sendMessage("§e"+language.getPhrase("InfoTool")+": §a" + Material.getMaterial(cmanager.getInfoToolID()));
return true;
}
}
return false;
}
return super.onCommand(sender, command, label, args);
}
|
diff --git a/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CheckoutProjectContinuumAction.java b/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CheckoutProjectContinuumAction.java
index 5a43ef0fd..172d9698b 100644
--- a/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CheckoutProjectContinuumAction.java
+++ b/continuum-core/src/main/java/org/apache/maven/continuum/core/action/CheckoutProjectContinuumAction.java
@@ -1,173 +1,174 @@
package org.apache.maven.continuum.core.action;
/*
* 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.maven.continuum.Continuum;
import org.apache.maven.continuum.execution.ContinuumBuildExecutorConstants;
import org.apache.maven.continuum.model.project.BuildDefinition;
import org.apache.maven.continuum.model.project.Project;
import org.apache.maven.continuum.model.scm.ScmResult;
import org.apache.maven.continuum.notification.ContinuumNotificationDispatcher;
import org.apache.maven.continuum.project.ContinuumProjectState;
import org.apache.maven.continuum.scm.ContinuumScm;
import org.apache.maven.continuum.scm.ContinuumScmException;
import org.apache.maven.continuum.store.ContinuumStore;
import org.apache.maven.continuum.utils.ContinuumUtils;
import org.apache.maven.scm.manager.NoSuchScmProviderException;
import org.codehaus.plexus.util.StringUtils;
import java.io.File;
import java.util.Map;
/**
* @author <a href="mailto:[email protected]">Trygve Laugstøl</a>
* @version $Id$
* @plexus.component role="org.codehaus.plexus.action.Action"
* role-hint="checkout-project"
*/
public class CheckoutProjectContinuumAction
extends AbstractContinuumAction
{
/**
* @plexus.requirement
*/
private ContinuumNotificationDispatcher notifier;
/**
* @plexus.requirement
*/
private ContinuumScm scm;
/**
* @plexus.requirement role-hint="jdo"
*/
private ContinuumStore store;
/**
* @plexus.requirement
*/
private Continuum continuum;
public void execute( Map context )
throws Exception
{
Project project = getProject( context );
int oldState = project.getState();
BuildDefinition buildDefinition = getBuildDefinition( context );
project.setState( ContinuumProjectState.CHECKING_OUT );
store.updateProject( project );
File workingDirectory = getWorkingDirectory( context );
// ----------------------------------------------------------------------
// Check out the project
// ----------------------------------------------------------------------
ScmResult result;
try
{
result = scm.checkOut( project, workingDirectory, context );
//CONTINUUM-1394
result.setChanges( null );
}
catch ( ContinuumScmException e )
{
// TODO: Dissect the scm exception to be able to give better feedback
Throwable cause = e.getCause();
if ( cause instanceof NoSuchScmProviderException )
{
result = new ScmResult();
result.setSuccess( false );
result.setProviderMessage( cause.getMessage() );
}
else if ( e.getResult() != null )
{
result = e.getResult();
}
else
{
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( e ) );
}
}
catch ( Throwable t )
{
// TODO: do we want this here, or should it be to the logs?
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( t ) );
}
finally
{
if ( oldState == ContinuumProjectState.NEW )
{
String relativePath = (String) getObject( context, KEY_PROJECT_RELATIVE_PATH, "" );
if ( StringUtils.isNotEmpty( relativePath ) )
{
//CONTINUUM-1218 : updating only the default build definition only for new projects
BuildDefinition bd = continuum.getDefaultBuildDefinition( project.getId() );
String buildFile = "";
- if (ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
+ if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "pom.xml";
bd.setType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR );
}
- else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
+ else
+ if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "project.xml";
bd.setType( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR );
}
else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "build.xml";
bd.setType( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR );
}
else
{
bd.setType( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR );
}
- bd.setBuildFile( relativePath + "/" + "buildFile" );
+ bd.setBuildFile( relativePath + "/" + buildFile );
store.storeBuildDefinition( bd );
}
}
project.setState( ContinuumProjectState.CHECKEDOUT );
store.updateProject( project );
notifier.checkoutComplete( project, buildDefinition );
}
context.put( KEY_CHECKOUT_SCM_RESULT, result );
}
}
| false | true | public void execute( Map context )
throws Exception
{
Project project = getProject( context );
int oldState = project.getState();
BuildDefinition buildDefinition = getBuildDefinition( context );
project.setState( ContinuumProjectState.CHECKING_OUT );
store.updateProject( project );
File workingDirectory = getWorkingDirectory( context );
// ----------------------------------------------------------------------
// Check out the project
// ----------------------------------------------------------------------
ScmResult result;
try
{
result = scm.checkOut( project, workingDirectory, context );
//CONTINUUM-1394
result.setChanges( null );
}
catch ( ContinuumScmException e )
{
// TODO: Dissect the scm exception to be able to give better feedback
Throwable cause = e.getCause();
if ( cause instanceof NoSuchScmProviderException )
{
result = new ScmResult();
result.setSuccess( false );
result.setProviderMessage( cause.getMessage() );
}
else if ( e.getResult() != null )
{
result = e.getResult();
}
else
{
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( e ) );
}
}
catch ( Throwable t )
{
// TODO: do we want this here, or should it be to the logs?
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( t ) );
}
finally
{
if ( oldState == ContinuumProjectState.NEW )
{
String relativePath = (String) getObject( context, KEY_PROJECT_RELATIVE_PATH, "" );
if ( StringUtils.isNotEmpty( relativePath ) )
{
//CONTINUUM-1218 : updating only the default build definition only for new projects
BuildDefinition bd = continuum.getDefaultBuildDefinition( project.getId() );
String buildFile = "";
if (ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "pom.xml";
bd.setType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR );
}
else if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "project.xml";
bd.setType( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR );
}
else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "build.xml";
bd.setType( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR );
}
else
{
bd.setType( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR );
}
bd.setBuildFile( relativePath + "/" + "buildFile" );
store.storeBuildDefinition( bd );
}
}
project.setState( ContinuumProjectState.CHECKEDOUT );
store.updateProject( project );
notifier.checkoutComplete( project, buildDefinition );
}
context.put( KEY_CHECKOUT_SCM_RESULT, result );
}
| public void execute( Map context )
throws Exception
{
Project project = getProject( context );
int oldState = project.getState();
BuildDefinition buildDefinition = getBuildDefinition( context );
project.setState( ContinuumProjectState.CHECKING_OUT );
store.updateProject( project );
File workingDirectory = getWorkingDirectory( context );
// ----------------------------------------------------------------------
// Check out the project
// ----------------------------------------------------------------------
ScmResult result;
try
{
result = scm.checkOut( project, workingDirectory, context );
//CONTINUUM-1394
result.setChanges( null );
}
catch ( ContinuumScmException e )
{
// TODO: Dissect the scm exception to be able to give better feedback
Throwable cause = e.getCause();
if ( cause instanceof NoSuchScmProviderException )
{
result = new ScmResult();
result.setSuccess( false );
result.setProviderMessage( cause.getMessage() );
}
else if ( e.getResult() != null )
{
result = e.getResult();
}
else
{
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( e ) );
}
}
catch ( Throwable t )
{
// TODO: do we want this here, or should it be to the logs?
result = new ScmResult();
result.setSuccess( false );
result.setException( ContinuumUtils.throwableMessagesToString( t ) );
}
finally
{
if ( oldState == ContinuumProjectState.NEW )
{
String relativePath = (String) getObject( context, KEY_PROJECT_RELATIVE_PATH, "" );
if ( StringUtils.isNotEmpty( relativePath ) )
{
//CONTINUUM-1218 : updating only the default build definition only for new projects
BuildDefinition bd = continuum.getDefaultBuildDefinition( project.getId() );
String buildFile = "";
if ( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "pom.xml";
bd.setType( ContinuumBuildExecutorConstants.MAVEN_TWO_BUILD_EXECUTOR );
}
else
if ( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "project.xml";
bd.setType( ContinuumBuildExecutorConstants.MAVEN_ONE_BUILD_EXECUTOR );
}
else if ( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR.equals( project.getExecutorId() ) )
{
buildFile = "build.xml";
bd.setType( ContinuumBuildExecutorConstants.ANT_BUILD_EXECUTOR );
}
else
{
bd.setType( ContinuumBuildExecutorConstants.SHELL_BUILD_EXECUTOR );
}
bd.setBuildFile( relativePath + "/" + buildFile );
store.storeBuildDefinition( bd );
}
}
project.setState( ContinuumProjectState.CHECKEDOUT );
store.updateProject( project );
notifier.checkoutComplete( project, buildDefinition );
}
context.put( KEY_CHECKOUT_SCM_RESULT, result );
}
|
diff --git a/src/org/apache/xerces/validators/schema/identity/XPathMatcher.java b/src/org/apache/xerces/validators/schema/identity/XPathMatcher.java
index 690d266a6..5634c6361 100644
--- a/src/org/apache/xerces/validators/schema/identity/XPathMatcher.java
+++ b/src/org/apache/xerces/validators/schema/identity/XPathMatcher.java
@@ -1,655 +1,655 @@
/*
* The Apache Software License, Version 1.1
*
*
* Copyright (c) 2001 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.schema.identity;
import org.apache.xerces.framework.XMLAttrList;
import org.apache.xerces.utils.QName;
import org.apache.xerces.utils.NamespacesScope;
import org.apache.xerces.utils.StringPool;
import org.xml.sax.SAXException;
import org.xml.sax.SAXNotRecognizedException;
import org.xml.sax.SAXNotSupportedException;
/**
* XPath matcher.
*
* @author Andy Clark, IBM
*
* @version $Id$
*/
public class XPathMatcher {
//
// Constants
//
// debugging
/** Compile to true to debug everything. */
private static final boolean DEBUG_ALL = false;
/** Compile to true to debug method callbacks. */
private static final boolean DEBUG_METHODS = DEBUG_ALL || false;
/** Compile to true to debug important method callbacks. */
private static final boolean DEBUG_METHODS2 = DEBUG_ALL || DEBUG_METHODS ||
false;
/** Compile to true to debug match. */
private static final boolean DEBUG_MATCH = DEBUG_ALL || false;
/** Don't touch this value unless you add more debug constants. */
private static final boolean DEBUG_ANY = DEBUG_METHODS ||
DEBUG_METHODS2 ||
DEBUG_MATCH;
//
// Data
//
/** XPath location path. */
private XPath.LocationPath fLocationPath;
/** Application preference to buffer content or not. */
private boolean fShouldBufferContent;
/** True if should buffer character content <em>at this time</em>. */
private boolean fBufferContent;
/** Buffer to hold match text. */
private StringBuffer fMatchedBuffer = new StringBuffer();
/** True if XPath has been matched. */
private boolean fMatched;
/** The matching string. */
private String fMatchedString;
/** Integer stack of step indexes. */
private IntegerStack fStepIndexes = new IntegerStack();
/** Current step. */
private int fCurrentStep;
/**
* No match depth. The value of this field will be zero while
* matching is successful.
*/
private int fNoMatchDepth;
// Xerces 1.x framework
/** String pool. */
protected StringPool fStringPool;
/** Namespace scope. */
protected NamespacesScope fNamespacesScope;
//
// Constructors
//
/**
* Constructs an XPath matcher that implements a document fragment
* handler.
*
* @param xpath The xpath.
* @param symbols The symbol table.
*/
public XPathMatcher(XPath xpath) {
this(xpath, false);
} // <init>(Stringm,SymbolTable,NamespaceContext)
/**
* Constructs an XPath matcher that implements a document fragment
* handler.
*
* @param xpath The xpath.
* @param symbols The symbol table.
* @param shouldBufferContent True if the matcher should buffer the
* matched content.
*/
public XPathMatcher(XPath xpath, boolean shouldBufferContent) {
fLocationPath = xpath.getLocationPath();
fShouldBufferContent = shouldBufferContent;
if (DEBUG_METHODS) {
System.out.println("XPATH["+toString()+"]: <init>()");
}
} // <init>(String,SymbolTable,NamespaceContext,boolean)
//
// Public methods
//
/** Returns true if XPath has been matched. */
public boolean isMatched() {
return fMatched;
} // isMatched():boolean
/** Returns the matched string. */
public String getMatchedString() {
return fMatchedString;
} // getMatchedString():String
//
// Protected methods
//
/**
* This method is called when the XPath handler matches the
* XPath expression. Subclasses can override this method to
* provide default handling upon a match.
*/
protected void matched(String content) throws SAXException {
if (DEBUG_METHODS || DEBUG_METHODS2) {
System.out.println("XPATH["+toString()+"]: matched \""+content+'"');
}
} // matched(String content)
//
// XMLDocumentFragmentHandler methods
//
/**
* The start of the document fragment.
*
* @param namespaceContext The namespace context in effect at the
* start of this document fragment. This
* object only represents the current context.
* Implementors of this class are responsible
* for copying the namespace bindings from the
* the current context (and its parent contexts)
* if that information is important.
*
* @throws SAXException Thrown by handler to signal an error.
*/
public void startDocumentFragment(StringPool stringPool,
NamespacesScope namespacesScope)
throws Exception {
if (DEBUG_METHODS) {
System.out.println("XPATH["+toString()+"]: startDocumentFragment("+
"stringPool="+stringPool+','+
"namespacesScope="+namespacesScope+
")");
}
// reset state
clear();
fMatchedBuffer.setLength(0);
fStepIndexes.clear();
fCurrentStep = 0;
fNoMatchDepth = 0;
// keep values
fStringPool = stringPool;
fNamespacesScope = namespacesScope;
if (namespacesScope == null) {
NamespacesScope.NamespacesHandler handler =
new NamespacesScope.NamespacesHandler() {
public void startNamespaceDeclScope(int prefix, int uri) throws Exception {
}
public void endNamespaceDeclScope(int prefix) throws Exception {
}
};
fNamespacesScope = new NamespacesScope(handler);
}
} // startDocumentFragment(StringPool,NamespacesScope)
/**
* The start of an element. If the document specifies the start element
* by using an empty tag, then the startElement method will immediately
* be followed by the endElement method, with no intervening methods.
*
* @param element The name of the element.
* @param attributes The element attributes.
*
* @throws SAXException Thrown by handler to signal an error.
*/
public void startElement(QName element, XMLAttrList attributes, int handle)
throws Exception {
if (DEBUG_METHODS || DEBUG_METHODS2) {
System.out.println("XPATH["+toString()+"]: startElement("+
"element={"+
"prefix="+fStringPool.toString(element.prefix)+','+
"localpart="+fStringPool.toString(element.localpart)+','+
"rawname="+fStringPool.toString(element.rawname)+','+
"uri="+fStringPool.toString(element.uri)+
"},"+
"attributes="+attributes+
")");
}
// return, if not matching
if (fNoMatchDepth > 0) {
fNoMatchDepth++;
return;
}
// check match
int startStepIndex = fCurrentStep;
while (fCurrentStep < fLocationPath.steps.length) {
XPath.Step step = fLocationPath.steps[fCurrentStep++];
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"attempting match at step["+(fCurrentStep - 1)+"]: \""+step+'"');
}
XPath.Axis axis = step.axis;
switch (axis.type) {
- case axis.SELF: {
+ case XPath.Axis.SELF: {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"axis: SELF");
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
fMatched = true;
fBufferContent = true && fShouldBufferContent;
break;
}
continue;
}
- case axis.CHILD: {
+ case XPath.Axis.CHILD: {
int elementStep = fCurrentStep + 1;
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"axis: CHILD");
}
// check element match
XPath.NodeTest nodeTest = step.nodeTest;
if (nodeTest.type == nodeTest.QNAME) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"nodeTest: QNAME");
}
boolean matched = true;
QName name = nodeTest.name;
if (name.uri == -1) {
if (element.rawname != name.rawname) {
//System.out.println(">>> fStringPool: "+fStringPool);
//System.out.println(">>> element.rawname: "+fStringPool.toString(element.rawname));
//System.out.println(">>> name.rawname: "+fStringPool.toString(name.rawname));
matched = false;
}
}
else {
if (element.uri != name.uri ||
element.localpart != name.localpart) {
matched = false;
}
}
if (!matched) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP *NOT* MATCHED");
}
fNoMatchDepth++;
return;
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
fMatched = true;
fBufferContent = true && fShouldBufferContent;
}
}
/***
// REVISIT: [Q] Is self:: axis needed? -Ac
else if (axis.type == XPath.Axis.SELF) {
// let pass
}
/***/
else {
throw new SAXException("axis \""+axis+"\" not allowed");
}
// check for attribute match
if (fCurrentStep < fLocationPath.steps.length) {
step = fLocationPath.steps[fCurrentStep];
axis = step.axis;
if (axis.type == axis.ATTRIBUTE) {
fCurrentStep++;
nodeTest = step.nodeTest;
if (nodeTest.type == nodeTest.QNAME) {
boolean matched = true;
QName name = nodeTest.name;
if (name.uri == -1) {
fMatchedString = attributes.getValue(name.rawname);
if (fMatchedString == null) {
matched = false;
}
}
else {
int aindex = attributes.getFirstAttr(handle);
while (aindex != -1) {
int auri = attributes.getAttrURI(aindex);
int alocalpart = attributes.getAttrLocalpart(aindex);
if (auri != -1 && alocalpart != -1 &&
auri == name.uri && alocalpart == name.localpart) {
fMatchedString = fStringPool.toString(attributes.getAttValue(aindex));
break;
}
aindex = attributes.getNextAttr(aindex);
}
if (fMatchedString == null) {
matched = false;
}
}
if (!matched) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"ATTRIBUTE *NOT* MATCHED");
}
fNoMatchDepth++;
return;
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
}
fBufferContent = false;
fCurrentStep++;
fMatched = fMatchedString != null;
matched(fMatchedString);
}
else {
throw new SAXException("node test \""+nodeTest+"\" not allowed");
}
}
}
break;
}
default: {
throw new SAXException("step \""+step+"\" not allowed");
}
}
break;
}
// push context
fNamespacesScope.increaseDepth();
fStepIndexes.push(startStepIndex);
} // startElement(QName,XMLAttrList,int)
/** Character content. */
public void characters(char[] ch, int offset, int length)
throws Exception {
if (DEBUG_METHODS) {
System.out.println("XPATH["+toString()+"]: characters("+
"text="+new String(ch, offset, length)+
")");
}
// collect match content
if (fBufferContent && fNoMatchDepth == 0) {
if (!DEBUG_METHODS && DEBUG_METHODS2) {
System.out.println("XPATH["+toString()+"]: characters("+
"text="+new String(ch, offset, length)+
")");
}
fMatchedBuffer.append(ch, offset, length);
}
} // characters(char[],int,int)
/**
* The end of an element.
*
* @param element The name of the element.
*
* @throws SAXException Thrown by handler to signal an error.
*/
public void endElement(QName element) throws Exception {
if (DEBUG_METHODS || DEBUG_METHODS2) {
System.out.println("XPATH["+toString()+"]: endElement("+
"element={"+
"prefix="+fStringPool.toString(element.prefix)+','+
"localpart="+fStringPool.toString(element.localpart)+','+
"rawname="+fStringPool.toString(element.rawname)+','+
"uri="+fStringPool.toString(element.uri)+
"})");
}
// return, if not matching
if (fNoMatchDepth > 0) {
fNoMatchDepth--;
return;
}
// signal match, if appropriate
if (fBufferContent) {
fBufferContent = false;
fMatchedString = fMatchedBuffer.toString();
matched(fMatchedString);
}
// go back a step
fCurrentStep = fStepIndexes.pop();
clear();
} // endElement(QName)
/**
* The end of the document fragment.
*
* @throws SAXException Thrown by handler to signal an error.
*/
public void endDocumentFragment() throws Exception {
if (DEBUG_METHODS) {
System.out.println("XPATH["+toString()+"]: endDocumentFragment()");
}
clear();
} // endDocumentFragment()
//
// Object methods
//
/** Returns a string representation of this object. */
public String toString() {
return fLocationPath.toString();
} // toString():String
//
// Private methods
//
/** Clears the match values. */
private void clear() {
fBufferContent = false;
fMatched = false;
fMatchedString = null;
} // clear()
//
// Classes
//
/**
* A simple integer stack.
*
* @author Andy Clark, IBM
*/
protected final static class IntegerStack {
//
// Data
//
/** Stack top. */
private int fTop = -1;
/** Stack data. */
private int[] fData = new int[4];
//
// Constructors
//
/** Default constructor. */
public IntegerStack() {
} // <init>()
//
// Public methods
//
/** Clears the stack. */
public void clear() {
fTop = -1;
} // clear()
/** Pushes an integer onto the stack. */
public void push(int value) {
ensureCapacity(++fTop);
fData[fTop] = value;
} // push(int)
/** Pops an integer off of the stack. */
public int pop() {
return fData[fTop--];
} // pop():int
//
// Private methods
//
/** Ensures data structure can hold data. */
private void ensureCapacity(int size) {
if (size >= fData.length) {
int[] array = new int[fData.length * 2];
System.arraycopy(fData, 0, array, 0, fData.length);
fData = array;
}
} // ensureCapacity(int)
} // class IntegerStack
//
// MAIN
//
// NOTE: The main of this class is here for debugging purposes.
// However, javac (JDK 1.1.8) has an internal compiler
// error when compiling. Jikes has no problem, though.
//
// If you want to use this main, use Jikes to compile but
// *never* check in this code to CVS without commenting it
// out. -Ac
/** Main program. */
/***
public static void main(String[] argv) throws Exception {
if (DEBUG_ANY) {
for (int i = 0; i < argv.length; i++) {
final String expr = argv[i];
final StringPool symbols = new StringPool();
final XPath xpath = new XPath(expr, symbols, null);
final XPathMatcher matcher = new XPathMatcher(xpath, true);
org.apache.xerces.parsers.SAXParser parser =
new org.apache.xerces.parsers.SAXParser(symbols) {
public void startDocument() throws Exception {
matcher.startDocumentFragment(matcher.fStringPool, null);
}
public void startElement(QName element, XMLAttrList attributes, int handle) throws Exception {
matcher.startElement(element, attributes, handle);
}
public void characters(char[] ch, int offset, int length) throws Exception {
matcher.characters(ch, offset, length);
}
public void endElement(QName element) throws Exception {
matcher.endElement(element);
}
public void endDocument() throws Exception {
matcher.endDocumentFragment();
}
};
System.out.println("#### argv["+i+"]: \""+expr+"\" -> \""+xpath.toString()+'"');
final String uri = argv[++i];
System.out.println("#### argv["+i+"]: "+uri);
parser.parse(uri);
}
}
} // main(String[])
/***/
} // class XPathMatcher
| false | true | public void startElement(QName element, XMLAttrList attributes, int handle)
throws Exception {
if (DEBUG_METHODS || DEBUG_METHODS2) {
System.out.println("XPATH["+toString()+"]: startElement("+
"element={"+
"prefix="+fStringPool.toString(element.prefix)+','+
"localpart="+fStringPool.toString(element.localpart)+','+
"rawname="+fStringPool.toString(element.rawname)+','+
"uri="+fStringPool.toString(element.uri)+
"},"+
"attributes="+attributes+
")");
}
// return, if not matching
if (fNoMatchDepth > 0) {
fNoMatchDepth++;
return;
}
// check match
int startStepIndex = fCurrentStep;
while (fCurrentStep < fLocationPath.steps.length) {
XPath.Step step = fLocationPath.steps[fCurrentStep++];
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"attempting match at step["+(fCurrentStep - 1)+"]: \""+step+'"');
}
XPath.Axis axis = step.axis;
switch (axis.type) {
case axis.SELF: {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"axis: SELF");
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
fMatched = true;
fBufferContent = true && fShouldBufferContent;
break;
}
continue;
}
case axis.CHILD: {
int elementStep = fCurrentStep + 1;
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"axis: CHILD");
}
// check element match
XPath.NodeTest nodeTest = step.nodeTest;
if (nodeTest.type == nodeTest.QNAME) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"nodeTest: QNAME");
}
boolean matched = true;
QName name = nodeTest.name;
if (name.uri == -1) {
if (element.rawname != name.rawname) {
//System.out.println(">>> fStringPool: "+fStringPool);
//System.out.println(">>> element.rawname: "+fStringPool.toString(element.rawname));
//System.out.println(">>> name.rawname: "+fStringPool.toString(name.rawname));
matched = false;
}
}
else {
if (element.uri != name.uri ||
element.localpart != name.localpart) {
matched = false;
}
}
if (!matched) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP *NOT* MATCHED");
}
fNoMatchDepth++;
return;
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
fMatched = true;
fBufferContent = true && fShouldBufferContent;
}
}
/***
// REVISIT: [Q] Is self:: axis needed? -Ac
else if (axis.type == XPath.Axis.SELF) {
// let pass
}
/***/
else {
throw new SAXException("axis \""+axis+"\" not allowed");
}
// check for attribute match
if (fCurrentStep < fLocationPath.steps.length) {
step = fLocationPath.steps[fCurrentStep];
axis = step.axis;
if (axis.type == axis.ATTRIBUTE) {
fCurrentStep++;
nodeTest = step.nodeTest;
if (nodeTest.type == nodeTest.QNAME) {
boolean matched = true;
QName name = nodeTest.name;
if (name.uri == -1) {
fMatchedString = attributes.getValue(name.rawname);
if (fMatchedString == null) {
matched = false;
}
}
else {
int aindex = attributes.getFirstAttr(handle);
while (aindex != -1) {
int auri = attributes.getAttrURI(aindex);
int alocalpart = attributes.getAttrLocalpart(aindex);
if (auri != -1 && alocalpart != -1 &&
auri == name.uri && alocalpart == name.localpart) {
fMatchedString = fStringPool.toString(attributes.getAttValue(aindex));
break;
}
aindex = attributes.getNextAttr(aindex);
}
if (fMatchedString == null) {
matched = false;
}
}
if (!matched) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"ATTRIBUTE *NOT* MATCHED");
}
fNoMatchDepth++;
return;
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
}
fBufferContent = false;
fCurrentStep++;
fMatched = fMatchedString != null;
matched(fMatchedString);
}
else {
throw new SAXException("node test \""+nodeTest+"\" not allowed");
}
}
}
break;
}
default: {
throw new SAXException("step \""+step+"\" not allowed");
}
}
break;
}
// push context
fNamespacesScope.increaseDepth();
fStepIndexes.push(startStepIndex);
} // startElement(QName,XMLAttrList,int)
| public void startElement(QName element, XMLAttrList attributes, int handle)
throws Exception {
if (DEBUG_METHODS || DEBUG_METHODS2) {
System.out.println("XPATH["+toString()+"]: startElement("+
"element={"+
"prefix="+fStringPool.toString(element.prefix)+','+
"localpart="+fStringPool.toString(element.localpart)+','+
"rawname="+fStringPool.toString(element.rawname)+','+
"uri="+fStringPool.toString(element.uri)+
"},"+
"attributes="+attributes+
")");
}
// return, if not matching
if (fNoMatchDepth > 0) {
fNoMatchDepth++;
return;
}
// check match
int startStepIndex = fCurrentStep;
while (fCurrentStep < fLocationPath.steps.length) {
XPath.Step step = fLocationPath.steps[fCurrentStep++];
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"attempting match at step["+(fCurrentStep - 1)+"]: \""+step+'"');
}
XPath.Axis axis = step.axis;
switch (axis.type) {
case XPath.Axis.SELF: {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"axis: SELF");
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
fMatched = true;
fBufferContent = true && fShouldBufferContent;
break;
}
continue;
}
case XPath.Axis.CHILD: {
int elementStep = fCurrentStep + 1;
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"axis: CHILD");
}
// check element match
XPath.NodeTest nodeTest = step.nodeTest;
if (nodeTest.type == nodeTest.QNAME) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"nodeTest: QNAME");
}
boolean matched = true;
QName name = nodeTest.name;
if (name.uri == -1) {
if (element.rawname != name.rawname) {
//System.out.println(">>> fStringPool: "+fStringPool);
//System.out.println(">>> element.rawname: "+fStringPool.toString(element.rawname));
//System.out.println(">>> name.rawname: "+fStringPool.toString(name.rawname));
matched = false;
}
}
else {
if (element.uri != name.uri ||
element.localpart != name.localpart) {
matched = false;
}
}
if (!matched) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP *NOT* MATCHED");
}
fNoMatchDepth++;
return;
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
fMatched = true;
fBufferContent = true && fShouldBufferContent;
}
}
/***
// REVISIT: [Q] Is self:: axis needed? -Ac
else if (axis.type == XPath.Axis.SELF) {
// let pass
}
/***/
else {
throw new SAXException("axis \""+axis+"\" not allowed");
}
// check for attribute match
if (fCurrentStep < fLocationPath.steps.length) {
step = fLocationPath.steps[fCurrentStep];
axis = step.axis;
if (axis.type == axis.ATTRIBUTE) {
fCurrentStep++;
nodeTest = step.nodeTest;
if (nodeTest.type == nodeTest.QNAME) {
boolean matched = true;
QName name = nodeTest.name;
if (name.uri == -1) {
fMatchedString = attributes.getValue(name.rawname);
if (fMatchedString == null) {
matched = false;
}
}
else {
int aindex = attributes.getFirstAttr(handle);
while (aindex != -1) {
int auri = attributes.getAttrURI(aindex);
int alocalpart = attributes.getAttrLocalpart(aindex);
if (auri != -1 && alocalpart != -1 &&
auri == name.uri && alocalpart == name.localpart) {
fMatchedString = fStringPool.toString(attributes.getAttValue(aindex));
break;
}
aindex = attributes.getNextAttr(aindex);
}
if (fMatchedString == null) {
matched = false;
}
}
if (!matched) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"ATTRIBUTE *NOT* MATCHED");
}
fNoMatchDepth++;
return;
}
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"STEP MATCHED");
}
if (fCurrentStep == fLocationPath.steps.length) {
if (DEBUG_MATCH) {
System.out.println("XPATH["+toString()+"]: "+
"PATH MATCHED");
}
}
fBufferContent = false;
fCurrentStep++;
fMatched = fMatchedString != null;
matched(fMatchedString);
}
else {
throw new SAXException("node test \""+nodeTest+"\" not allowed");
}
}
}
break;
}
default: {
throw new SAXException("step \""+step+"\" not allowed");
}
}
break;
}
// push context
fNamespacesScope.increaseDepth();
fStepIndexes.push(startStepIndex);
} // startElement(QName,XMLAttrList,int)
|
diff --git a/hk2/class-model/src/main/java/org/glassfish/hk2/classmodel/reflect/impl/TypesImpl.java b/hk2/class-model/src/main/java/org/glassfish/hk2/classmodel/reflect/impl/TypesImpl.java
index 0a8962fba..473e2ca82 100755
--- a/hk2/class-model/src/main/java/org/glassfish/hk2/classmodel/reflect/impl/TypesImpl.java
+++ b/hk2/class-model/src/main/java/org/glassfish/hk2/classmodel/reflect/impl/TypesImpl.java
@@ -1,117 +1,119 @@
/*
* DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS HEADER.
*
* Copyright 2010 Sun Microsystems, Inc. All rights reserved.
*
* The contents of this file are subject to the terms of either the GNU
* General Public License Version 2 only ("GPL") or the Common Development
* and Distribution License("CDDL") (collectively, the "License"). You
* may not use this file except in compliance with the License. You can obtain
* a copy of the License at https://glassfish.dev.java.net/public/CDDL+GPL.html
* or glassfish/bootstrap/legal/LICENSE.txt. See the License for the specific
* language governing permissions and limitations under the License.
*
* When distributing the software, include this License Header Notice in each
* file and include the License file at glassfish/bootstrap/legal/LICENSE.txt.
* Sun designates this particular file as subject to the "Classpath" exception
* as provided by Sun in the GPL Version 2 section of the License file that
* accompanied this code. If applicable, add the following below the License
* Header, with the fields enclosed by brackets [] replaced by your own
* identifying information: "Portions Copyrighted [year]
* [name of copyright owner]"
*
* Contributor(s):
*
* If you wish your version of this file to be governed by only the CDDL or
* only the GPL Version 2, indicate your decision by adding "[Contributor]
* elects to include this software in this distribution under the [CDDL or GPL
* Version 2] license." If you don't indicate a single choice of license, a
* recipient has the option to distribute your version of this file under
* either the CDDL, the GPL Version 2 or to extend the choice of license to
* its licensees as provided above. However, if you add GPL Version 2 code
* and therefore, elected the GPL Version 2 license, then the option applies
* only if the new code is made subject to such option by the copyright
* holder.
*/
package org.glassfish.hk2.classmodel.reflect.impl;
import org.glassfish.hk2.classmodel.reflect.*;
import org.objectweb.asm.Opcodes;
import java.net.URI;
/**
* Results of a parsing activity, all java resources are inventoried in three
* main categories : classes, interfaces and annotations with cross references
*
* @author Jerome Dochez
*/
public class TypesImpl implements TypeBuilder {
final URI definingURI;
final TypesCtr types;
public TypesImpl(TypesCtr types, URI definingURI) {
this.definingURI = definingURI;
this.types = types;
}
public Class<? extends Type> getType(int access) {
if ((access & Opcodes.ACC_ANNOTATION)==Opcodes.ACC_ANNOTATION) {
return AnnotationType.class;
} else
if ((access & Opcodes.ACC_INTERFACE)==Opcodes.ACC_INTERFACE) {
return InterfaceModel.class;
} else {
return ClassModel.class;
}
}
- public synchronized TypeImpl getType(int access, String name, TypeProxy parent) {
+ public TypeImpl getType(int access, String name, TypeProxy parent) {
Class<? extends Type> requestedType = getType(access);
TypeProxy<Type> typeProxy = types.getHolder(name, requestedType);
- final Type type = typeProxy.get();
- if (null == type) {
- if ((access & Opcodes.ACC_ANNOTATION)==Opcodes.ACC_ANNOTATION) {
- return new AnnotationTypeImpl(name, typeProxy);
- } else
- if ((access & Opcodes.ACC_INTERFACE)==Opcodes.ACC_INTERFACE) {
- return new InterfaceModelImpl(name, typeProxy, parent);
+ synchronized(typeProxy) {
+ final Type type = typeProxy.get();
+ if (null == type) {
+ if ((access & Opcodes.ACC_ANNOTATION)==Opcodes.ACC_ANNOTATION) {
+ return new AnnotationTypeImpl(name, typeProxy);
+ } else
+ if ((access & Opcodes.ACC_INTERFACE)==Opcodes.ACC_INTERFACE) {
+ return new InterfaceModelImpl(name, typeProxy, parent);
+ } else {
+ return new ClassModelImpl(name, typeProxy, parent);
+ }
} else {
- return new ClassModelImpl(name, typeProxy, parent);
+ TypeImpl impl = (TypeImpl)type;
+ if (ExtensibleTypeImpl.class.isInstance(impl)) {
+ // ensure we have the parent right
+ ((ExtensibleTypeImpl<?>)impl).setParent(parent);
+ }
+ return impl;
}
- } else {
- TypeImpl impl = (TypeImpl)type;
- if (ExtensibleTypeImpl.class.isInstance(impl)) {
- // ensure we have the parent right
- ((ExtensibleTypeImpl<?>)impl).setParent(parent);
- }
- return impl;
}
}
public FieldModelImpl getFieldModel(String name, TypeProxy type, ClassModel declaringType) {
return new FieldModelImpl(name, type, declaringType);
}
@Override
public TypeProxy getHolder(String name) {
TypeProxy proxy = getHolder(name, InterfaceModel.class);
if (proxy!=null) {
return proxy;
}
proxy = getHolder(name, ClassModel.class);
if (proxy!=null) {
return proxy;
}
return getHolder(name, AnnotationType.class);
}
@Override
public <T extends Type> TypeProxy<T> getHolder(String name, Class<T> type) {
return (TypeProxy<T>) types.getHolder(name, type);
}
}
| false | true | public synchronized TypeImpl getType(int access, String name, TypeProxy parent) {
Class<? extends Type> requestedType = getType(access);
TypeProxy<Type> typeProxy = types.getHolder(name, requestedType);
final Type type = typeProxy.get();
if (null == type) {
if ((access & Opcodes.ACC_ANNOTATION)==Opcodes.ACC_ANNOTATION) {
return new AnnotationTypeImpl(name, typeProxy);
} else
if ((access & Opcodes.ACC_INTERFACE)==Opcodes.ACC_INTERFACE) {
return new InterfaceModelImpl(name, typeProxy, parent);
} else {
return new ClassModelImpl(name, typeProxy, parent);
}
} else {
TypeImpl impl = (TypeImpl)type;
if (ExtensibleTypeImpl.class.isInstance(impl)) {
// ensure we have the parent right
((ExtensibleTypeImpl<?>)impl).setParent(parent);
}
return impl;
}
}
| public TypeImpl getType(int access, String name, TypeProxy parent) {
Class<? extends Type> requestedType = getType(access);
TypeProxy<Type> typeProxy = types.getHolder(name, requestedType);
synchronized(typeProxy) {
final Type type = typeProxy.get();
if (null == type) {
if ((access & Opcodes.ACC_ANNOTATION)==Opcodes.ACC_ANNOTATION) {
return new AnnotationTypeImpl(name, typeProxy);
} else
if ((access & Opcodes.ACC_INTERFACE)==Opcodes.ACC_INTERFACE) {
return new InterfaceModelImpl(name, typeProxy, parent);
} else {
return new ClassModelImpl(name, typeProxy, parent);
}
} else {
TypeImpl impl = (TypeImpl)type;
if (ExtensibleTypeImpl.class.isInstance(impl)) {
// ensure we have the parent right
((ExtensibleTypeImpl<?>)impl).setParent(parent);
}
return impl;
}
}
}
|
diff --git a/app/net/sparkmuse/data/twig/TwigUserDao.java b/app/net/sparkmuse/data/twig/TwigUserDao.java
index f00afaa..bfa0a57 100644
--- a/app/net/sparkmuse/data/twig/TwigUserDao.java
+++ b/app/net/sparkmuse/data/twig/TwigUserDao.java
@@ -1,169 +1,175 @@
package net.sparkmuse.data.twig;
import net.sparkmuse.data.UserDao;
import net.sparkmuse.user.Votable;
import net.sparkmuse.user.Votables;
import net.sparkmuse.user.UserLogin;
import net.sparkmuse.data.entity.*;
import com.google.inject.Inject;
import static com.google.appengine.api.datastore.Query.FilterOperator.*;
import com.google.common.collect.Sets;
import com.google.common.collect.Iterables;
import com.google.common.base.Predicate;
import java.util.Set;
import java.util.Map;
import java.util.List;
import org.apache.commons.collections.CollectionUtils;
/**
* Created by IntelliJ IDEA.
*
* @author neteller
* @created: Sep 19, 2010
*/
public class TwigUserDao extends TwigDao implements UserDao {
@Inject
public TwigUserDao(DatastoreService service) {
super(service);
}
public UserVO findOrCreateUserBy(UserLogin login) {
final UserVO userVO = helper.only(datastore.find()
.type(UserVO.class)
.addFilter("authProviderUserId", EQUAL, login.getAuthProviderUserId()));
//user never logged in before
if (null == userVO) {
//see if we already created one
- UserVO newUser = helper.only(datastore.find()
+ final UserVO adminCreatedUser = helper.only(datastore.find()
.type(UserVO.class)
.addFilter("userNameLowercase", EQUAL, login.getScreenName().toLowerCase()));
//otherwise create a new guy
- if (null == newUser) newUser = UserVO.newUser(login.getScreenName());
+ if (null == adminCreatedUser) {
+ final UserVO newUser = UserVO.newUser(login.getScreenName());
- newUser.updateUserDuring(login);
- final UserVO storedNewUser = helper.store(newUser);
+ newUser.updateUserDuring(login);
+ final UserVO storedNewUser = helper.store(newUser);
- final UserProfile profile = UserProfile.newProfile(storedNewUser);
- helper.store(profile);
+ final UserProfile profile = UserProfile.newProfile(storedNewUser);
+ helper.store(profile);
- return storedNewUser;
+ return storedNewUser;
+ }
+ else {
+ adminCreatedUser.updateUserDuring(login);
+ return helper.update(adminCreatedUser);
+ }
}
//user was created or invited but never logged in, same as below, just wanted it doc'd
//repeat user login
else {
userVO.updateUserDuring(login);
return helper.update(userVO);
}
}
public UserVO findUserBy(Long id) {
return helper.getUser(id);
}
public UserProfile findUserProfileBy(String userName) {
final UserVO user = helper.only(datastore.find()
.type(UserVO.class)
.addFilter("userNameLowercase", EQUAL, userName.toLowerCase()));
if (null == user) return null;
return helper.only(datastore.find()
.type(UserProfile.class)
.ancestor(user)
);
}
public List<UserProfile> getAllProfiles() {
return helper.all(datastore.find().type(UserProfile.class));
}
public void createUser(String userName) {
UserVO newUser = UserVO.newUser(userName);
final UserVO storedNewUser = helper.store(newUser);
final UserProfile profile = UserProfile.newProfile(storedNewUser);
helper.store(profile);
}
public Map<Long, UserVO> findUsersBy(Set<Long> ids) {
return helper.getUsers(ids);
}
public void saveApplication(String userName, String url) {
UserApplication app = new UserApplication();
app.userName = userName;
app.url = url;
datastore.store(app);
}
/**
* Stores a record of the vote for the given user, upvotes the votable, stores
* it to the datastore, and adjusts the author's reputation.
*
* @param votable
* @param voter
*/
public void vote(Votable votable, UserVO voter) {
helper.associate(voter);
final UserVote voteModel = datastore.load()
.type(UserVote.class)
.id(Votables.newKey(votable))
.parent(voter)
.now();
//check for existing vote
if (null == voteModel) {
//store vote later so we can check if user has voted on whatever
datastore.store().instance(UserVote.newUpVote(votable, voter)).parent(voter).later();
//record aggregate vote count on entity
if (votable instanceof Entity) {
votable.upVote();
helper.update((Entity) votable);
}
//adjust reputation
final UserVO author = votable.getAuthor();
author.setReputation(author.getReputation() + 1);
helper.update(author);
}
}
public <T extends Entity<T>> void vote(Class<T> entityClass, Long id, UserVO voter) {
T entity = helper.load(entityClass, id);
if (entity instanceof Votable) {
vote((Votable) entity, voter);
}
}
public Set<UserVote> findVotesFor(Set<Votable> votables, UserVO user) {
if (CollectionUtils.size(votables) == 0) return Sets.newHashSet();
Set<String> ids = Sets.newHashSet();
for (Votable votable: votables) {
ids.add(Votables.newKey(votable));
}
helper.associate(user);
final Map<String, UserVote> voteMap = datastore.load()
.type(UserVote.class)
.ids(ids)
.parent(user)
.now();
//filter out nulls
final Iterable<UserVote> votes = Iterables.filter(voteMap.values(), new Predicate<UserVote>(){
public boolean apply(UserVote voteModel) {
return null != voteModel;
}
});
return Sets.newHashSet(votes);
}
}
| false | true | public UserVO findOrCreateUserBy(UserLogin login) {
final UserVO userVO = helper.only(datastore.find()
.type(UserVO.class)
.addFilter("authProviderUserId", EQUAL, login.getAuthProviderUserId()));
//user never logged in before
if (null == userVO) {
//see if we already created one
UserVO newUser = helper.only(datastore.find()
.type(UserVO.class)
.addFilter("userNameLowercase", EQUAL, login.getScreenName().toLowerCase()));
//otherwise create a new guy
if (null == newUser) newUser = UserVO.newUser(login.getScreenName());
newUser.updateUserDuring(login);
final UserVO storedNewUser = helper.store(newUser);
final UserProfile profile = UserProfile.newProfile(storedNewUser);
helper.store(profile);
return storedNewUser;
}
//user was created or invited but never logged in, same as below, just wanted it doc'd
//repeat user login
else {
userVO.updateUserDuring(login);
return helper.update(userVO);
}
}
| public UserVO findOrCreateUserBy(UserLogin login) {
final UserVO userVO = helper.only(datastore.find()
.type(UserVO.class)
.addFilter("authProviderUserId", EQUAL, login.getAuthProviderUserId()));
//user never logged in before
if (null == userVO) {
//see if we already created one
final UserVO adminCreatedUser = helper.only(datastore.find()
.type(UserVO.class)
.addFilter("userNameLowercase", EQUAL, login.getScreenName().toLowerCase()));
//otherwise create a new guy
if (null == adminCreatedUser) {
final UserVO newUser = UserVO.newUser(login.getScreenName());
newUser.updateUserDuring(login);
final UserVO storedNewUser = helper.store(newUser);
final UserProfile profile = UserProfile.newProfile(storedNewUser);
helper.store(profile);
return storedNewUser;
}
else {
adminCreatedUser.updateUserDuring(login);
return helper.update(adminCreatedUser);
}
}
//user was created or invited but never logged in, same as below, just wanted it doc'd
//repeat user login
else {
userVO.updateUserDuring(login);
return helper.update(userVO);
}
}
|
diff --git a/java/src/com/android/inputmethod/latin/ContactsDictionary.java b/java/src/com/android/inputmethod/latin/ContactsDictionary.java
index b057cf4e..e789e63c 100644
--- a/java/src/com/android/inputmethod/latin/ContactsDictionary.java
+++ b/java/src/com/android/inputmethod/latin/ContactsDictionary.java
@@ -1,164 +1,162 @@
/*
* Copyright (C) 2009 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.inputmethod.latin;
import android.content.ContentResolver;
import android.content.Context;
import android.database.ContentObserver;
import android.database.Cursor;
import android.os.SystemClock;
import android.provider.BaseColumns;
import android.provider.ContactsContract.Contacts;
import android.text.TextUtils;
import android.util.Log;
import com.android.inputmethod.keyboard.Keyboard;
public class ContactsDictionary extends ExpandableDictionary {
private static final String[] PROJECTION = {
BaseColumns._ID,
Contacts.DISPLAY_NAME,
};
private static final String TAG = "ContactsDictionary";
/**
* Frequency for contacts information into the dictionary
*/
private static final int FREQUENCY_FOR_CONTACTS = 128;
private static final int FREQUENCY_FOR_CONTACTS_BIGRAM = 90;
private static final int INDEX_NAME = 1;
private ContentObserver mObserver;
private long mLastLoadedContacts;
public ContactsDictionary(Context context, int dicTypeId) {
super(context, dicTypeId);
// Perform a managed query. The Activity will handle closing and requerying the cursor
// when needed.
ContentResolver cres = context.getContentResolver();
cres.registerContentObserver(
Contacts.CONTENT_URI, true,mObserver = new ContentObserver(null) {
@Override
public void onChange(boolean self) {
setRequiresReload(true);
}
});
loadDictionary();
}
@Override
public synchronized void close() {
if (mObserver != null) {
getContext().getContentResolver().unregisterContentObserver(mObserver);
mObserver = null;
}
super.close();
}
@Override
public void startDictionaryLoadingTaskLocked() {
long now = SystemClock.uptimeMillis();
if (mLastLoadedContacts == 0
|| now - mLastLoadedContacts > 30 * 60 * 1000 /* 30 minutes */) {
super.startDictionaryLoadingTaskLocked();
}
}
@Override
public void loadDictionaryAsync() {
try {
Cursor cursor = getContext().getContentResolver()
.query(Contacts.CONTENT_URI, PROJECTION, null, null, null);
if (cursor != null) {
addWords(cursor);
}
} catch(IllegalStateException e) {
Log.e(TAG, "Contacts DB is having problems");
}
mLastLoadedContacts = SystemClock.uptimeMillis();
}
@Override
public void getBigrams(final WordComposer codes, final CharSequence previousWord,
final WordCallback callback) {
// Do not return bigrams from Contacts when nothing was typed.
if (codes.size() <= 0) return;
super.getBigrams(codes, previousWord, callback);
}
private void addWords(Cursor cursor) {
clearDictionary();
final int maxWordLength = getMaxWordLength();
try {
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(INDEX_NAME);
- if (name != null) {
+ if (name != null && -1 == name.indexOf('@')) {
int len = name.length();
String prevWord = null;
// TODO: Better tokenization for non-Latin writing systems
for (int i = 0; i < len; i++) {
if (Character.isLetter(name.charAt(i))) {
int j;
for (j = i + 1; j < len; j++) {
char c = name.charAt(j);
if (!(c == Keyboard.CODE_DASH
|| c == Keyboard.CODE_SINGLE_QUOTE
|| Character.isLetter(c))) {
break;
}
}
String word = name.substring(i, j);
i = j - 1;
// Safeguard against adding really long words. Stack
// may overflow due to recursion
// Also don't add single letter words, possibly confuses
// capitalization of i.
final int wordLen = word.length();
if (wordLen < maxWordLength && wordLen > 1) {
super.addWord(word, FREQUENCY_FOR_CONTACTS);
if (!TextUtils.isEmpty(prevWord)) {
- // TODO Do not add email address
- // Not so critical
super.setBigram(prevWord, word,
FREQUENCY_FOR_CONTACTS_BIGRAM);
}
prevWord = word;
}
}
}
}
cursor.moveToNext();
}
}
cursor.close();
} catch(IllegalStateException e) {
Log.e(TAG, "Contacts DB is having problems");
}
}
}
| false | true | private void addWords(Cursor cursor) {
clearDictionary();
final int maxWordLength = getMaxWordLength();
try {
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(INDEX_NAME);
if (name != null) {
int len = name.length();
String prevWord = null;
// TODO: Better tokenization for non-Latin writing systems
for (int i = 0; i < len; i++) {
if (Character.isLetter(name.charAt(i))) {
int j;
for (j = i + 1; j < len; j++) {
char c = name.charAt(j);
if (!(c == Keyboard.CODE_DASH
|| c == Keyboard.CODE_SINGLE_QUOTE
|| Character.isLetter(c))) {
break;
}
}
String word = name.substring(i, j);
i = j - 1;
// Safeguard against adding really long words. Stack
// may overflow due to recursion
// Also don't add single letter words, possibly confuses
// capitalization of i.
final int wordLen = word.length();
if (wordLen < maxWordLength && wordLen > 1) {
super.addWord(word, FREQUENCY_FOR_CONTACTS);
if (!TextUtils.isEmpty(prevWord)) {
// TODO Do not add email address
// Not so critical
super.setBigram(prevWord, word,
FREQUENCY_FOR_CONTACTS_BIGRAM);
}
prevWord = word;
}
}
}
}
cursor.moveToNext();
}
}
cursor.close();
} catch(IllegalStateException e) {
Log.e(TAG, "Contacts DB is having problems");
}
}
| private void addWords(Cursor cursor) {
clearDictionary();
final int maxWordLength = getMaxWordLength();
try {
if (cursor.moveToFirst()) {
while (!cursor.isAfterLast()) {
String name = cursor.getString(INDEX_NAME);
if (name != null && -1 == name.indexOf('@')) {
int len = name.length();
String prevWord = null;
// TODO: Better tokenization for non-Latin writing systems
for (int i = 0; i < len; i++) {
if (Character.isLetter(name.charAt(i))) {
int j;
for (j = i + 1; j < len; j++) {
char c = name.charAt(j);
if (!(c == Keyboard.CODE_DASH
|| c == Keyboard.CODE_SINGLE_QUOTE
|| Character.isLetter(c))) {
break;
}
}
String word = name.substring(i, j);
i = j - 1;
// Safeguard against adding really long words. Stack
// may overflow due to recursion
// Also don't add single letter words, possibly confuses
// capitalization of i.
final int wordLen = word.length();
if (wordLen < maxWordLength && wordLen > 1) {
super.addWord(word, FREQUENCY_FOR_CONTACTS);
if (!TextUtils.isEmpty(prevWord)) {
super.setBigram(prevWord, word,
FREQUENCY_FOR_CONTACTS_BIGRAM);
}
prevWord = word;
}
}
}
}
cursor.moveToNext();
}
}
cursor.close();
} catch(IllegalStateException e) {
Log.e(TAG, "Contacts DB is having problems");
}
}
|
diff --git a/src/main/java/com/sorcix/sirc/IrcInput.java b/src/main/java/com/sorcix/sirc/IrcInput.java
index 1048582..6f5228d 100644
--- a/src/main/java/com/sorcix/sirc/IrcInput.java
+++ b/src/main/java/com/sorcix/sirc/IrcInput.java
@@ -1,134 +1,134 @@
/*
* IrcInput.java
*
* This file is part of the Sorcix Java IRC Library (sIRC).
*
* Copyright (C) 2008-2010 Vic Demuzere http://sorcix.com
*
* Permission is hereby granted, free of charge, to any person
* obtaining a copy of this software and associated documentation
* files (the "Software"), to deal in the Software without
* restriction, including without limitation the rights to use, copy,
* modify, merge, publish, distribute, sublicense, and/or sell copies
* of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
* NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS
* BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN
* ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
* CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package com.sorcix.sirc;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.Reader;
import java.net.SocketException;
import java.util.Iterator;
/**
* Input Thread.
*
* @author Sorcix
*/
final class IrcInput extends Thread {
/** Stream used to read from the IRC server. */
private final BufferedReader in;
/** The IrcConnection. */
private final IrcConnection irc;
private final IrcParser parser = new IrcParser();
/**
* Creates a new input thread.
*
* @param irc The IrcConnection using this output thread.
* @param in The stream to use for communication.
*/
protected IrcInput(final IrcConnection irc, final Reader in) {
this.setName("sIRC-IN:" + irc.getServerAddress() + "-" + irc.getClient().getUserName());
this.setPriority(Thread.NORM_PRIORITY);
this.setDaemon(false);
this.in = new BufferedReader(in);
this.irc = irc;
}
/**
* Closes the input stream.
*
* @throws IOException
* @see IrcConnection#disconnect()
*/
protected void close() throws IOException {
this.in.close();
}
/**
* Returns the reader used in this input thread.
*
* @return the reader.
*/
protected BufferedReader getReader() {
return this.in;
}
/**
* Handles a line received by the IRC server.
*
* @param line The line to handle.
*/
private void handleLine(final String line) {
// transform the raw line into an easier format
final IrcPacket parser = new IrcPacket(line, this.irc);
// Handle numeric server replies.
if (parser.isNumeric()) {
this.parser.parseNumeric(this.irc, parser);
return;
}
// Handle different commands
this.parser.parseCommand(this.irc, parser);
}
/**
* Checks the input stream for new messages.
*/
@Override
public void run() {
String line = null;
try {
// wait for lines to come in
while ((line = this.in.readLine()) != null) {
IrcDebug.log("<<< " + line);
// always respond to PING
if (line.startsWith("PING ")) {
this.irc.out.pong(line.substring(5));
} else {
this.handleLine(line);
}
}
} catch (final SocketException ex) {
this.irc.setConnected(false);
} catch (final IOException ex) {
this.irc.setConnected(false);
} catch (final Exception ex) {
- IrcDebug.log("Exception " + ex + " on: " + line);
+ IrcDebug.log("Exception " + ex + " on: " + line);
ex.printStackTrace();
}
// when reaching this, we are disconnected
this.irc.setConnected(false);
// close connections
this.irc.disconnect();
// send disconnect event
for (final Iterator<ServerListener> it = this.irc.getServerListeners(); it.hasNext();) {
it.next().onDisconnect(this.irc);
}
}
}
| true | true | public void run() {
String line = null;
try {
// wait for lines to come in
while ((line = this.in.readLine()) != null) {
IrcDebug.log("<<< " + line);
// always respond to PING
if (line.startsWith("PING ")) {
this.irc.out.pong(line.substring(5));
} else {
this.handleLine(line);
}
}
} catch (final SocketException ex) {
this.irc.setConnected(false);
} catch (final IOException ex) {
this.irc.setConnected(false);
} catch (final Exception ex) {
IrcDebug.log("Exception " + ex + " on: " + line);
ex.printStackTrace();
}
// when reaching this, we are disconnected
this.irc.setConnected(false);
// close connections
this.irc.disconnect();
// send disconnect event
for (final Iterator<ServerListener> it = this.irc.getServerListeners(); it.hasNext();) {
it.next().onDisconnect(this.irc);
}
}
| public void run() {
String line = null;
try {
// wait for lines to come in
while ((line = this.in.readLine()) != null) {
IrcDebug.log("<<< " + line);
// always respond to PING
if (line.startsWith("PING ")) {
this.irc.out.pong(line.substring(5));
} else {
this.handleLine(line);
}
}
} catch (final SocketException ex) {
this.irc.setConnected(false);
} catch (final IOException ex) {
this.irc.setConnected(false);
} catch (final Exception ex) {
IrcDebug.log("Exception " + ex + " on: " + line);
ex.printStackTrace();
}
// when reaching this, we are disconnected
this.irc.setConnected(false);
// close connections
this.irc.disconnect();
// send disconnect event
for (final Iterator<ServerListener> it = this.irc.getServerListeners(); it.hasNext();) {
it.next().onDisconnect(this.irc);
}
}
|
diff --git a/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/PnlAbstractUniqueValue.java b/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/PnlAbstractUniqueValue.java
index 72b665f33..85d0a06cb 100644
--- a/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/PnlAbstractUniqueValue.java
+++ b/orbisgis-view/src/main/java/org/orbisgis/view/toc/actions/cui/legends/PnlAbstractUniqueValue.java
@@ -1,666 +1,666 @@
/**
* OrbisGIS is a GIS application dedicated to scientific spatial simulation.
* This cross-platform GIS is developed at French IRSTV institute and is able to
* manipulate and create vector and raster spatial information.
*
* OrbisGIS is distributed under GPL 3 license. It is produced by the "Atelier SIG"
* team of the IRSTV Institute <http://www.irstv.fr/> CNRS FR 2488.
*
* Copyright (C) 2007-2012 IRSTV (FR CNRS 2488)
*
* This file is part of OrbisGIS.
*
* OrbisGIS 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.
*
* OrbisGIS 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
* OrbisGIS. If not, see <http://www.gnu.org/licenses/>.
*
* For more information, please consult: <http://www.orbisgis.org/>
* or contact directly:
* info_at_ orbisgis.org
*/
package org.orbisgis.view.toc.actions.cui.legends;
import org.apache.log4j.Logger;
import org.gdms.data.DataSource;
import org.gdms.data.values.Value;
import org.gdms.driver.DriverException;
import org.orbisgis.core.layerModel.ILayer;
import org.orbisgis.core.renderer.se.Symbolizer;
import org.orbisgis.legend.Legend;
import org.orbisgis.legend.thematic.LineParameters;
import org.orbisgis.legend.thematic.recode.AbstractRecodedLegend;
import org.orbisgis.progress.ProgressMonitor;
import org.orbisgis.sif.UIFactory;
import org.orbisgis.sif.UIPanel;
import org.orbisgis.view.background.*;
import org.orbisgis.view.joblist.JobListItem;
import org.orbisgis.view.toc.actions.cui.LegendContext;
import org.orbisgis.view.toc.actions.cui.components.CanvasSE;
import org.orbisgis.view.toc.actions.cui.legend.ILegendPanel;
import org.orbisgis.view.toc.actions.cui.legends.model.KeyEditorUniqueValue;
import org.orbisgis.view.toc.actions.cui.legends.model.PreviewCellRenderer;
import org.orbisgis.view.toc.actions.cui.legends.model.TableModelUniqueValue;
import org.xnap.commons.i18n.I18n;
import org.xnap.commons.i18n.I18nFactory;
import javax.swing.*;
import javax.swing.event.CellEditorListener;
import javax.swing.table.AbstractTableModel;
import javax.swing.table.TableCellEditor;
import javax.swing.table.TableColumn;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.beans.EventHandler;
import java.net.URL;
import java.util.HashSet;
import java.util.TreeSet;
/**
* Methods shared by unique value analysis.
* @author alexis
*/
public abstract class PnlAbstractUniqueValue<U extends LineParameters> extends AbstractFieldPanel implements ILegendPanel, ActionListener {
public final static String CREATE_CLASSIF = "Create classification";
public final static Logger LOGGER = Logger.getLogger(PnlAbstractUniqueValue.class);
private static I18n I18N = I18nFactory.getI18n(PnlAbstractUniqueValue.class);
private AbstractRecodedLegend<U> legend;
private static final String ADD = "add";
private static final String REMOVE = "remove";
private DataSource ds;
private JPanel colorConfig;
private JLabel endCol;
private JLabel startCol;
private JTable table;
public final static int CELL_PREVIEW_WIDTH = CanvasSE.WIDTH/2;
public final static int CELL_PREVIEW_HEIGHT = CanvasSE.HEIGHT/2;
protected final static String JOB_NAME = "recodeSelectDistinct";
@Override
public void initialize(LegendContext lc) {
if (getLegend() == null) {
setLegend(getEmptyAnalysis());
initPreview();
}
setGeometryType(lc.getGeometryType());
ILayer layer = lc.getLayer();
if (layer != null && layer.getDataSource() != null) {
setDataSource(layer.getDataSource());
}
}
protected void setLegendImpl(Legend leg){
this.legend = (AbstractRecodedLegend<U>) leg;
}
/**
* Creates and fill the combo box that will be used to compute the
* analysis.
*
* @return A ComboBox linked to the underlying MappedLegend that configures the analysis field.
*/
public JComboBox getFieldComboBox() {
if (ds != null) {
JComboBox jcc = getFieldCombo(ds);
ActionListener acl2 = EventHandler.create(ActionListener.class,
this, "updateField", "source.selectedItem");
String field = legend.getLookupFieldName();
if (field != null && !field.isEmpty()) {
jcc.setSelectedItem(field);
}
jcc.addActionListener(acl2);
updateField((String) jcc.getSelectedItem());
return jcc;
} else {
return new JComboBox();
}
}
/**
* Sets the associated data source
* @param newDS the new {@link DataSource}.
*/
protected void setDataSource(DataSource newDS){
ds = newDS;
}
/**
* Used when the field against which the analysis is made changes.
*
* @param obj The new field.
*/
public void updateField(String obj) {
legend.setLookupFieldName(obj);
}
@Override
public Legend getLegend() {
return legend;
}
@Override
public void actionPerformed(ActionEvent e) {
if(e.getActionCommand().equals(ADD)){
String key = legend.getNotUsedKey("newValue");
U lp = legend.getFallbackParameters();
legend.put(key, lp);
TableModelUniqueValue model = (TableModelUniqueValue) getJTable().getModel();
model.fireTableDataChanged();
} else if (e.getActionCommand().equals(REMOVE)){
TableModelUniqueValue model = (TableModelUniqueValue) getJTable().getModel();
int col = getJTable().getSelectedColumn();
int row = getJTable().getSelectedRow();
if(col>=0 && row >= 0){
String key = (String)getJTable().getValueAt(row, col);
legend.remove(key);
model.fireTableDataChanged();
}
}
}
/**
* Creates the two buttons add and remove, links them to this through actions and put them in a JPanel.
* @return the two buttons in a JPanel.
*/
public JPanel getButtonsPanel(){
JPanel jp = new JPanel();
JButton jb1 = new JButton(I18N.tr("Add"));
jb1.setActionCommand(ADD);
jb1.addActionListener(this);
jp.add(jb1);
jp.setAlignmentX((float) .5);
JButton remove = new JButton(I18N.tr("Remove"));
remove.setActionCommand(REMOVE);
remove.addActionListener(this);
jp.add(jb1);
jp.add(remove);
jp.setAlignmentX((float) .5);
return jp;
}
/**
* Gets the panel that can be used to produce the colours of a generated classification
* @return The configuration panel.
*/
public JPanel getColorConfig(){
colorConfig = new JPanel();
BoxLayout classLayout = new BoxLayout(colorConfig, BoxLayout.Y_AXIS);
colorConfig.setLayout(classLayout);
//The start colour
JPanel start = new JPanel();
start.add(new JLabel(I18N.tr("Start colour :")));
startCol = getFilledLabel(Color.BLUE);
start.add(startCol);
start.setAlignmentX((float).5);
colorConfig.add(start);
//The end colour
JPanel end = new JPanel();
end.add(new JLabel(I18N.tr("End colour :")));
endCol = getFilledLabel(Color.RED);
end.setAlignmentX((float).5);
end.add(endCol);
colorConfig.add(end);
//We add colorConfig to the global panel
colorConfig.setAlignmentX((float).5);
return colorConfig;
}
/**
* Initialize the panels.
*/
public abstract void initializeLegendFields();
/**
* Gets an empty analysis that can be used ot build a panel equivalent to the caller.
* @return an empty analysis
*/
public abstract AbstractRecodedLegend<U> getEmptyAnalysis();
/**
* Init the preview of the fallback symbol.
*/
public abstract void initPreview();
/**
* Gets a unique symbol configuration whose only difference with {@code fallback} is one of its color set to {@code
* c}.
* @param fallback The original configuration
* @param c The new colour
* @return A new configuration.
*/
public abstract U getColouredParameters(U fallback, Color c);
/**
* We take the fallback configuration and copy it for each key.
* @param set A set of keys we use as a basis.
* @param pm The progress monitor that can be used to stop the process.
* @return A fresh unique value analysis.
*/
public AbstractRecodedLegend<U> createConstantClassification(TreeSet<String> set, ProgressMonitor pm) {
U lp = legend.getFallbackParameters();
AbstractRecodedLegend newRL = getEmptyAnalysis();
newRL.setFallbackParameters(lp);
int size = set.size();
double m = size == 0 ? 0 : 90.0/(double)size;
int i = 0;
int n = 0;
pm.startTask(CREATE_CLASSIF, 100);
for(String s : set){
newRL.put(s, lp);
if(i*m>n){
n++;
pm.progressTo(n+10);
}
if(pm.isCancelled()){
pm.endTask();
return null;
}
i++;
}
pm.progressTo(100);
pm.endTask();
return newRL;
}
/**
* We take the fallback configuration and copy it for each key, changing the colour. The colour management is
* made thanks to {@link #getColouredParameters(org.orbisgis.legend.thematic.LineParameters, java.awt.Color)}.
* @param set A set of keys we use as a basis.
* @param pm The progress monitor that can be used to stop the process.
* @param start the starting color for the gradient
* @param end the ending color for the gradient
* @return A fresh unique value analysis.
*/
public final AbstractRecodedLegend<U> createColouredClassification(TreeSet<String> set, ProgressMonitor pm,
Color start, Color end) {
U lp = legend.getFallbackParameters();
AbstractRecodedLegend<U> newRL = getEmptyAnalysis();
newRL.setFallbackParameters(lp);
int size = set.size();
int redStart = start.getRed();
int greenStart = start.getGreen();
int blueStart = start.getBlue();
int alphaStart = start.getAlpha();
- int redThreshold;
- int greenThreshold;
- int blueThreshold;
- int alphaThreshold;
+ double redThreshold;
+ double greenThreshold;
+ double blueThreshold;
+ double alphaThreshold;
if(size <= 1){
redThreshold = 0;
greenThreshold = 0;
blueThreshold = 0;
alphaThreshold = 0;
} else {
- redThreshold = (redStart-end.getRed())/(size-1);
- greenThreshold = (greenStart-end.getGreen())/(size-1);
- blueThreshold = (blueStart-end.getBlue())/(size-1);
- alphaThreshold = (alphaStart-end.getAlpha())/(size-1);
+ redThreshold = ((double)(redStart-end.getRed()))/(size-1);
+ greenThreshold = ((double)(greenStart-end.getGreen()))/(size-1);
+ blueThreshold = ((double)(blueStart-end.getBlue()))/(size-1);
+ alphaThreshold = ((double)(alphaStart-end.getAlpha()))/(size-1);
}
double m = size == 0 ? 0 : 90.0/(double)size;
int i=0;
int n = 0;
pm.startTask(CREATE_CLASSIF , 100);
for(String s : set){
- Color newCol = new Color(redStart-redThreshold*i,
- greenStart-i*greenThreshold,
- blueStart-i*blueThreshold,
- alphaStart-i*alphaThreshold);
+ Color newCol = new Color(redStart-(int)(redThreshold*i),
+ greenStart-(int)(i*greenThreshold),
+ blueStart-(int)(i*blueThreshold),
+ alphaStart-(int)(i*alphaThreshold));
U value = getColouredParameters(lp, newCol);
newRL.put(s, value);
if(i*m>n){
n++;
pm.progressTo(n+10);
}
if(pm.isCancelled()){
pm.endTask();
return null;
}
i++;
}
pm.endTask();
return newRL;
}
/**
* Disables the colour configuration.
*/
public void onFromFallback(){
setFieldState(false,colorConfig);
}
/**
* Enables the colour configuration.
*/
public void onComputed(){
setFieldState(true, colorConfig);
}
/**
* Gets the JTable used to draw the mapping
* @return the JTable
*/
public JTable getJTable(){
return table;
}
/**
* Gets the constant Symbolizer obtained when using all the constant and fallback values of the original Symbolizer.
* @return The fallback Symbolizer.
*/
public abstract Symbolizer getFallbackSymbolizer();
/**
* Update the inner CanvasSE. It updates its symbolizer and forced the image to be redrawn.
*/
public final void updatePreview(Object source){
JComboBox jcb = (JComboBox) source;
updateLUComboBox(jcb.getSelectedIndex());
CanvasSE prev = getPreview();
prev.setSymbol(getFallbackSymbolizer());
prev.imageChanged();
AbstractTableModel model = (AbstractTableModel) getJTable().getModel();
model.fireTableDataChanged();
}
/**
* Gets the model used to build the JTable.
* @return The table model.
*/
public abstract AbstractTableModel getTableModel();
/**
* Gets the editor used to configure a cell with a preview.
* @return A cell editor.
*/
public abstract TableCellEditor getParametersCellEditor();
/**
* Gets the editor used to configure a key of the table
* @return A cell editor.
*/
public abstract KeyEditorUniqueValue<U> getKeyCellEditor();
/**
* Build the panel that contains the JTable where the map is displayed.
* @return The panel that contains the JTable where the map is displayed.
*/
public JPanel getTablePanel() {
JPanel jp = new JPanel();
BoxLayout bl = new BoxLayout(jp, BoxLayout.Y_AXIS);
jp.setLayout(bl);
jp.setBorder(BorderFactory.createTitledBorder(I18N.tr("Unique value classification")));
//we build the table here
AbstractTableModel model = getTableModel();
table = new JTable(model);
table.setDefaultEditor(Object.class, null);
table.setRowHeight(CELL_PREVIEW_HEIGHT);
final int previewWidth = CELL_PREVIEW_WIDTH;
TableColumn previews = table.getColumnModel().getColumn(TableModelUniqueValue.PREVIEW_COLUMN);
previews.setWidth(previewWidth);
previews.setMinWidth(previewWidth);
previews.setMaxWidth(previewWidth);
previews.setCellRenderer(new PreviewCellRenderer(table, String.class, ((AbstractRecodedLegend<U>)getLegend())));
previews.setCellEditor(getParametersCellEditor());
//We put a default editor on the keys.
TableColumn keys = table.getColumnModel().getColumn(TableModelUniqueValue.KEY_COLUMN);
KeyEditorUniqueValue<U> ker = getKeyCellEditor();
CellEditorListener cel = EventHandler.create(CellEditorListener.class, model, "fireTableDataChanged", null, "editingStopped");
ker.addCellEditorListener(cel);
keys.setCellEditor(ker);
JScrollPane jsp = new JScrollPane(table);
table.setPreferredScrollableViewportSize(new Dimension(400,200));
jsp.setAlignmentX((float).5);
jp.add(jsp, BorderLayout.CENTER);
table.doLayout();
jp.add(getButtonsPanel());
return jp;
}
/**
* This Job can be used as a background operation to retrieve a set containing the distinct data of a specific
* field in a DataSource.
*/
public class SelectDistinctJob implements BackgroundJob {
private final String fieldName;
private TreeSet<String> result = null;
/**
* Builds the BackgroundJob.
* @param f The name of the field we want the data from.
*/
public SelectDistinctJob(String f){
fieldName = f;
}
@Override
public void run(ProgressMonitor pm) {
result = getValues(pm);
if(result != null){
AbstractRecodedLegend<U> rl;
if(colorConfig.isEnabled() && result.size() > 0){
Color start = startCol.getBackground();
Color end = endCol.getBackground();
rl = createColouredClassification(result, pm, start, end);
} else {
rl = createConstantClassification(result, pm);
}
if(rl != null){
rl.setLookupFieldName(legend.getLookupFieldName());
rl.setName(legend.getName());
setLegend(rl);
}
} else {
pm.startTask(PnlRecodedLine.CREATE_CLASSIF, 100);
pm.endTask();
}
}
/**
* Gathers all the distinct values of the input DataSource in a {@link HashSet}.
* @param pm Used to be able to cancel the job.
* @return The distinct values as String instances in a {@link HashSet} or null if the job has been cancelled.
*/
public TreeSet<String> getValues(final ProgressMonitor pm){
TreeSet<String> ret = new TreeSet<String>();
try {
long rowCount=ds.getRowCount();
pm.startTask(I18N.tr("Retrieving classes"), 10);
pm.progressTo(0);
double m = rowCount>0 ?(double)10/rowCount : 0;
int n =0;
int fieldIndex = ds.getFieldIndexByName(fieldName);
final int warn = 100;
for(long i=0; i<rowCount; i++){
Value val = ds.getFieldValue(i, fieldIndex);
ret.add(val.toString());
if(ret.size() == warn){
final UIPanel cancel = new CancelPanel(warn);
try{
SwingUtilities.invokeAndWait(new Runnable() {
@Override
public void run() {
if(!UIFactory.showDialog(cancel,true, true)){
pm.setCancelled(true);
}
}
});
} catch (Exception ie){
LOGGER.warn(I18N.tr("The application has ended unexpectedly"));
}
}
if(i*m>n*10){
n++;
pm.progressTo(n);
}
if(pm.isCancelled()){
pm.endTask();
return null;
}
}
} catch (DriverException e) {
LOGGER.error("IO error while handling the input data source : " + e.getMessage());
}
pm.endTask();
return ret;
}
/**
* Gets the generated DataSource.
* @return The gathered information in a DataSource.
*/
public TreeSet<String> getResult() {
return result;
}
@Override
public String getTaskName() {
return "select distinct";
}
}
/**
* This panel is used to let the user cancel classifications on more values than a given threshold.
*/
private static class CancelPanel implements UIPanel {
private int threshold;
/**
* Builds a new CancelPanel
* @param thres The expected limit, displayed in the inner JLable.
*/
public CancelPanel(int thres){
super();
threshold = thres;
}
@Override
public URL getIconURL() {
return UIFactory.getDefaultIcon();
}
@Override
public String getTitle() {
return I18N.tr("Continue ?");
}
@Override
public String validateInput() {
return null;
}
@Override
public Component getComponent() {
JPanel pan = new JPanel();
JLabel lab = new JLabel();
StringBuilder sb = new StringBuilder();
sb.append(I18N.tr("<html><p>The analysis seems to generate more than "));
sb.append(threshold);
sb.append(I18N.tr(" different values...</p><p>Are you sure you want to continue ?</p></html>"));
lab.setText(sb.toString());
pan.add(lab);
return pan;
}
}
/**
* This progress listener listens to the progression of the background operation that retrieves data from
* the analysed source and builds a simple unique value classification with it.
*/
public class DistinctListener implements ProgressListener {
private JDialog window;
private final JobListItem jli;
private int count = 0;
/**
* Builds the listener from the given {@code JobListItem}. Not that the construction ends by displaying
* a {@link JDialog} in modal mode that stays always on top of the application.
* @param jli The item that will provide the progress bar.
*/
public DistinctListener(JobListItem jli){
this.jli = jli;
JDialog root = (JDialog) SwingUtilities.getRoot(PnlAbstractUniqueValue.this);
root.setEnabled(false);
this.window = new JDialog(root,I18N.tr("Operation in progress..."));
window.setLayout(new BorderLayout());
window.setAlwaysOnTop(true);
window.setVisible(true);
window.setModal(true);
window.setDefaultCloseOperation(JDialog.DISPOSE_ON_CLOSE);
window.add(jli.getItemPanel());
window.setLocationRelativeTo(root);
window.setMinimumSize(jli.getItemPanel().getPreferredSize());
}
@Override
public void progressChanged(Job job) {
window.pack();
}
@Override
public void subTaskStarted(Job job) {
}
@Override
public void subTaskFinished(Job job) {
count ++;
//I know I have two subtasks... This is unfortunate, but I don't find really efficient way to hide my
//dialog from the listener without that..
if(count >= 2){
window.setVisible(false);
JDialog root = (JDialog) SwingUtilities.getRoot(PnlAbstractUniqueValue.this);
root.setEnabled(true);
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
jli.dispose();
}
});
}
}
}
/**
* This backgroundListener waits for operation on {@code Job} with {@link PnlRecodedLine#JOB_NAME} as its name.
* When such a {@link Job} is added, it adds a DistinctListener to the associated Job. When it is removed, it
* retrieves the gathered information and build a new classification from it.
*/
public class OperationListener implements BackgroundListener {
@Override
public void jobAdded(Job job) {
if(job.getId().is(new DefaultJobId(JOB_NAME))){
JobListItem jli = new JobListItem(job).listenToJob(true);
DistinctListener listener = new DistinctListener(jli);
job.addProgressListener(listener);
}
}
@Override
public void jobRemoved(Job job) {
if(job.getId().is(new DefaultJobId(JOB_NAME))){
((AbstractTableModel) getJTable().getModel()).fireTableDataChanged();
getJTable().invalidate();
}
}
@Override
public void jobReplaced(Job job) {
}
}
}
| false | true | public final AbstractRecodedLegend<U> createColouredClassification(TreeSet<String> set, ProgressMonitor pm,
Color start, Color end) {
U lp = legend.getFallbackParameters();
AbstractRecodedLegend<U> newRL = getEmptyAnalysis();
newRL.setFallbackParameters(lp);
int size = set.size();
int redStart = start.getRed();
int greenStart = start.getGreen();
int blueStart = start.getBlue();
int alphaStart = start.getAlpha();
int redThreshold;
int greenThreshold;
int blueThreshold;
int alphaThreshold;
if(size <= 1){
redThreshold = 0;
greenThreshold = 0;
blueThreshold = 0;
alphaThreshold = 0;
} else {
redThreshold = (redStart-end.getRed())/(size-1);
greenThreshold = (greenStart-end.getGreen())/(size-1);
blueThreshold = (blueStart-end.getBlue())/(size-1);
alphaThreshold = (alphaStart-end.getAlpha())/(size-1);
}
double m = size == 0 ? 0 : 90.0/(double)size;
int i=0;
int n = 0;
pm.startTask(CREATE_CLASSIF , 100);
for(String s : set){
Color newCol = new Color(redStart-redThreshold*i,
greenStart-i*greenThreshold,
blueStart-i*blueThreshold,
alphaStart-i*alphaThreshold);
U value = getColouredParameters(lp, newCol);
newRL.put(s, value);
if(i*m>n){
n++;
pm.progressTo(n+10);
}
if(pm.isCancelled()){
pm.endTask();
return null;
}
i++;
}
pm.endTask();
return newRL;
}
| public final AbstractRecodedLegend<U> createColouredClassification(TreeSet<String> set, ProgressMonitor pm,
Color start, Color end) {
U lp = legend.getFallbackParameters();
AbstractRecodedLegend<U> newRL = getEmptyAnalysis();
newRL.setFallbackParameters(lp);
int size = set.size();
int redStart = start.getRed();
int greenStart = start.getGreen();
int blueStart = start.getBlue();
int alphaStart = start.getAlpha();
double redThreshold;
double greenThreshold;
double blueThreshold;
double alphaThreshold;
if(size <= 1){
redThreshold = 0;
greenThreshold = 0;
blueThreshold = 0;
alphaThreshold = 0;
} else {
redThreshold = ((double)(redStart-end.getRed()))/(size-1);
greenThreshold = ((double)(greenStart-end.getGreen()))/(size-1);
blueThreshold = ((double)(blueStart-end.getBlue()))/(size-1);
alphaThreshold = ((double)(alphaStart-end.getAlpha()))/(size-1);
}
double m = size == 0 ? 0 : 90.0/(double)size;
int i=0;
int n = 0;
pm.startTask(CREATE_CLASSIF , 100);
for(String s : set){
Color newCol = new Color(redStart-(int)(redThreshold*i),
greenStart-(int)(i*greenThreshold),
blueStart-(int)(i*blueThreshold),
alphaStart-(int)(i*alphaThreshold));
U value = getColouredParameters(lp, newCol);
newRL.put(s, value);
if(i*m>n){
n++;
pm.progressTo(n+10);
}
if(pm.isCancelled()){
pm.endTask();
return null;
}
i++;
}
pm.endTask();
return newRL;
}
|
diff --git a/coreplugins/browser/src/main/java/browser/DataEditAction.java b/coreplugins/browser/src/main/java/browser/DataEditAction.java
index 9f1c6d9d0..2bc1fbfff 100644
--- a/coreplugins/browser/src/main/java/browser/DataEditAction.java
+++ b/coreplugins/browser/src/main/java/browser/DataEditAction.java
@@ -1,604 +1,610 @@
/*
Copyright (c) 2006, 2007, 2010, The Cytoscape Consortium (www.cytoscape.org)
This library is free software; you can redistribute it and/or modify it
under the terms of the GNU Lesser General Public License as published
by the Free Software Foundation; either version 2.1 of the License, or
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. The software and
documentation provided hereunder is on an "as is" basis, and the
Institute for Systems Biology and the Whitehead Institute
have no obligations to provide maintenance, support,
updates, enhancements or modifications. In no event shall the
Institute for Systems Biology and the Whitehead Institute
be liable to any party for direct, indirect, special,
incidental or consequential damages, including lost profits, arising
out of the use of this software and its documentation, even if the
Institute for Systems Biology and the Whitehead Institute
have been advised of the possibility of such damage. See
the GNU Lesser General Public License for more details.
You should have received a copy of the GNU Lesser General Public License
along with this library; if not, write to the Free Software Foundation,
Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307 USA.
*/
package browser;
import static browser.DataObjectType.NETWORK;
import browser.util.AttrUtil;
import cytoscape.Cytoscape;
import cytoscape.data.CyAttributes;
import org.cytoscape.equations.BooleanList;
import org.cytoscape.equations.EqnCompiler;
import org.cytoscape.equations.DoubleList;
import org.cytoscape.equations.Equation;
import org.cytoscape.equations.FunctionUtil;
import org.cytoscape.equations.LongList;
import org.cytoscape.equations.StringList;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Map;
import java.util.List;
import java.util.TreeMap;
import javax.swing.JOptionPane;
import javax.swing.undo.AbstractUndoableEdit;
/**
* Validate and set new value to the CyAttributes.
*/
public class DataEditAction extends AbstractUndoableEdit {
private final String attrKey;
private final String attrName;
private final Object old_value;
private final Object new_value;
private final DataObjectType objectType;
private final DataTableModel tableModel;
private boolean valid = false;
private ValidatedObjectAndEditString objectAndEditString = null;
/**
* Creates a new DataEditAction object.
*
* @param table DOCUMENT ME!
* @param attrKey DOCUMENT ME!
* @param attrName DOCUMENT ME!
* @param keys DOCUMENT ME!
* @param old_value DOCUMENT ME!
* @param new_value DOCUMENT ME!
* @param graphObjectType DOCUMENT ME!
*/
public DataEditAction(DataTableModel table, String attrKey, String attrName,
Object old_value, Object new_value, DataObjectType graphObjectType)
{
this.tableModel = table;
this.attrKey = attrKey;
this.attrName = attrName;
this.old_value = old_value;
this.new_value = new_value;
this.objectType = graphObjectType;
redo();
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getPresentationName() {
return attrKey + " attribute " + attrName + " changed.";
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getRedoPresentationName() {
return "Redo: " + attrKey + ":" + attrName + " to:" + new_value + " from " + old_value;
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public String getUndoPresentationName() {
return "Undo: " + attrKey + ":" + attrName + " back to:" + old_value + " from " + new_value;
}
public ValidatedObjectAndEditString getValidatedObjectAndEditString() { return objectAndEditString; }
/**
* Set attribute value. Input validater is added.
*
* @param id
* @param att
* @param newValue
*/
private void setAttributeValue(final String id, final String attrName, final Object newValue) {
valid = false;
if (newValue == null)
return;
final CyAttributes attrs = objectType.getAssociatedAttributes();
// Error message for the popup dialog.
String errMessage = null;
// Change object to String
final String newValueStr = newValue.toString().trim();
final byte targetType = attrs.getType(attrName);
if (targetType == CyAttributes.TYPE_INTEGER)
handleInteger(newValueStr, attrs, id);
else if (targetType == CyAttributes.TYPE_FLOATING)
handleDouble(newValueStr, attrs, id);
else if (targetType == CyAttributes.TYPE_BOOLEAN)
handleBoolean(newValueStr, attrs, id);
else if (targetType == CyAttributes.TYPE_STRING)
handleString(newValueStr, attrs, id);
else if (targetType == CyAttributes.TYPE_SIMPLE_LIST)
handleList(newValueStr, attrs, id);
else if (targetType == CyAttributes.TYPE_SIMPLE_MAP)
handleMap(newValueStr, attrs, id);
}
private void handleInteger(final String newValueStr, final CyAttributes attrs, final String id) {
// Deal with equations first:
if (newValueStr != null && newValueStr.length() >= 2 && newValueStr.charAt(0) == '=') {
final Equation equation = parseEquation(newValueStr, attrs, id, attrName);
if (equation == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#PARSE");
attrs.deleteAttribute(id, attrName);
return;
}
final Class returnType = equation.getType();
if (returnType != Long.class && returnType != Double.class && returnType != Boolean.class && returnType != Object.class) {
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " but should be of type Integer!");
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
return;
}
attrs.setAttribute(id, attrName, equation);
final Object attrValue = attrs.getAttribute(id, attrName);
String errorMessage = attrs.getLastEquationError();
if (errorMessage != null)
errorMessage = "#ERROR(" + errorMessage + ")";
objectAndEditString = new ValidatedObjectAndEditString(attrValue, newValueStr, errorMessage);
valid = true;
return;
}
Integer newIntVal;
try {
newIntVal = Integer.valueOf(newValueStr);
attrs.setAttribute(id, attrName, newIntVal);
objectAndEditString = new ValidatedObjectAndEditString(newIntVal);
valid = true;
} catch (final Exception e) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#ERROR");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Attribute " + attrName
+ " should be an Integer (or the number is too big/small).");
}
}
private void handleDouble(final String newValueStr, final CyAttributes attrs, final String id) {
// Deal with equations first:
if (newValueStr != null && newValueStr.length() >= 2 && newValueStr.charAt(0) == '=') {
final Equation equation = parseEquation(newValueStr, attrs, id, attrName);
if (equation == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#PARSE");
attrs.deleteAttribute(id, attrName);
return;
}
final Class returnType = equation.getType();
if (returnType != Double.class && returnType != Long.class && returnType != Boolean.class && returnType != Object.class) {
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " but should be of type Floating Point!");
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
return;
}
attrs.setAttribute(id, attrName, equation);
final Object attrValue = attrs.getAttribute(id, attrName);
String errorMessage = attrs.getLastEquationError();
if (errorMessage != null)
errorMessage = "#ERROR(" + errorMessage + ")";
objectAndEditString = new ValidatedObjectAndEditString(attrValue, newValueStr, errorMessage);
valid = true;
return;
}
Double newDblVal;
try {
newDblVal = Double.valueOf(newValueStr);
attrs.setAttribute(id, attrName, newDblVal);
objectAndEditString = new ValidatedObjectAndEditString(newDblVal);
valid = true;
} catch (final Exception e) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#ERROR");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Attribute " + attrName
+ " should be a floating point number (or the number is too big/small).");
}
}
private void handleBoolean(final String newValueStr, final CyAttributes attrs, final String id) {
// Deal with equations first:
if (newValueStr != null && newValueStr.length() >= 2 && newValueStr.charAt(0) == '=') {
final Equation equation = parseEquation(newValueStr, attrs, id, attrName);
if (equation == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#PARSE");
attrs.deleteAttribute(id, attrName);
return;
}
final Class returnType = equation.getType();
if (returnType != Boolean.class && returnType != Long.class && returnType != Double.class && returnType != Object.class) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " but should be of type Boolean!");
return;
}
attrs.setAttribute(id, attrName, equation);
final Object attrValue = attrs.getAttribute(id, attrName);
String errorMessage = attrs.getLastEquationError();
if (errorMessage != null)
errorMessage = "#ERROR(" + errorMessage + ")";
objectAndEditString = new ValidatedObjectAndEditString(attrValue, newValueStr, errorMessage);
valid = true;
return;
}
Boolean newBoolVal = false;
try {
newBoolVal = Boolean.valueOf(newValueStr);
attrs.setAttribute(id, attrName, newBoolVal);
objectAndEditString = new ValidatedObjectAndEditString(newBoolVal);
valid = true;
} catch (final Exception e) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#ERROR");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Attribute " + attrName + " should be a boolean value (true/false).");
}
}
private void handleString(final String newValueStr, final CyAttributes attrs, final String id) {
final String newStrVal = replaceCStyleEscapes(newValueStr);
// Deal with equations first:
if (newValueStr != null && newValueStr.length() >= 2 && newValueStr.charAt(0) == '=') {
final Equation equation = parseEquation(newStrVal, attrs, id, attrName);
if (equation == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newStrVal, "#PARSE");
attrs.deleteAttribute(id, attrName);
return;
}
attrs.setAttribute(id, attrName, equation);
objectAndEditString = new ValidatedObjectAndEditString(attrs.getAttribute(id, attrName), equation.toString());
final Object attrValue = attrs.getAttribute(id, attrName);
String errorMessage = attrs.getLastEquationError();
if (errorMessage != null)
errorMessage = "#ERROR(" + errorMessage + ")";
objectAndEditString = new ValidatedObjectAndEditString(attrValue, newValueStr, errorMessage);
valid = true;
return;
}
attrs.setAttribute(id, attrName, newStrVal);
objectAndEditString = new ValidatedObjectAndEditString(newStrVal);
valid = true;
}
private void handleList(final String newValueStr, final CyAttributes attrs, final String id) {
// Deal with equations first:
if (newValueStr != null && newValueStr.length() >= 2 && newValueStr.charAt(0) == '=') {
final Equation equation = parseEquation(newValueStr, attrs, id, attrName);
if (equation == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#PARSE");
attrs.deleteAttribute(id, attrName);
return;
}
final Class returnType = equation.getType();
if (!FunctionUtil.isSomeKindOfList(returnType) && returnType != Object.class) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " but should be of type List!");
return;
}
final byte listElementType = attrs.getListElementType(attrName);
if (returnType == DoubleList.class && listElementType != CyAttributes.TYPE_FLOATING
|| returnType == LongList.class && listElementType != CyAttributes.TYPE_INTEGER
|| returnType == StringList.class && listElementType != CyAttributes.TYPE_STRING
|| returnType == BooleanList.class && listElementType != CyAttributes.TYPE_BOOLEAN)
{
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " which is the wrong type of list!");
return;
}
attrs.setListAttribute(id, attrName, equation);
final Object attrValue = attrs.getAttribute(id, attrName);
String errorMessage = attrs.getLastEquationError();
if (errorMessage != null)
errorMessage = "#ERROR(" + errorMessage + ")";
objectAndEditString = new ValidatedObjectAndEditString(attrValue, newValueStr, errorMessage);
valid = true;
return;
}
final String escapedString = replaceCStyleEscapes(newValueStr);
- final List origList = attrs.getListAttribute(id, attrName);
+ final int elementType = attrs.getListElementType(attrName);
List newList = null;
- if (origList.isEmpty() || origList.get(0).getClass() == String.class)
+ switch (elementType) {
+ case CyAttributes.TYPE_STRING:
newList = parseStringListValue(escapedString);
- else if (origList.get(0).getClass() == Double.class)
+ break;
+ case CyAttributes.TYPE_FLOATING:
newList = parseDoubleListValue(escapedString);
- else if (origList.get(0).getClass() == Integer.class)
+ break;
+ case CyAttributes.TYPE_INTEGER:
newList = parseIntegerListValue(escapedString);
- else if (origList.get(0).getClass() == Boolean.class)
+ break;
+ case CyAttributes.TYPE_BOOLEAN:
newList = parseBooleanListValue(escapedString);
- else
+ break;
+ default:
throw new ClassCastException("can't determined List type!");
+ }
if (newList == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#ERROR");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Invalid list!");
return;
}
else {
attrs.setListAttribute(id, attrName, newList);
objectAndEditString = new ValidatedObjectAndEditString(escapedString);
valid = true;
}
}
private void handleMap(final String newValueStr, final CyAttributes attrs, final String id) {
// Deal with equations first:
if (newValueStr != null && newValueStr.length() >= 2 && newValueStr.charAt(0) == '=') {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#ERROR");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Error in attribute \"" + attrName
+ "\": no equations are supported for maps!");
return;
}
showErrorWindow("Map editing is not supported in this version.");
}
/**
* Assumes that "s" consists of components separated by dots.
* @returns the last component of "s" or all of "s" if there are no dots
*/
private static String getLastDotComponent(final String s) {
final int lastDotPos = s.lastIndexOf('.');
if (lastDotPos == -1)
return s;
return s.substring(lastDotPos + 1);
}
/** Does some rudimentary list syntax checking and returns the number of items in "listCandidate."
* @param listCandidate a string that will be analysed as to list-syntax conformance.
* @returns -1 if "listCandidate" does not conform to a list syntax, otherwise the number of items in the simple list.
*/
private int countListItems(final String listCandidate) {
if (listCandidate.length() < 2 || listCandidate.charAt(0) != '[' || listCandidate.charAt(listCandidate.length() - 1) != ']')
return -1;
int commaCount = 0;
for (int charIndex = 1; charIndex < listCandidate.length() - 1; ++charIndex) {
if (listCandidate.charAt(charIndex) == ',')
++commaCount;
}
return commaCount;
}
/** Attemps to convert "listCandidate" to a List of String.
* @param listCandidate hopefully a list of strings.
* @returns the List if "listCandidate" has been successfully parsed, else null.
*/
private List parseStringListValue(final String listCandidate) {
final int itemCount = countListItems(listCandidate);
if (itemCount == -1)
return null;
final String bracketlessList = listCandidate.substring(1, listCandidate.length() - 1);
final String[] items = bracketlessList.split("\\s*,\\s*");
return Arrays.asList(items);
}
/** Attemps to convert "listCandidate" to a List of Double.
* @param listCandidate hopefully a list of doubles.
* @returns the List if "listCandidate" has been successfully parsed, else null.
*/
private List parseDoubleListValue(final String listCandidate) {
final int itemCount = countListItems(listCandidate);
if (itemCount == -1)
return null;
final String bracketlessList = listCandidate.substring(1, listCandidate.length() - 1);
final String[] items = bracketlessList.split("\\s*,\\s*");
final List<Double> doubleList = new ArrayList<Double>(itemCount);
try {
for (final String item : items) {
final Double newDouble = Double.valueOf(item);
doubleList.add(newDouble);
}
} catch (final NumberFormatException e) {
return null; // At least one of the list items was not a double.
}
return doubleList;
}
/** Attemps to convert "listCandidate" to a List of Integer.
* @param listCandidate hopefully a list of ints.
* @returns the List if "listCandidate" has been successfully parsed, else null.
*/
private List parseIntegerListValue(final String listCandidate) {
final int itemCount = countListItems(listCandidate);
if (itemCount == -1)
return null;
final String bracketlessList = listCandidate.substring(1, listCandidate.length() - 1);
final String[] items = bracketlessList.split("\\s*,\\s*");
final List<Integer> intList = new ArrayList<Integer>(itemCount);
try {
for (final String item : items) {
final Integer newInteger = Integer.valueOf(item);
intList.add(newInteger);
}
} catch (final NumberFormatException e) {
return null; // At least one of the list items was not a int.
}
return intList;
}
/** Attemps to convert "listCandidate" to a List of Boolean.
* @param listCandidate hopefully a list of booleans.
* @returns the List if "listCandidate" has been successfully parsed, else null.
*/
private List parseBooleanListValue(final String listCandidate) {
final int itemCount = countListItems(listCandidate);
if (itemCount == -1)
return null;
final String bracketlessList = listCandidate.substring(1, listCandidate.length() - 1);
final String[] items = bracketlessList.split("\\s*,\\s*");
final List<Boolean> booleanList = new ArrayList<Boolean>(itemCount);
try {
for (final String item : items) {
final Boolean newBoolean = Boolean.valueOf(item);
booleanList.add(newBoolean);
}
} catch (final NumberFormatException e) {
return null; // At least one of the list items was not a boolean.
}
return booleanList;
}
private String replaceCStyleEscapes(String s) {
StringBuffer sb = new StringBuffer( s );
int index = 0;
while ( index < sb.length() ) {
if ( sb.charAt(index) == '\\' ) {
if ( sb.charAt(index+1) == 'n') {
sb.setCharAt(index,'\n');
sb.deleteCharAt(index+1);
index++;
} else if ( sb.charAt(index+1) == 'b') {
sb.setCharAt(index,'\b');
sb.deleteCharAt(index+1);
index++;
} else if ( sb.charAt(index+1) == 'r') {
sb.setCharAt(index,'\r');
sb.deleteCharAt(index+1);
index++;
} else if ( sb.charAt(index+1) == 'f') {
sb.setCharAt(index,'\f');
sb.deleteCharAt(index+1);
index++;
} else if ( sb.charAt(index+1) == 't') {
sb.setCharAt(index,'\t');
sb.deleteCharAt(index+1);
index++;
}
}
index++;
}
return sb.toString();
}
// Pop-up window for error message
private static void showErrorWindow(final String errMessage) {
JOptionPane.showMessageDialog(Cytoscape.getDesktop(), errMessage, "Invalid Value!",
JOptionPane.ERROR_MESSAGE);
}
/**
* For redo function.
*/
public void redo() {
setAttributeValue(attrKey, attrName, new_value);
}
/**
* DOCUMENT ME!
*/
public void undo() {
setAttributeValue(attrKey, attrName, old_value);
if (objectType != NETWORK) {
tableModel.setTableData();
} else {
tableModel.setNetworkTable();
}
}
/**
* DOCUMENT ME!
*
* @return DOCUMENT ME!
*/
public boolean isValid() {
return valid;
}
/**
* @returns the successfully compiled equation or null if an error occurred
*/
private Equation parseEquation(final String equation, final CyAttributes attrs, final String id,
final String currentAttrName)
{
final Map<String, Class> attribNameToTypeMap = AttrUtil.getAttrNamesAndTypes(attrs);
attribNameToTypeMap.put("ID", String.class);
final EqnCompiler compiler = new EqnCompiler();
if (!compiler.compile(equation, attribNameToTypeMap)) {
showErrorWindow("Error in equation for attribute\"" + currentAttrName + "\": "
+ compiler.getLastErrorMsg());
return null;
}
return compiler.getEquation();
}
}
| false | true | private void handleList(final String newValueStr, final CyAttributes attrs, final String id) {
// Deal with equations first:
if (newValueStr != null && newValueStr.length() >= 2 && newValueStr.charAt(0) == '=') {
final Equation equation = parseEquation(newValueStr, attrs, id, attrName);
if (equation == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#PARSE");
attrs.deleteAttribute(id, attrName);
return;
}
final Class returnType = equation.getType();
if (!FunctionUtil.isSomeKindOfList(returnType) && returnType != Object.class) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " but should be of type List!");
return;
}
final byte listElementType = attrs.getListElementType(attrName);
if (returnType == DoubleList.class && listElementType != CyAttributes.TYPE_FLOATING
|| returnType == LongList.class && listElementType != CyAttributes.TYPE_INTEGER
|| returnType == StringList.class && listElementType != CyAttributes.TYPE_STRING
|| returnType == BooleanList.class && listElementType != CyAttributes.TYPE_BOOLEAN)
{
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " which is the wrong type of list!");
return;
}
attrs.setListAttribute(id, attrName, equation);
final Object attrValue = attrs.getAttribute(id, attrName);
String errorMessage = attrs.getLastEquationError();
if (errorMessage != null)
errorMessage = "#ERROR(" + errorMessage + ")";
objectAndEditString = new ValidatedObjectAndEditString(attrValue, newValueStr, errorMessage);
valid = true;
return;
}
final String escapedString = replaceCStyleEscapes(newValueStr);
final List origList = attrs.getListAttribute(id, attrName);
List newList = null;
if (origList.isEmpty() || origList.get(0).getClass() == String.class)
newList = parseStringListValue(escapedString);
else if (origList.get(0).getClass() == Double.class)
newList = parseDoubleListValue(escapedString);
else if (origList.get(0).getClass() == Integer.class)
newList = parseIntegerListValue(escapedString);
else if (origList.get(0).getClass() == Boolean.class)
newList = parseBooleanListValue(escapedString);
else
throw new ClassCastException("can't determined List type!");
if (newList == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#ERROR");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Invalid list!");
return;
}
else {
attrs.setListAttribute(id, attrName, newList);
objectAndEditString = new ValidatedObjectAndEditString(escapedString);
valid = true;
}
}
| private void handleList(final String newValueStr, final CyAttributes attrs, final String id) {
// Deal with equations first:
if (newValueStr != null && newValueStr.length() >= 2 && newValueStr.charAt(0) == '=') {
final Equation equation = parseEquation(newValueStr, attrs, id, attrName);
if (equation == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#PARSE");
attrs.deleteAttribute(id, attrName);
return;
}
final Class returnType = equation.getType();
if (!FunctionUtil.isSomeKindOfList(returnType) && returnType != Object.class) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " but should be of type List!");
return;
}
final byte listElementType = attrs.getListElementType(attrName);
if (returnType == DoubleList.class && listElementType != CyAttributes.TYPE_FLOATING
|| returnType == LongList.class && listElementType != CyAttributes.TYPE_INTEGER
|| returnType == StringList.class && listElementType != CyAttributes.TYPE_STRING
|| returnType == BooleanList.class && listElementType != CyAttributes.TYPE_BOOLEAN)
{
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#TYPE");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Error in attribute \"" + attrName
+ "\": equation is of type " + getLastDotComponent(returnType.toString())
+ " which is the wrong type of list!");
return;
}
attrs.setListAttribute(id, attrName, equation);
final Object attrValue = attrs.getAttribute(id, attrName);
String errorMessage = attrs.getLastEquationError();
if (errorMessage != null)
errorMessage = "#ERROR(" + errorMessage + ")";
objectAndEditString = new ValidatedObjectAndEditString(attrValue, newValueStr, errorMessage);
valid = true;
return;
}
final String escapedString = replaceCStyleEscapes(newValueStr);
final int elementType = attrs.getListElementType(attrName);
List newList = null;
switch (elementType) {
case CyAttributes.TYPE_STRING:
newList = parseStringListValue(escapedString);
break;
case CyAttributes.TYPE_FLOATING:
newList = parseDoubleListValue(escapedString);
break;
case CyAttributes.TYPE_INTEGER:
newList = parseIntegerListValue(escapedString);
break;
case CyAttributes.TYPE_BOOLEAN:
newList = parseBooleanListValue(escapedString);
break;
default:
throw new ClassCastException("can't determined List type!");
}
if (newList == null) {
objectAndEditString = new ValidatedObjectAndEditString(null, newValueStr, "#ERROR");
attrs.deleteAttribute(id, attrName);
showErrorWindow("Invalid list!");
return;
}
else {
attrs.setListAttribute(id, attrName, newList);
objectAndEditString = new ValidatedObjectAndEditString(escapedString);
valid = true;
}
}
|
diff --git a/src/org/jbs/happysad/UIDhelper.java b/src/org/jbs/happysad/UIDhelper.java
index 0ea4d89..7dba479 100644
--- a/src/org/jbs/happysad/UIDhelper.java
+++ b/src/org/jbs/happysad/UIDhelper.java
@@ -1,70 +1,70 @@
package org.jbs.happysad;
import android.content.SharedPreferences;
import android.accounts.Account;
import android.accounts.AccountManager;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Toast;
public class UIDhelper{
private String USER_DATA;
public UIDhelper(){
//
}
public long getUID(){
return UIDtoken.INSTANCE.getUID();
}
public long getSetUID(SharedPreferences sp, Context ctx){
long tempID = this.getUID();
if ( tempID >=0 ){ return tempID;}
final AccountManager manager = AccountManager.get(ctx);
final Account[] accounts = manager.getAccounts();
- if (accounts.length > 1){
+ if (accounts.length >= 1){
//ok so we know there's at least one account being used.
//let's use it.
String username = new String(accounts[0].name);
//is the username is stored in shared preferences, we know that can get the UID
//get the ID given the username (this way we can save multiple users
long uid = sp.getLong("usernameLong", -1);
UIDtoken.INSTANCE.setUID(uid);
if (uid < 0){
NetHelper NH = new NetHelper();
long UID = NH.getID(username);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("usernameLong", UID);
editor.putString("usernameString", username);
editor.commit();
//then we call nethelper methods set the id from the returned thing return
UIDtoken.INSTANCE.setUID(UID);
return UID;
}
else{
//myID = sp.getLong( "usernameLong", -1);
return -1;
}
}
/*else{
Context context = ctx;
String loginPrompt = getString(R.string.error_login_message);
CharSequence text = loginPrompt;
Toast toast = Toast.makeText(context, text, 1000);
toast.show()
}*/
return -5;
}
}
| true | true | public long getSetUID(SharedPreferences sp, Context ctx){
long tempID = this.getUID();
if ( tempID >=0 ){ return tempID;}
final AccountManager manager = AccountManager.get(ctx);
final Account[] accounts = manager.getAccounts();
if (accounts.length > 1){
//ok so we know there's at least one account being used.
//let's use it.
String username = new String(accounts[0].name);
//is the username is stored in shared preferences, we know that can get the UID
//get the ID given the username (this way we can save multiple users
long uid = sp.getLong("usernameLong", -1);
UIDtoken.INSTANCE.setUID(uid);
if (uid < 0){
NetHelper NH = new NetHelper();
long UID = NH.getID(username);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("usernameLong", UID);
editor.putString("usernameString", username);
editor.commit();
//then we call nethelper methods set the id from the returned thing return
UIDtoken.INSTANCE.setUID(UID);
return UID;
}
else{
//myID = sp.getLong( "usernameLong", -1);
return -1;
}
}
/*else{
Context context = ctx;
String loginPrompt = getString(R.string.error_login_message);
CharSequence text = loginPrompt;
Toast toast = Toast.makeText(context, text, 1000);
toast.show()
}*/
| public long getSetUID(SharedPreferences sp, Context ctx){
long tempID = this.getUID();
if ( tempID >=0 ){ return tempID;}
final AccountManager manager = AccountManager.get(ctx);
final Account[] accounts = manager.getAccounts();
if (accounts.length >= 1){
//ok so we know there's at least one account being used.
//let's use it.
String username = new String(accounts[0].name);
//is the username is stored in shared preferences, we know that can get the UID
//get the ID given the username (this way we can save multiple users
long uid = sp.getLong("usernameLong", -1);
UIDtoken.INSTANCE.setUID(uid);
if (uid < 0){
NetHelper NH = new NetHelper();
long UID = NH.getID(username);
SharedPreferences.Editor editor = sp.edit();
editor.putLong("usernameLong", UID);
editor.putString("usernameString", username);
editor.commit();
//then we call nethelper methods set the id from the returned thing return
UIDtoken.INSTANCE.setUID(UID);
return UID;
}
else{
//myID = sp.getLong( "usernameLong", -1);
return -1;
}
}
/*else{
Context context = ctx;
String loginPrompt = getString(R.string.error_login_message);
CharSequence text = loginPrompt;
Toast toast = Toast.makeText(context, text, 1000);
toast.show()
}*/
|
diff --git a/de.walware.docmlet.tex.core/src/de/walware/docmlet/tex/internal/core/builder/TexProjectBuild.java b/de.walware.docmlet.tex.core/src/de/walware/docmlet/tex/internal/core/builder/TexProjectBuild.java
index 9253e51..a2761ea 100644
--- a/de.walware.docmlet.tex.core/src/de/walware/docmlet/tex/internal/core/builder/TexProjectBuild.java
+++ b/de.walware.docmlet.tex.core/src/de/walware/docmlet/tex/internal/core/builder/TexProjectBuild.java
@@ -1,344 +1,346 @@
/*=============================================================================#
# Copyright (c) 2014 Stephan Wahlbrink (WalWare.de) 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:
# Stephan Wahlbrink - initial API and implementation
#=============================================================================*/
package de.walware.docmlet.tex.internal.core.builder;
import java.util.ArrayList;
import java.util.Collection;
import java.util.List;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.resources.IResourceDelta;
import org.eclipse.core.resources.IResourceDeltaVisitor;
import org.eclipse.core.resources.IResourceVisitor;
import org.eclipse.core.resources.IncrementalProjectBuilder;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IStatus;
import org.eclipse.core.runtime.MultiStatus;
import org.eclipse.core.runtime.Status;
import org.eclipse.core.runtime.SubMonitor;
import org.eclipse.core.runtime.content.IContentDescription;
import org.eclipse.core.runtime.content.IContentType;
import org.eclipse.osgi.util.NLS;
import de.walware.ecommons.ltk.IExtContentTypeManager;
import de.walware.ecommons.ltk.IModelManager;
import de.walware.ecommons.ltk.ISourceUnit;
import de.walware.ecommons.ltk.LTK;
import de.walware.ecommons.ltk.core.IModelTypeDescriptor;
import de.walware.docmlet.tex.core.TexBuildParticipant;
import de.walware.docmlet.tex.core.TexCore;
import de.walware.docmlet.tex.core.model.ILtxSourceUnit;
import de.walware.docmlet.tex.core.model.ILtxWorkspaceSourceUnit;
import de.walware.docmlet.tex.core.model.LtxSuModelContainer;
import de.walware.docmlet.tex.internal.core.TexCorePlugin;
import de.walware.docmlet.tex.internal.core.TexProject;
import de.walware.docmlet.tex.internal.core.model.LtxModelManager;
public class TexProjectBuild extends TexProjectTask
implements IResourceVisitor, IResourceDeltaVisitor {
private final static class VirtualSourceUnit {
private final IFile file;
private final String modelTypeId;
public VirtualSourceUnit(final IFile file, final String modelTypeId) {
this.file= file;
this.modelTypeId= modelTypeId;
}
public IFile getResource() {
return this.file;
}
public String getModelTypeId() {
return this.modelTypeId;
}
@Override
public int hashCode() {
return this.file.hashCode();
}
@Override
public String toString() {
return this.file.toString();
}
}
private final IExtContentTypeManager modelRegistry= LTK.getExtContentTypeManager();
private final MultiStatus status;
private final List<ILtxWorkspaceSourceUnit> updatedLtxUnits;
private final List<VirtualSourceUnit> removedLtxFiles;
private SubMonitor visitProgress;
public TexProjectBuild(final TexProjectBuilder builder) {
super(builder);
this.status= new MultiStatus(TexCore.PLUGIN_ID, 0,
NLS.bind("TeX build status for ''{0}''", getTexProject().getProject().getName() ),
null );
this.updatedLtxUnits= new ArrayList<>();
this.removedLtxFiles= new ArrayList<>();
}
private void dispose(final SubMonitor progress) {
progress.setWorkRemaining(this.updatedLtxUnits.size());
for (final ILtxSourceUnit unit : this.updatedLtxUnits) {
unit.disconnect(progress.newChild(1));
}
}
public void build(final int kind,
final SubMonitor progress) throws CoreException {
try {
progress.setTaskName(NLS.bind("Preparing TeX build for ''{0}''", getTexProject().getProject().getName()));
progress.setWorkRemaining(10 + 20 + 80 + 10);
final IResourceDelta delta;
switch (kind) {
case IncrementalProjectBuilder.AUTO_BUILD:
case IncrementalProjectBuilder.INCREMENTAL_BUILD:
delta= getTexProjectBuilder().getDelta(getTexProject().getProject());
progress.worked(10);
break;
default:
delta= null;
}
if (progress.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
progress.setWorkRemaining(20 + 80 + 10);
this.visitProgress= progress.newChild(20);
if (delta != null) {
setBuildType(IncrementalProjectBuilder.INCREMENTAL_BUILD);
delta.accept(this);
}
else {
setBuildType(IncrementalProjectBuilder.FULL_BUILD);
getTexProject().getProject().accept(this);
}
this.visitProgress= null;
if (progress.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
progress.setTaskName(NLS.bind("Analyzing LaTeX file(s) of ''{0}''", getTexProject().getProject().getName()));
processLtxFiles(progress.newChild(80));
}
finally {
progress.setWorkRemaining(10);
dispose(progress.newChild(10));
if (!this.status.isOK()) {
TexCorePlugin.log(this.status);
}
}
}
@Override
public boolean visit(final IResourceDelta delta) throws CoreException {
final IResource resource= delta.getResource();
if (resource.getType() == IResource.FILE) {
if (this.visitProgress.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
this.visitProgress.setWorkRemaining(100);
try {
switch (delta.getKind()) {
case IResourceDelta.ADDED:
case IResourceDelta.CHANGED:
visitFileAdded((IFile) resource, delta, this.visitProgress.newChild(1));
break;
case IResourceDelta.REMOVED:
visitFileRemove((IFile) resource, delta, this.visitProgress.newChild(1));
break;
default:
break;
}
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
"An error occurred when checking file ''{0}''", e ));
}
}
return true;
}
@Override
public boolean visit(final IResource resource) throws CoreException {
if (resource.getType() == IResource.FILE) {
this.visitProgress.setWorkRemaining(100);
visitFileAdded((IFile) resource, null, this.visitProgress.newChild(1));
}
return true;
}
private void visitFileAdded(final IFile file, final IResourceDelta delta,
final SubMonitor progress) throws CoreException {
final IContentDescription contentDescription= file.getContentDescription();
if (contentDescription == null) {
return;
}
final IContentType contentType= contentDescription.getContentType();
if (contentType == null) {
return;
}
if (contentType.isKindOf(LTX_CONTENT_TYPE)) {
final IModelTypeDescriptor modelType= this.modelRegistry.getModelTypeForContentType(contentType.getId());
if (modelType == null) {
clearLtx(file, null);
return;
}
final ISourceUnit unit= LTK.getSourceUnitManager().getSourceUnit(
modelType.getId(), LTK.PERSISTENCE_CONTEXT, file, true, progress );
if (unit instanceof ILtxWorkspaceSourceUnit) {
this.updatedLtxUnits.add((ILtxWorkspaceSourceUnit) unit);
}
}
}
private void visitFileRemove(final IFile file, final IResourceDelta delta,
final SubMonitor progress) throws CoreException {
final IContentDescription contentDescription= file.getContentDescription();
if (contentDescription == null) {
return;
}
final IContentType contentType= contentDescription.getContentType();
if (contentType == null) {
return;
}
if (contentType.isKindOf(LTX_CONTENT_TYPE)) {
final IModelTypeDescriptor modelType= this.modelRegistry.getModelTypeForContentType(contentType.getId());
final VirtualSourceUnit unit= new VirtualSourceUnit(file, (modelType != null) ? modelType.getId() : null);
this.removedLtxFiles.add(unit);
if ((delta != null && (delta.getFlags() & IResourceDelta.MOVED_TO) != 0)) {
final IResource movedTo= file.getWorkspace().getRoot().findMember(delta.getMovedToPath());
if (movedTo instanceof IFile) {
final TexProject movedToProject= TexProject.getTexProject(movedTo.getProject());
if (modelType == null
|| movedToProject == null || movedToProject == getTexProject()
|| !getTexProjectBuilder().hasBeenBuilt(movedToProject.getProject()) ) {
clearLtx((IFile) movedTo, getParticipant(unit.getModelTypeId()));
}
}
}
}
}
private void processLtxFiles(final SubMonitor progress) throws CoreException {
progress.setWorkRemaining(2);
final LtxModelManager ltxModelManager= TexCorePlugin.getDefault().getLtxModelManager();
{ final SubMonitor sub= progress.newChild(1);
int subRemaining= this.removedLtxFiles.size() + this.updatedLtxUnits.size() * 5;
sub.setWorkRemaining(subRemaining);
for (final VirtualSourceUnit unit : this.removedLtxFiles) {
try {
final TexBuildParticipant participant= getParticipant(unit.getModelTypeId());
// >> remove from LTX index
if (participant != null) {
participant.ltxUnitRemoved(unit.getResource(), sub.newChild(1));
}
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
NLS.bind("An error occurred when processing removed file ''{0}''.", unit.getResource()),
e ));
}
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
sub.setWorkRemaining((subRemaining-= 1));
}
if (!this.updatedLtxUnits.isEmpty()) {
final LtxBuildReconciler ltxReconciler= new LtxBuildReconciler(ltxModelManager);
for (final ILtxWorkspaceSourceUnit unit : this.updatedLtxUnits) {
try {
final TexBuildParticipant participant= getParticipant(unit.getModelTypeId());
clearLtx((IFile) unit.getResource(), participant);
final LtxSuModelContainer<ILtxSourceUnit> adapter= (LtxSuModelContainer<ILtxSourceUnit>) unit.getAdapter(LtxSuModelContainer.class);
if (adapter != null) {
ltxReconciler.reconcile(adapter, IModelManager.MODEL_FILE, sub.newChild(3));
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
}
// >> update LTX index
if (participant != null && participant.isEnabled()) {
participant.ltxUnitUpdated(unit, sub.newChild(2));
}
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
NLS.bind("An error occurred when processing file ''{0}''.", unit.getResource()),
e ));
}
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
sub.setWorkRemaining((subRemaining-= 5));
}
}
}
{ final SubMonitor sub= progress.newChild(1);
final Collection<TexBuildParticipant> participants= getParticipants();
sub.setWorkRemaining(participants.size());
for (final TexBuildParticipant participant : participants) {
- try {
- participant.ltxFinished(sub.newChild(1));
- }
- catch (final Exception e) {
- this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
- NLS.bind("An error occurred when processing LaTeX file(s) in ''{0}''.", getTexProject().getProject().getName()),
- e ));
+ if (participant.isEnabled()) {
+ try {
+ participant.ltxFinished(sub.newChild(1));
+ }
+ catch (final Exception e) {
+ this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
+ NLS.bind("An error occurred when processing LaTeX file(s) in ''{0}''.", getTexProject().getProject().getName()),
+ e ));
+ }
}
}
}
}
private void clearLtx(final IFile file, final TexBuildParticipant partitipant) throws CoreException {
if (partitipant != null) {
partitipant.clear(file);
}
}
}
| true | true | private void processLtxFiles(final SubMonitor progress) throws CoreException {
progress.setWorkRemaining(2);
final LtxModelManager ltxModelManager= TexCorePlugin.getDefault().getLtxModelManager();
{ final SubMonitor sub= progress.newChild(1);
int subRemaining= this.removedLtxFiles.size() + this.updatedLtxUnits.size() * 5;
sub.setWorkRemaining(subRemaining);
for (final VirtualSourceUnit unit : this.removedLtxFiles) {
try {
final TexBuildParticipant participant= getParticipant(unit.getModelTypeId());
// >> remove from LTX index
if (participant != null) {
participant.ltxUnitRemoved(unit.getResource(), sub.newChild(1));
}
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
NLS.bind("An error occurred when processing removed file ''{0}''.", unit.getResource()),
e ));
}
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
sub.setWorkRemaining((subRemaining-= 1));
}
if (!this.updatedLtxUnits.isEmpty()) {
final LtxBuildReconciler ltxReconciler= new LtxBuildReconciler(ltxModelManager);
for (final ILtxWorkspaceSourceUnit unit : this.updatedLtxUnits) {
try {
final TexBuildParticipant participant= getParticipant(unit.getModelTypeId());
clearLtx((IFile) unit.getResource(), participant);
final LtxSuModelContainer<ILtxSourceUnit> adapter= (LtxSuModelContainer<ILtxSourceUnit>) unit.getAdapter(LtxSuModelContainer.class);
if (adapter != null) {
ltxReconciler.reconcile(adapter, IModelManager.MODEL_FILE, sub.newChild(3));
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
}
// >> update LTX index
if (participant != null && participant.isEnabled()) {
participant.ltxUnitUpdated(unit, sub.newChild(2));
}
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
NLS.bind("An error occurred when processing file ''{0}''.", unit.getResource()),
e ));
}
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
sub.setWorkRemaining((subRemaining-= 5));
}
}
}
{ final SubMonitor sub= progress.newChild(1);
final Collection<TexBuildParticipant> participants= getParticipants();
sub.setWorkRemaining(participants.size());
for (final TexBuildParticipant participant : participants) {
try {
participant.ltxFinished(sub.newChild(1));
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
NLS.bind("An error occurred when processing LaTeX file(s) in ''{0}''.", getTexProject().getProject().getName()),
e ));
}
}
}
}
| private void processLtxFiles(final SubMonitor progress) throws CoreException {
progress.setWorkRemaining(2);
final LtxModelManager ltxModelManager= TexCorePlugin.getDefault().getLtxModelManager();
{ final SubMonitor sub= progress.newChild(1);
int subRemaining= this.removedLtxFiles.size() + this.updatedLtxUnits.size() * 5;
sub.setWorkRemaining(subRemaining);
for (final VirtualSourceUnit unit : this.removedLtxFiles) {
try {
final TexBuildParticipant participant= getParticipant(unit.getModelTypeId());
// >> remove from LTX index
if (participant != null) {
participant.ltxUnitRemoved(unit.getResource(), sub.newChild(1));
}
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
NLS.bind("An error occurred when processing removed file ''{0}''.", unit.getResource()),
e ));
}
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
sub.setWorkRemaining((subRemaining-= 1));
}
if (!this.updatedLtxUnits.isEmpty()) {
final LtxBuildReconciler ltxReconciler= new LtxBuildReconciler(ltxModelManager);
for (final ILtxWorkspaceSourceUnit unit : this.updatedLtxUnits) {
try {
final TexBuildParticipant participant= getParticipant(unit.getModelTypeId());
clearLtx((IFile) unit.getResource(), participant);
final LtxSuModelContainer<ILtxSourceUnit> adapter= (LtxSuModelContainer<ILtxSourceUnit>) unit.getAdapter(LtxSuModelContainer.class);
if (adapter != null) {
ltxReconciler.reconcile(adapter, IModelManager.MODEL_FILE, sub.newChild(3));
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
}
// >> update LTX index
if (participant != null && participant.isEnabled()) {
participant.ltxUnitUpdated(unit, sub.newChild(2));
}
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
NLS.bind("An error occurred when processing file ''{0}''.", unit.getResource()),
e ));
}
if (sub.isCanceled()) {
throw new CoreException(Status.CANCEL_STATUS);
}
sub.setWorkRemaining((subRemaining-= 5));
}
}
}
{ final SubMonitor sub= progress.newChild(1);
final Collection<TexBuildParticipant> participants= getParticipants();
sub.setWorkRemaining(participants.size());
for (final TexBuildParticipant participant : participants) {
if (participant.isEnabled()) {
try {
participant.ltxFinished(sub.newChild(1));
}
catch (final Exception e) {
this.status.add(new Status(IStatus.ERROR, TexCore.PLUGIN_ID, 0,
NLS.bind("An error occurred when processing LaTeX file(s) in ''{0}''.", getTexProject().getProject().getName()),
e ));
}
}
}
}
}
|
diff --git a/Power/src/Power.java b/Power/src/Power.java
index 8e2f209..8a6853c 100644
--- a/Power/src/Power.java
+++ b/Power/src/Power.java
@@ -1,20 +1,20 @@
// Compute integer powers of 2.
class Power {
public static void main(String args[]) {
int e;
int result;
for (int i = 0; i < 10; i++) {
- result = i;
+ result = 1;
e = i;
while (e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i +
" power is " + result);
}
}
}
| true | true | public static void main(String args[]) {
int e;
int result;
for (int i = 0; i < 10; i++) {
result = i;
e = i;
while (e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i +
" power is " + result);
}
}
| public static void main(String args[]) {
int e;
int result;
for (int i = 0; i < 10; i++) {
result = 1;
e = i;
while (e > 0) {
result *= 2;
e--;
}
System.out.println("2 to the " + i +
" power is " + result);
}
}
|
diff --git a/E-Adventure/src/es/eucm/eadventure/editor/gui/structurepanel/EffectsStructurePanel.java b/E-Adventure/src/es/eucm/eadventure/editor/gui/structurepanel/EffectsStructurePanel.java
index 934ee694..a647d699 100644
--- a/E-Adventure/src/es/eucm/eadventure/editor/gui/structurepanel/EffectsStructurePanel.java
+++ b/E-Adventure/src/es/eucm/eadventure/editor/gui/structurepanel/EffectsStructurePanel.java
@@ -1,482 +1,482 @@
/**
* <e-Adventure> is an <e-UCM> research project. <e-UCM>, Department of Software
* Engineering and Artificial Intelligence. Faculty of Informatics, Complutense
* University of Madrid (Spain).
*
* @author Del Blanco, A., Marchiori, E., Torrente, F.J. (alphabetical order) *
* @author L�pez Ma�as, E., P�rez Padilla, F., Sollet, E., Torijano, B. (former
* developers by alphabetical order)
* @author Moreno-Ger, P. & Fern�ndez-Manj�n, B. (directors)
* @year 2009 Web-site: http://e-adventure.e-ucm.es
*/
/*
* Copyright (C) 2004-2009 <e-UCM> research group
*
* This file is part of <e-Adventure> project, an educational game & game-like
* simulation authoring tool, available at http://e-adventure.e-ucm.es.
*
* <e-Adventure> 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.
*
* <e-Adventure> 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
* <e-Adventure>; if not, write to the Free Software Foundation, Inc., 59 Temple
* Place, Suite 330, Boston, MA 02111-1307 USA
*
*/
package es.eucm.eadventure.editor.gui.structurepanel;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import javax.swing.BorderFactory;
import javax.swing.Icon;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JPanel;
import javax.swing.SwingConstants;
import javax.swing.border.Border;
import javax.swing.event.ListSelectionEvent;
import javax.swing.event.ListSelectionListener;
import es.eucm.eadventure.common.gui.TC;
import es.eucm.eadventure.editor.gui.editdialogs.SelectEffectsDialog;
import es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects.ChangesInSceneStructureListElement;
import es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects.EffectsStructureListElement;
import es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects.FeedbackStructureListElement;
import es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects.GameStateStructureListElement;
import es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects.MainStructureListElement;
import es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects.MiscelaneousStructureListElement;
import es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects.MultimediaStructureListElement;
import es.eucm.eadventure.editor.gui.structurepanel.structureelements.Effects.TriggerStructureListElement;
/**
* Extends structure panel to adapt to select effects dialog
*
*/
public class EffectsStructurePanel extends StructurePanel {
/**
*
*/
private static final long serialVersionUID = 1L;
private static final String ACTIVATE_URL = "effects_short/Effects_Activate.html";
private static final String DEACTIVATE_URL = "effects_short/Effects_Deactivate.html";
private static final String INCR_URL = "effects_short/Effects_Increment.html";
private static final String DECR_URL = "effects_short/Effects_Decrement.html";
private static final String SET_URL = "effects_short/Effects_Setvar.html";
private static final String MACRO_URL = "effects_short/Effects_Macro.html";
private static final String CONSUME_URL = "effects_short/Effects_Consume.html";
private static final String GENERATE_URL = "effects_short/Effects_Generate.html";
private static final String CANCEL_URL = "effects_short/Effects_Cancel.html";
private static final String SP_PLAYER_URL = "effects_short/Effects_SP_Player.html";
private static final String SP_NPC_URL = "effects_short/Effects_SP_NPC.html";
private static final String BOOK_URL = "effects_short/Effects_Book.html";
private static final String SOUND_URL = "effects_short/Effects_Audio.html";
private static final String ANIMATION_URL = "effects_short/Effects_Animation.html";
private static final String MV_PLAYER_URL = "effects_short/Effects_MV_Player.html";
private static final String MV_NPC_URL = "effects_short/Effects_MV_NPC.html";
private static final String CONV_URL = "effects_short/Effects_Conversation.html";
private static final String CUTSCENE_URL = "effects_short/Effects_Cutscene.html";
private static final String SCENE_URL = "effects_short/Effects_Scene.html";
private static final String LAST_SCENE_URL = "effects_short/Effects_LastScene.html";
private static final String RAMDON_URL = "effects_short/Effects_Random.html";
private static final String TEXT_URL = "effects_short/Effects_ShowText.html";
private static final String TIME_URL = "effects_short/Effects_WaitTime.html";
private static final String HIGHLIGHT_URL = "effects_short/Effects_HighlightItem.html";
private static final String MOVE_OBJECT_URL = "effects_short/Effects_MoveObject.html";
private EffectInfoPanel infoPanel;
private boolean showAll;
private SelectEffectsDialog dialog;
/*
* Constants for icon size in buttons. Three sizes are available: SMALL (16x16), MEDIUM (32x32) and LARGE (64x64)
*/
public static final int ICON_SIZE_SMALL = 0;
public static final int ICON_SIZE_MEDIUM = 1;
public static final int ICON_SIZE_LARGE = 2;
public static final int ICON_SIZE_LARGE_HOT = 3;
private static String getIconBasePath( int size ) {
if( size == ICON_SIZE_SMALL )
return "img/icons/effects/16x16/";
else if( size == ICON_SIZE_LARGE )
return "img/icons/effects/64x64/";
else if( size == ICON_SIZE_LARGE_HOT )
return "img/icons/effects/64x64-hot/";
else
return "img/icons/effects/32x32/";
}
public static Icon getEffectIcon( String name, int size ) {
Icon effectIcon = null;
if( name.equals( TC.get( "Effect.Activate" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "activate.png" );
}
else if( name.equals( TC.get( "Effect.Deactivate" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "deactivate.png" );
}
else if( name.equals( TC.get( "Effect.SetValue" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "set-value.png" );
}
else if( name.equals( TC.get( "Effect.IncrementVar" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "increment.png" );
}
else if( name.equals( TC.get( "Effect.DecrementVar" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "decrement.png" );
}
else if( name.equals( TC.get( "Effect.MacroReference" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "macro.png" );
}
else if( name.equals( TC.get( "Effect.ConsumeObject" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "consume-object.png" );
}
else if( name.equals( TC.get( "Effect.GenerateObject" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "generate-object.png" );
}
else if( name.equals( TC.get( "Effect.CancelAction" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "cancel-action.png" );
}
else if( name.equals( TC.get( "Effect.SpeakPlayer" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "speak-player.png" );
}
else if( name.equals( TC.get( "Effect.SpeakCharacter" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "speak-npc.png" );
}
else if( name.equals( TC.get( "Effect.TriggerBook" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-book.png" );
}
else if( name.equals( TC.get( "Effect.PlaySound" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "play-sound.png" );
}
else if( name.equals( TC.get( "Effect.PlayAnimation" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "play-animation.png" );
}
else if( name.equals( TC.get( "Effect.MovePlayer" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-player.png" );
}
else if( name.equals( TC.get( "Effect.MoveCharacter" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-npc.png" );
}
else if( name.equals( TC.get( "Effect.TriggerConversation" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-conversation.png" );
}
else if( name.equals( TC.get( "Effect.TriggerCutscene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-cutscene.png" );
}
else if( name.equals( TC.get( "Effect.TriggerScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-scene.png" );
}
else if( name.equals( TC.get( "Effect.TriggerLastScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-last-scene.png" );
}
else if( name.equals( TC.get( "Effect.RandomEffect" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "random-effect.png" );
}
else if( name.equals( TC.get( "Effect.ShowText" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "show-text.png" );
}
else if( name.equals( TC.get( "Effect.WaitTime" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "wait.png" );
}
else if (name.equals( TC.get( "Effect.HighlightItem" ) )) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "highlight-item.png");
}
else if (name.equals( TC.get( "Effect.MoveObject" ) )) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-object.png");
}
else if( name.equals( TC.get( "EffectsGroup.GameState" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "game-state.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Multimedia" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "multimedia.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Miscellaneous" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "miscellaneous.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Trigger" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-events.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Feedback" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "feedback.png" );
}
else if( name.equals( TC.get( "EffectsGroup.ChangeInScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "changes-in-scene.png" );
}
- else if( name.equals( TC.get( "EffectsGroup.Main.png" ) ) ) {
+ else if( name.equals( TC.get( "EffectsGroup.Main" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "effects" );
}
// when this method is called for structure list effects
else
effectIcon = new ImageIcon( getIconBasePath( size ) + "effects" );
return effectIcon;
}
public EffectsStructurePanel( boolean showAll, SelectEffectsDialog dialog ) {
super( null, 30, 55 );
this.showAll = showAll;
this.dialog = dialog;
infoPanel = new EffectInfoPanel( );
recreateElements( );
//StructureControl.getInstance().setStructurePanel(this);
changeEffectEditPanel( ( (EffectsStructureListElement) structureElements.get( 0 ) ).getPath( ) );
}
public String getSelectedEffect( ) {
if( /*selectedElement==0 ||*/list.getSelectedRow( ) == -1 )
return null;
return structureElements.get( selectedElement ).getChild( list.getSelectedRow( ) ).getName( );
}
@Override
public void recreateElements( ) {
structureElements.clear( );
if( showAll )
structureElements.add( new MainStructureListElement( ) );
else {
structureElements.add( new GameStateStructureListElement( ) );
structureElements.add( new MultimediaStructureListElement( ) );
structureElements.add( new FeedbackStructureListElement( ) );
structureElements.add( new TriggerStructureListElement( ) );
structureElements.add( new ChangesInSceneStructureListElement( ) );
structureElements.add( new MiscelaneousStructureListElement( ) );
}
update( );
}
@Override
public void update( ) {
super.update( );
int i = 0;
removeAll( );
for( StructureListElement element : structureElements ) {
if( i == selectedElement )
add( createSelectedElementPanel( element, i ), new Integer( element.getChildCount( ) != 0 ? -1 : 40 ) );
else {
button = new JButton( element.getName( ), element.getIcon( ) );
button.setHorizontalAlignment( SwingConstants.LEFT );
Border b1 = BorderFactory.createRaisedBevelBorder( );
Border b2 = BorderFactory.createEmptyBorder( 3, 10, 3, 10 );
button.setBorder( BorderFactory.createCompoundBorder( b1, b2 ) );
button.setContentAreaFilled( false );
button.addActionListener( new ListElementButtonActionListener( i ) );
button.setFocusable( false );
if( i < selectedElement )
//add(button, new Integer(selectedElement == 0?15:35));
add( button, new Integer( 35 ) );
else if( i > selectedElement )
//add(button, new Integer(selectedElement == 0?15:35));
add( button, new Integer( 35 ) );
}
i++;
}
this.updateUI( );
}
@Override
protected JPanel createSelectedElementPanel( final StructureListElement element, final int index ) {
JPanel result = super.createSelectedElementPanel( element, index );
button.addActionListener( new ListElementButtonActionListener( index ) );
list.addMouseListener( new MouseAdapter( ) {
@Override
public void mouseClicked( MouseEvent e ) {
if( e.getClickCount( ) == 2 ) {
dialog.setOk( true );
}
}
} );
list.getSelectionModel( ).addListSelectionListener( new ListSelectionListener( ) {
public void valueChanged( ListSelectionEvent e ) {
if( list.getSelectedRow( ) >= 0 ) {
list.setRowHeight( 20 );
list.setRowHeight( list.getSelectedRow( ), 30 );
list.editCellAt( list.getSelectedRow( ), 0 );
changeEffectEditPanel( getSelectedEffect( ) );
}
else {
changeEffectEditPanel( ( (EffectsStructureListElement) structureElements.get( index ) ).getPath( ) );
}
}
} );
return result;
}
/**
* @return the infoPanel
*/
public EffectInfoPanel getInfoPanel( ) {
return infoPanel;
}
/**
* @param infoPanel
* the infoPanel to set
*/
public void setInfoPanel( EffectInfoPanel infoPanel ) {
this.infoPanel = infoPanel;
}
private void changeEffectEditPanel( String name ) {
String text = null;
if( name.equals( TC.get( "Effect.Activate" ) ) ) {
text = ACTIVATE_URL;
}
else if( name.equals( TC.get( "Effect.Deactivate" ) ) ) {
text = DEACTIVATE_URL;
}
else if( name.equals( TC.get( "Effect.SetValue" ) ) ) {
text = SET_URL;
}
else if( name.equals( TC.get( "Effect.IncrementVar" ) ) ) {
text = INCR_URL;
}
else if( name.equals( TC.get( "Effect.DecrementVar" ) ) ) {
text = DECR_URL;
}
else if( name.equals( TC.get( "Effect.MacroReference" ) ) ) {
text = MACRO_URL;
}
else if( name.equals( TC.get( "Effect.ConsumeObject" ) ) ) {
text = CONSUME_URL;
}
else if( name.equals( TC.get( "Effect.GenerateObject" ) ) ) {
text = GENERATE_URL;
}
else if( name.equals( TC.get( "Effect.CancelAction" ) ) ) {
text = CANCEL_URL;
}
else if( name.equals( TC.get( "Effect.SpeakPlayer" ) ) ) {
text = SP_PLAYER_URL;
}
else if( name.equals( TC.get( "Effect.SpeakCharacter" ) ) ) {
text = SP_NPC_URL;
}
else if( name.equals( TC.get( "Effect.TriggerBook" ) ) ) {
text = BOOK_URL;
}
else if( name.equals( TC.get( "Effect.PlaySound" ) ) ) {
text = SOUND_URL;
}
else if( name.equals( TC.get( "Effect.PlayAnimation" ) ) ) {
text = ANIMATION_URL;
}
else if( name.equals( TC.get( "Effect.MovePlayer" ) ) ) {
text = MV_PLAYER_URL;
}
else if( name.equals( TC.get( "Effect.MoveCharacter" ) ) ) {
text = MV_NPC_URL;
}
else if( name.equals( TC.get( "Effect.TriggerConversation" ) ) ) {
text = CONV_URL;
}
else if( name.equals( TC.get( "Effect.TriggerCutscene" ) ) ) {
text = CUTSCENE_URL;
}
else if( name.equals( TC.get( "Effect.TriggerScene" ) ) ) {
text = SCENE_URL;
}
else if( name.equals( TC.get( "Effect.TriggerLastScene" ) ) ) {
text = LAST_SCENE_URL;
}
else if( name.equals( TC.get( "Effect.RandomEffect" ) ) ) {
text = RAMDON_URL;
}
else if( name.equals( TC.get( "Effect.ShowText" ) ) ) {
text = TEXT_URL;
}
else if( name.equals( TC.get( "Effect.WaitTime" ) ) ) {
text = TIME_URL;
}
else if( name.equals( TC.get( "Effect.HighlightItem" ) )) {
text = HIGHLIGHT_URL;
}
else if( name.equals( TC.get( "Effect.MoveObject" ))) {
text = MOVE_OBJECT_URL;
}
// when this method is called for structure list effects
else
text = name;
infoPanel.setHTMLText( text );
}
private class ListElementButtonActionListener implements ActionListener {
private int index;
public ListElementButtonActionListener( int index ) {
this.index = index;
}
public void actionPerformed( ActionEvent arg0 ) {
selectedElement = index;
update( );
changeEffectEditPanel( ( (EffectsStructureListElement) structureElements.get( selectedElement ) ).getPath( ) );
list.requestFocusInWindow( );
}
}
}
| true | true | public static Icon getEffectIcon( String name, int size ) {
Icon effectIcon = null;
if( name.equals( TC.get( "Effect.Activate" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "activate.png" );
}
else if( name.equals( TC.get( "Effect.Deactivate" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "deactivate.png" );
}
else if( name.equals( TC.get( "Effect.SetValue" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "set-value.png" );
}
else if( name.equals( TC.get( "Effect.IncrementVar" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "increment.png" );
}
else if( name.equals( TC.get( "Effect.DecrementVar" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "decrement.png" );
}
else if( name.equals( TC.get( "Effect.MacroReference" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "macro.png" );
}
else if( name.equals( TC.get( "Effect.ConsumeObject" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "consume-object.png" );
}
else if( name.equals( TC.get( "Effect.GenerateObject" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "generate-object.png" );
}
else if( name.equals( TC.get( "Effect.CancelAction" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "cancel-action.png" );
}
else if( name.equals( TC.get( "Effect.SpeakPlayer" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "speak-player.png" );
}
else if( name.equals( TC.get( "Effect.SpeakCharacter" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "speak-npc.png" );
}
else if( name.equals( TC.get( "Effect.TriggerBook" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-book.png" );
}
else if( name.equals( TC.get( "Effect.PlaySound" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "play-sound.png" );
}
else if( name.equals( TC.get( "Effect.PlayAnimation" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "play-animation.png" );
}
else if( name.equals( TC.get( "Effect.MovePlayer" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-player.png" );
}
else if( name.equals( TC.get( "Effect.MoveCharacter" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-npc.png" );
}
else if( name.equals( TC.get( "Effect.TriggerConversation" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-conversation.png" );
}
else if( name.equals( TC.get( "Effect.TriggerCutscene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-cutscene.png" );
}
else if( name.equals( TC.get( "Effect.TriggerScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-scene.png" );
}
else if( name.equals( TC.get( "Effect.TriggerLastScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-last-scene.png" );
}
else if( name.equals( TC.get( "Effect.RandomEffect" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "random-effect.png" );
}
else if( name.equals( TC.get( "Effect.ShowText" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "show-text.png" );
}
else if( name.equals( TC.get( "Effect.WaitTime" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "wait.png" );
}
else if (name.equals( TC.get( "Effect.HighlightItem" ) )) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "highlight-item.png");
}
else if (name.equals( TC.get( "Effect.MoveObject" ) )) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-object.png");
}
else if( name.equals( TC.get( "EffectsGroup.GameState" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "game-state.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Multimedia" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "multimedia.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Miscellaneous" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "miscellaneous.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Trigger" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-events.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Feedback" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "feedback.png" );
}
else if( name.equals( TC.get( "EffectsGroup.ChangeInScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "changes-in-scene.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Main.png" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "effects" );
}
// when this method is called for structure list effects
else
effectIcon = new ImageIcon( getIconBasePath( size ) + "effects" );
return effectIcon;
}
| public static Icon getEffectIcon( String name, int size ) {
Icon effectIcon = null;
if( name.equals( TC.get( "Effect.Activate" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "activate.png" );
}
else if( name.equals( TC.get( "Effect.Deactivate" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "deactivate.png" );
}
else if( name.equals( TC.get( "Effect.SetValue" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "set-value.png" );
}
else if( name.equals( TC.get( "Effect.IncrementVar" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "increment.png" );
}
else if( name.equals( TC.get( "Effect.DecrementVar" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "decrement.png" );
}
else if( name.equals( TC.get( "Effect.MacroReference" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "macro.png" );
}
else if( name.equals( TC.get( "Effect.ConsumeObject" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "consume-object.png" );
}
else if( name.equals( TC.get( "Effect.GenerateObject" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "generate-object.png" );
}
else if( name.equals( TC.get( "Effect.CancelAction" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "cancel-action.png" );
}
else if( name.equals( TC.get( "Effect.SpeakPlayer" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "speak-player.png" );
}
else if( name.equals( TC.get( "Effect.SpeakCharacter" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "speak-npc.png" );
}
else if( name.equals( TC.get( "Effect.TriggerBook" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-book.png" );
}
else if( name.equals( TC.get( "Effect.PlaySound" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "play-sound.png" );
}
else if( name.equals( TC.get( "Effect.PlayAnimation" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "play-animation.png" );
}
else if( name.equals( TC.get( "Effect.MovePlayer" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-player.png" );
}
else if( name.equals( TC.get( "Effect.MoveCharacter" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-npc.png" );
}
else if( name.equals( TC.get( "Effect.TriggerConversation" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-conversation.png" );
}
else if( name.equals( TC.get( "Effect.TriggerCutscene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-cutscene.png" );
}
else if( name.equals( TC.get( "Effect.TriggerScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-scene.png" );
}
else if( name.equals( TC.get( "Effect.TriggerLastScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-last-scene.png" );
}
else if( name.equals( TC.get( "Effect.RandomEffect" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "random-effect.png" );
}
else if( name.equals( TC.get( "Effect.ShowText" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "show-text.png" );
}
else if( name.equals( TC.get( "Effect.WaitTime" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "wait.png" );
}
else if (name.equals( TC.get( "Effect.HighlightItem" ) )) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "highlight-item.png");
}
else if (name.equals( TC.get( "Effect.MoveObject" ) )) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "move-object.png");
}
else if( name.equals( TC.get( "EffectsGroup.GameState" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "game-state.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Multimedia" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "multimedia.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Miscellaneous" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "miscellaneous.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Trigger" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "trigger-events.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Feedback" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "feedback.png" );
}
else if( name.equals( TC.get( "EffectsGroup.ChangeInScene" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "changes-in-scene.png" );
}
else if( name.equals( TC.get( "EffectsGroup.Main" ) ) ) {
effectIcon = new ImageIcon( getIconBasePath( size ) + "effects" );
}
// when this method is called for structure list effects
else
effectIcon = new ImageIcon( getIconBasePath( size ) + "effects" );
return effectIcon;
}
|
diff --git a/container/openejb-core/src/main/java/org/apache/openejb/cli/MainImpl.java b/container/openejb-core/src/main/java/org/apache/openejb/cli/MainImpl.java
index cd52c5e06e..261ac733e1 100644
--- a/container/openejb-core/src/main/java/org/apache/openejb/cli/MainImpl.java
+++ b/container/openejb-core/src/main/java/org/apache/openejb/cli/MainImpl.java
@@ -1,276 +1,279 @@
/**
* 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.openejb.cli;
import org.apache.xbean.finder.ResourceFinder;
import org.apache.openejb.loader.SystemInstance;
import org.apache.openejb.util.OpenEjbVersion;
import org.apache.commons.cli.PosixParser;
import org.apache.commons.cli.CommandLineParser;
import org.apache.commons.cli.Options;
import org.apache.commons.cli.HelpFormatter;
import org.apache.commons.cli.CommandLine;
import org.apache.commons.cli.ParseException;
import java.util.ArrayList;
import java.util.Locale;
import java.util.Properties;
import java.util.Enumeration;
import java.util.Map;
import java.util.List;
import java.io.IOException;
import java.io.File;
import java.io.FileInputStream;
import java.io.BufferedInputStream;
import java.io.InputStream;
import java.io.PrintWriter;
import java.io.StringWriter;
import java.lang.reflect.Method;
import java.net.URL;
/**
* Entry point for ALL things OpenEJB. This will use the new service
* architecture explained here:
*
* @link http://docs.codehaus.org/display/OPENEJB/Executables
*
* @version $Rev$ $Date$
*/
public class MainImpl implements Main {
private static final String BASE_PATH = "META-INF/org.apache.openejb.cli/";
private static final String MAIN_CLASS_PROPERTY_NAME = "main.class";
private static ResourceFinder finder = null;
private static String locale = "";
private static String descriptionBase = "description";
private static String descriptionI18n;
public void main(String[] args) {
args = processSystemProperties(args);
finder = new ResourceFinder(BASE_PATH);
locale = Locale.getDefault().getLanguage();
descriptionI18n = descriptionBase + "." + locale;
CommandLineParser parser = new PosixParser();
// create the Options
Options options = new Options();
options.addOption(null, "version", false, "");
options.addOption("h", "help", false, "");
+ options.addOption("e", "errors", false, "Produce execution error messages");
CommandLine line = null;
String commandName = null;
try {
// parse the arguments up until the first
// command, then let the rest fall into
// the arguments array.
line = parser.parse(options, args, true);
// Get and remove the commandName (first arg)
List<String> list = line.getArgList();
if (list.size() > 0){
commandName = list.get(0);
list.remove(0);
}
// The rest of the args will be passed to the command
args = line.getArgs();
} catch (ParseException exp) {
exp.printStackTrace();
System.exit(-1);
}
if (line.hasOption("version")) {
OpenEjbVersion.get().print(System.out);
System.exit(0);
} else if (line.hasOption("help") || commandName == null || commandName.equals("help")) {
help();
System.exit(0);
}
Properties props = null;
try {
props = finder.findProperties(commandName);
} catch (IOException e1) {
System.out.println("Unavailable command: " + commandName);
help(false);
System.exit(1);
}
if (props == null) {
System.out.println("Unavailable command: " + commandName);
help(false);
System.exit(1);
}
// Shift the command name itself off the args list
String mainClass = props.getProperty(MAIN_CLASS_PROPERTY_NAME);
if (mainClass == null) {
throw new NullPointerException("Command " + commandName + " did not specify a " + MAIN_CLASS_PROPERTY_NAME + " property");
}
Class<?> clazz = null;
try {
clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClass);
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("Main class of command " + commandName + " does not exist: " + mainClass, cnfe);
}
Method mainMethod = null;
try {
mainMethod = clazz.getMethod("main", String[].class);
} catch (Exception e) {
throw new IllegalStateException("Main class of command " + commandName + " does not have a static main method: " + mainClass, e);
}
try {
// WARNING, Definitely do *not* unwrap 'new Object[]{args}' to 'args'
mainMethod.invoke(clazz, new Object[]{args});
} catch (Throwable e) {
- e.printStackTrace();
+ if (line.hasOption("errors")) {
+ e.printStackTrace();
+ }
System.exit(-10);
}
}
private String[] processSystemProperties(String[] args) {
ArrayList<String> argsList = new ArrayList<String>();
// We have to pre-screen for openejb.base as it has a direct affect
// on where we look for the conf/system.properties file which we
// need to read in and apply before we apply the command line -D
// properties. Once SystemInstance.init() is called in the next
// section of code, the openejb.base value is cemented and cannot
// be changed.
for (String arg : args) {
if (arg.indexOf("-Dopenejb.base") != -1) {
String prop = arg.substring(arg.indexOf("-D") + 2, arg.indexOf("="));
String val = arg.substring(arg.indexOf("=") + 1);
System.setProperty(prop, val);
}
}
// get SystemInstance (the only static class in the system)
// so we'll set up all the props in it
SystemInstance systemInstance = null;
try {
SystemInstance.init(System.getProperties());
systemInstance = SystemInstance.get();
} catch (Exception e) {
e.printStackTrace();
System.exit(2);
}
// Read in and apply the conf/system.properties
try {
File conf = systemInstance.getBase().getDirectory("conf");
File file = new File(conf, "system.properties");
if (file.exists()){
Properties systemProperties = new Properties();
FileInputStream fin = new FileInputStream(file);
InputStream in = new BufferedInputStream(fin);
systemProperties.load(in);
System.getProperties().putAll(systemProperties);
}
} catch (IOException e) {
System.out.println("Processing conf/system.properties failed: "+e.getMessage());
}
// Now read in and apply the properties specified on the command line
for (int i = 0; i < args.length; i++) {
String arg = args[i];
if (arg.indexOf("-D") != -1) {
String prop = arg.substring(arg.indexOf("-D") + 2, arg.indexOf("="));
String val = arg.substring(arg.indexOf("=") + 1);
System.setProperty(prop, val);
} else {
argsList.add(arg);
}
}
args = (String[]) argsList.toArray(new String[argsList.size()]);
return args;
}
//DMB: TODO: Delete me
public static Enumeration<URL> doFindCommands() throws IOException {
return Thread.currentThread().getContextClassLoader().getResources(BASE_PATH);
}
private static void help() {
help(true);
}
private static void help(boolean printHeader) {
// Here we are using commons-cli to create the list of available commands
// We actually use a different Options object to parse the 'openejb' command
try {
Options options = new Options();
ResourceFinder commandFinder = new ResourceFinder("META-INF");
Map<String, Properties> commands = commandFinder.mapAvailableProperties("org.apache.openejb.cli");
for (Map.Entry<String, Properties> command : commands.entrySet()) {
if (command.getKey().contains(".")) continue;
Properties p = command.getValue();
String description = p.getProperty(descriptionI18n, p.getProperty(descriptionBase));
options.addOption(command.getKey(), false, description);
}
HelpFormatter formatter = new HelpFormatter();
StringWriter sw = new StringWriter();
PrintWriter pw = new PrintWriter(sw);
String syntax = "openejb <command> [options] [args]";
String header = "\nAvailable commands:";
String footer = "\n" +
"Try 'openejb <command> --help' for help on a specific command.\n" +
"For example 'openejb deploy --help'.\n" +
"\n" +
"Apache OpenEJB -- EJB Container System and Server.\n" +
"For additional information, see http://openejb.apache.org\n" +
"Bug Reports to <[email protected]>";
if (!printHeader){
pw.append(header).append("\n\n");
formatter.printOptions(pw, 74, options, 1, 3);
} else {
formatter.printHelp(pw, 74, syntax, header, options, 1, 3, footer, false);
}
pw.flush();
// Fix up the commons-cli output to our liking.
String text = sw.toString().replaceAll("\n -", "\n ");
text = text.replace("\nApache OpenEJB","\n\nApache OpenEJB");
System.out.print(text);
} catch (IOException e) {
e.printStackTrace();
}
}
}
| false | true | public void main(String[] args) {
args = processSystemProperties(args);
finder = new ResourceFinder(BASE_PATH);
locale = Locale.getDefault().getLanguage();
descriptionI18n = descriptionBase + "." + locale;
CommandLineParser parser = new PosixParser();
// create the Options
Options options = new Options();
options.addOption(null, "version", false, "");
options.addOption("h", "help", false, "");
CommandLine line = null;
String commandName = null;
try {
// parse the arguments up until the first
// command, then let the rest fall into
// the arguments array.
line = parser.parse(options, args, true);
// Get and remove the commandName (first arg)
List<String> list = line.getArgList();
if (list.size() > 0){
commandName = list.get(0);
list.remove(0);
}
// The rest of the args will be passed to the command
args = line.getArgs();
} catch (ParseException exp) {
exp.printStackTrace();
System.exit(-1);
}
if (line.hasOption("version")) {
OpenEjbVersion.get().print(System.out);
System.exit(0);
} else if (line.hasOption("help") || commandName == null || commandName.equals("help")) {
help();
System.exit(0);
}
Properties props = null;
try {
props = finder.findProperties(commandName);
} catch (IOException e1) {
System.out.println("Unavailable command: " + commandName);
help(false);
System.exit(1);
}
if (props == null) {
System.out.println("Unavailable command: " + commandName);
help(false);
System.exit(1);
}
// Shift the command name itself off the args list
String mainClass = props.getProperty(MAIN_CLASS_PROPERTY_NAME);
if (mainClass == null) {
throw new NullPointerException("Command " + commandName + " did not specify a " + MAIN_CLASS_PROPERTY_NAME + " property");
}
Class<?> clazz = null;
try {
clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClass);
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("Main class of command " + commandName + " does not exist: " + mainClass, cnfe);
}
Method mainMethod = null;
try {
mainMethod = clazz.getMethod("main", String[].class);
} catch (Exception e) {
throw new IllegalStateException("Main class of command " + commandName + " does not have a static main method: " + mainClass, e);
}
try {
// WARNING, Definitely do *not* unwrap 'new Object[]{args}' to 'args'
mainMethod.invoke(clazz, new Object[]{args});
} catch (Throwable e) {
e.printStackTrace();
System.exit(-10);
}
}
| public void main(String[] args) {
args = processSystemProperties(args);
finder = new ResourceFinder(BASE_PATH);
locale = Locale.getDefault().getLanguage();
descriptionI18n = descriptionBase + "." + locale;
CommandLineParser parser = new PosixParser();
// create the Options
Options options = new Options();
options.addOption(null, "version", false, "");
options.addOption("h", "help", false, "");
options.addOption("e", "errors", false, "Produce execution error messages");
CommandLine line = null;
String commandName = null;
try {
// parse the arguments up until the first
// command, then let the rest fall into
// the arguments array.
line = parser.parse(options, args, true);
// Get and remove the commandName (first arg)
List<String> list = line.getArgList();
if (list.size() > 0){
commandName = list.get(0);
list.remove(0);
}
// The rest of the args will be passed to the command
args = line.getArgs();
} catch (ParseException exp) {
exp.printStackTrace();
System.exit(-1);
}
if (line.hasOption("version")) {
OpenEjbVersion.get().print(System.out);
System.exit(0);
} else if (line.hasOption("help") || commandName == null || commandName.equals("help")) {
help();
System.exit(0);
}
Properties props = null;
try {
props = finder.findProperties(commandName);
} catch (IOException e1) {
System.out.println("Unavailable command: " + commandName);
help(false);
System.exit(1);
}
if (props == null) {
System.out.println("Unavailable command: " + commandName);
help(false);
System.exit(1);
}
// Shift the command name itself off the args list
String mainClass = props.getProperty(MAIN_CLASS_PROPERTY_NAME);
if (mainClass == null) {
throw new NullPointerException("Command " + commandName + " did not specify a " + MAIN_CLASS_PROPERTY_NAME + " property");
}
Class<?> clazz = null;
try {
clazz = Thread.currentThread().getContextClassLoader().loadClass(mainClass);
} catch (ClassNotFoundException cnfe) {
throw new IllegalStateException("Main class of command " + commandName + " does not exist: " + mainClass, cnfe);
}
Method mainMethod = null;
try {
mainMethod = clazz.getMethod("main", String[].class);
} catch (Exception e) {
throw new IllegalStateException("Main class of command " + commandName + " does not have a static main method: " + mainClass, e);
}
try {
// WARNING, Definitely do *not* unwrap 'new Object[]{args}' to 'args'
mainMethod.invoke(clazz, new Object[]{args});
} catch (Throwable e) {
if (line.hasOption("errors")) {
e.printStackTrace();
}
System.exit(-10);
}
}
|
diff --git a/src/uk/me/parabola/mkgmap/reader/osm/boundary/BoundaryUtil.java b/src/uk/me/parabola/mkgmap/reader/osm/boundary/BoundaryUtil.java
index 543f3b76..b50865d1 100644
--- a/src/uk/me/parabola/mkgmap/reader/osm/boundary/BoundaryUtil.java
+++ b/src/uk/me/parabola/mkgmap/reader/osm/boundary/BoundaryUtil.java
@@ -1,337 +1,341 @@
/*
* Copyright (C) 2006, 2011.
*
* This program is free software; you can redistribute it and/or modify
* it under the terms of the GNU General Public License version 3 or
* version 2 as published by the Free Software Foundation.
*
* This program is distributed in the hope that it will be useful, but
* WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* General Public License for more details.
*/
package uk.me.parabola.mkgmap.reader.osm.boundary;
import java.awt.geom.Area;
import java.io.BufferedInputStream;
import java.io.DataInputStream;
import java.io.EOFException;
import java.io.File;
import java.io.FileFilter;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.Date;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.regex.Pattern;
import uk.me.parabola.imgfmt.app.Coord;
import uk.me.parabola.log.Logger;
import uk.me.parabola.mkgmap.reader.osm.Tags;
import uk.me.parabola.mkgmap.reader.osm.Way;
import uk.me.parabola.util.Java2DConverter;
public class BoundaryUtil {
private static final Logger log = Logger.getLogger(BoundaryUtil.class);
public static class BoundaryFileFilter implements FileFilter {
public boolean accept(File pathname) {
return pathname.isFile() && pathname.getName().endsWith(".bnd");
}
}
public static List<BoundaryElement> splitToElements(Area area) {
if (area.isEmpty()) {
return Collections.emptyList();
}
List<List<Coord>> areaElements = Java2DConverter.areaToShapes(area);
if (areaElements.isEmpty()) {
// this may happen if a boundary overlaps a raster tile in a very small area
// so that it is has no dimension
log.debug("Area has no dimension. Area:",area.getBounds());
return Collections.emptyList();
}
List<BoundaryElement> bElements = new ArrayList<BoundaryElement>();
for (List<Coord> singleElement : areaElements) {
if (singleElement.size() <= 3) {
// need at least 4 items to describe a polygon
continue;
}
Way w = new Way(0, singleElement);
boolean outer = w.clockwise();
bElements.add(new BoundaryElement(outer, singleElement));
}
if (bElements.isEmpty()) {
// should not happen because empty polygons should be removed by
// the Java2DConverter
log.error("Empty boundary elements list after conversion. Area: "+area.getBounds());
return Collections.emptyList();
}
// reverse the list because it starts with the inner elements first and
// we need the other way round
Collections.reverse(bElements);
assert bElements.get(0).isOuter() : log.threadTag()+" first element is not outer. "+ bElements;
return bElements;
}
public static Area convertToArea(List<BoundaryElement> list) {
Area area = new Area();
for (BoundaryElement elem : list) {
if (elem.isOuter()) {
area.add(elem.getArea());
} else {
area.subtract(elem.getArea());
}
}
return area;
}
public static List<Boundary> loadBoundaryFile(File boundaryFile,
uk.me.parabola.imgfmt.app.Area bbox) throws IOException
{
log.debug("Load boundary file",boundaryFile,"within",bbox);
List<Boundary> boundaryList = new ArrayList<Boundary>();
FileInputStream stream = new FileInputStream(boundaryFile);
try {
DataInputStream inpStream = new DataInputStream(
new BufferedInputStream(stream, 1024 * 1024));
try {
// 1st read the mkgmap release the boundary file is created by
String mkgmapRel = inpStream.readUTF();
long createTime = inpStream.readLong();
if (log.isDebugEnabled()) {
log.debug("File created by mkgmap release",mkgmapRel,"at",new Date(createTime));
}
while (true) {
int minLat = inpStream.readInt();
int minLong = inpStream.readInt();
int maxLat = inpStream.readInt();
int maxLong = inpStream.readInt();
log.debug("Next boundary. Lat min:",minLat,"max:",maxLat,"Long min:",minLong,"max:",maxLong);
uk.me.parabola.imgfmt.app.Area rBbox = new uk.me.parabola.imgfmt.app.Area(
minLat, minLong, maxLat, maxLong);
int bSize = inpStream.readInt();
log.debug("Size:",bSize);
if (bbox == null || bbox.intersects(rBbox)) {
log.debug("Bbox intersects. Load the boundary");
Tags tags = new Tags();
int noOfTags = inpStream.readInt();
for (int i = 0; i < noOfTags; i++) {
String name = inpStream.readUTF();
String value = inpStream.readUTF();
tags.put(name, value);
}
int noBElems = inpStream.readInt();
assert noBElems > 0;
// the first area is always an outer area and will be assigned to the variable
Area area = null;
for (int i = 0; i < noBElems; i++) {
boolean outer = inpStream.readBoolean();
int noCoords = inpStream.readInt();
log.debug("No of coords",noCoords);
List<Coord> points = new ArrayList<Coord>(noCoords);
for (int c = 0; c < noCoords; c++) {
int lat = inpStream.readInt();
int lon = inpStream.readInt();
points.add(new Coord(lat, lon));
}
Area elemArea = Java2DConverter.createArea(points);
if (outer) {
if (area == null) {
area = elemArea;
} else {
area.add(elemArea);
}
} else {
if (area == null) {
log.warn("Boundary: "+tags);
log.warn("Outer way is tagged incosistently as inner way. Ignoring it.");
log.warn("Points: "+points);
} else {
area.subtract(elemArea);
}
}
}
- Boundary boundary = new Boundary(area, tags);
- boundaryList.add(boundary);
+ if (area != null) {
+ Boundary boundary = new Boundary(area, tags);
+ boundaryList.add(boundary);
+ } else {
+ log.warn("Boundary "+tags+" does not contain any valid area in file "+boundaryFile);
+ }
} else {
log.debug("Bbox does not intersect. Skip",bSize);
inpStream.skipBytes(bSize);
}
}
} catch (EOFException exp) {
// it's always thrown at the end of the file
// log.error("Got EOF at the end of the file");
}
inpStream.close();
} finally {
if (stream != null)
stream.close();
}
return boundaryList;
}
public static List<File> getBoundaryFiles(File boundaryDir,
uk.me.parabola.imgfmt.app.Area bbox) {
List<File> boundaryFiles = new ArrayList<File>();
for (int latSplit = BoundaryUtil.getSplitBegin(bbox.getMinLat()); latSplit <= BoundaryUtil
.getSplitBegin(bbox.getMaxLat()); latSplit += BoundaryUtil.RASTER) {
for (int lonSplit = BoundaryUtil.getSplitBegin(bbox.getMinLong()); lonSplit <= BoundaryUtil
.getSplitBegin(bbox.getMaxLong()); lonSplit += BoundaryUtil.RASTER) {
File bndFile = new File(boundaryDir, "bounds_"
+ getKey(latSplit, lonSplit) + ".bnd");
if (bndFile.exists())
boundaryFiles.add(bndFile);
}
}
return boundaryFiles;
}
public static List<Boundary> loadBoundaries(File boundaryDir,
uk.me.parabola.imgfmt.app.Area bbox) {
List<File> boundaryFiles = getBoundaryFiles(boundaryDir, bbox);
List<Boundary> boundaries = new ArrayList<Boundary>();
for (File boundaryFile : boundaryFiles) {
try {
boundaries.addAll(loadBoundaryFile(boundaryFile, bbox));
} catch (IOException exp) {
log.warn("Cannot load boundary file", boundaryFile + ".",exp);
// String basename = "missingbounds/";
// String[] bParts = boundaryFile.getName().substring(0,boundaryFile.getName().length()-4).split("_");
// int minLat = Integer.valueOf(bParts[1]);
// int minLong = Integer.valueOf(bParts[2]);
// uk.me.parabola.imgfmt.app.Area bBbox = new uk.me.parabola.imgfmt.app.Area(minLat, minLong, minLat+RASTER, minLong+RASTER);
// GpxCreator.createAreaGpx(basename+boundaryFile.getName(), bBbox);
// log.error("GPX created "+basename+boundaryFile.getName());
}
}
if (boundaryFiles.size() > 1) {
boundaries = mergeBoundaries(boundaries);
}
return boundaries;
}
private static List<Boundary> mergeBoundaries(List<Boundary> boundaryList) {
int noIdBoundaries = 0;
Map<String, Boundary> mergeMap = new HashMap<String, Boundary>();
for (Boundary toMerge : boundaryList) {
String bId = toMerge.getTags().get("mkgmap:boundaryid");
if (bId == null) {
noIdBoundaries++;
mergeMap.put("n" + noIdBoundaries, toMerge);
} else {
Boundary existingBoundary = mergeMap.get(bId);
if (existingBoundary == null) {
mergeMap.put(bId, toMerge);
} else {
if (log.isInfoEnabled())
log.info("Merge boundaries", existingBoundary.getTags(), "with", toMerge.getTags());
existingBoundary.getArea().add(toMerge.getArea());
// Merge the mkgmap:lies_in tag
// They should be the same but better to check that...
String liesInTagExist = existingBoundary.getTags().get("mkgmap:lies_in");
String liesInTagMerge = toMerge.getTags().get("mkgmap:lies_in");
if (liesInTagExist != null && liesInTagExist.equals(liesInTagMerge)==false) {
if (liesInTagMerge == null) {
existingBoundary.getTags().remove("mkgmap:lies_in");
} else {
// there is a difference in the lies_in tag => keep the equal ids
Set<String> existIds = new HashSet<String>(Arrays.asList(liesInTagExist.split(";")));
Set<String> mergeIds = new HashSet<String>(Arrays.asList(liesInTagMerge.split(";")));
existIds.retainAll(mergeIds);
if (existIds.isEmpty()) {
existingBoundary.getTags().remove("mkgmap:lies_in");
} else {
StringBuilder newLiesIn = new StringBuilder();
for (String liesInEntry : existIds) {
if (newLiesIn.length() > 0) {
newLiesIn.append(";");
}
newLiesIn.append(liesInEntry);
}
existingBoundary.getTags().put("mkgmap:lies_in", newLiesIn.toString());
}
}
}
}
}
}
if (noIdBoundaries > 0) {
log.error(noIdBoundaries
+ " without boundary id. Could not merge them.");
}
return new ArrayList<Boundary>(mergeMap.values());
}
public static final int RASTER = 50000;
public static int getSplitBegin(int value) {
int rem = value % RASTER;
if (rem == 0) {
return value;
} else if (value >= 0) {
return value - rem;
} else {
return value - RASTER - rem;
}
}
public static int getSplitEnd(int value) {
int rem = value % RASTER;
if (rem == 0) {
return value;
} else if (value >= 0) {
return value + RASTER - rem;
} else {
return value - rem;
}
}
public static String getKey(int lat, int lon) {
return lat + "_" + lon;
}
/**
* Retrieve the bounding box of the given boundary file.
* @param boundaryFile the boundary file
* @return the bounding box
*/
public static uk.me.parabola.imgfmt.app.Area getBbox(File boundaryFile) {
String filename = boundaryFile.getName();
// cut off the extension
filename = filename.substring(0,filename.length()-4);
String[] fParts = filename.split(Pattern.quote("_"));
int lat = Integer.valueOf(fParts[1]);
int lon = Integer.valueOf(fParts[2]);
return new uk.me.parabola.imgfmt.app.Area(lat, lon, lat+RASTER, lon+RASTER);
}
}
| true | true | public static List<Boundary> loadBoundaryFile(File boundaryFile,
uk.me.parabola.imgfmt.app.Area bbox) throws IOException
{
log.debug("Load boundary file",boundaryFile,"within",bbox);
List<Boundary> boundaryList = new ArrayList<Boundary>();
FileInputStream stream = new FileInputStream(boundaryFile);
try {
DataInputStream inpStream = new DataInputStream(
new BufferedInputStream(stream, 1024 * 1024));
try {
// 1st read the mkgmap release the boundary file is created by
String mkgmapRel = inpStream.readUTF();
long createTime = inpStream.readLong();
if (log.isDebugEnabled()) {
log.debug("File created by mkgmap release",mkgmapRel,"at",new Date(createTime));
}
while (true) {
int minLat = inpStream.readInt();
int minLong = inpStream.readInt();
int maxLat = inpStream.readInt();
int maxLong = inpStream.readInt();
log.debug("Next boundary. Lat min:",minLat,"max:",maxLat,"Long min:",minLong,"max:",maxLong);
uk.me.parabola.imgfmt.app.Area rBbox = new uk.me.parabola.imgfmt.app.Area(
minLat, minLong, maxLat, maxLong);
int bSize = inpStream.readInt();
log.debug("Size:",bSize);
if (bbox == null || bbox.intersects(rBbox)) {
log.debug("Bbox intersects. Load the boundary");
Tags tags = new Tags();
int noOfTags = inpStream.readInt();
for (int i = 0; i < noOfTags; i++) {
String name = inpStream.readUTF();
String value = inpStream.readUTF();
tags.put(name, value);
}
int noBElems = inpStream.readInt();
assert noBElems > 0;
// the first area is always an outer area and will be assigned to the variable
Area area = null;
for (int i = 0; i < noBElems; i++) {
boolean outer = inpStream.readBoolean();
int noCoords = inpStream.readInt();
log.debug("No of coords",noCoords);
List<Coord> points = new ArrayList<Coord>(noCoords);
for (int c = 0; c < noCoords; c++) {
int lat = inpStream.readInt();
int lon = inpStream.readInt();
points.add(new Coord(lat, lon));
}
Area elemArea = Java2DConverter.createArea(points);
if (outer) {
if (area == null) {
area = elemArea;
} else {
area.add(elemArea);
}
} else {
if (area == null) {
log.warn("Boundary: "+tags);
log.warn("Outer way is tagged incosistently as inner way. Ignoring it.");
log.warn("Points: "+points);
} else {
area.subtract(elemArea);
}
}
}
Boundary boundary = new Boundary(area, tags);
boundaryList.add(boundary);
} else {
log.debug("Bbox does not intersect. Skip",bSize);
inpStream.skipBytes(bSize);
}
}
} catch (EOFException exp) {
// it's always thrown at the end of the file
// log.error("Got EOF at the end of the file");
}
inpStream.close();
} finally {
if (stream != null)
stream.close();
}
return boundaryList;
}
| public static List<Boundary> loadBoundaryFile(File boundaryFile,
uk.me.parabola.imgfmt.app.Area bbox) throws IOException
{
log.debug("Load boundary file",boundaryFile,"within",bbox);
List<Boundary> boundaryList = new ArrayList<Boundary>();
FileInputStream stream = new FileInputStream(boundaryFile);
try {
DataInputStream inpStream = new DataInputStream(
new BufferedInputStream(stream, 1024 * 1024));
try {
// 1st read the mkgmap release the boundary file is created by
String mkgmapRel = inpStream.readUTF();
long createTime = inpStream.readLong();
if (log.isDebugEnabled()) {
log.debug("File created by mkgmap release",mkgmapRel,"at",new Date(createTime));
}
while (true) {
int minLat = inpStream.readInt();
int minLong = inpStream.readInt();
int maxLat = inpStream.readInt();
int maxLong = inpStream.readInt();
log.debug("Next boundary. Lat min:",minLat,"max:",maxLat,"Long min:",minLong,"max:",maxLong);
uk.me.parabola.imgfmt.app.Area rBbox = new uk.me.parabola.imgfmt.app.Area(
minLat, minLong, maxLat, maxLong);
int bSize = inpStream.readInt();
log.debug("Size:",bSize);
if (bbox == null || bbox.intersects(rBbox)) {
log.debug("Bbox intersects. Load the boundary");
Tags tags = new Tags();
int noOfTags = inpStream.readInt();
for (int i = 0; i < noOfTags; i++) {
String name = inpStream.readUTF();
String value = inpStream.readUTF();
tags.put(name, value);
}
int noBElems = inpStream.readInt();
assert noBElems > 0;
// the first area is always an outer area and will be assigned to the variable
Area area = null;
for (int i = 0; i < noBElems; i++) {
boolean outer = inpStream.readBoolean();
int noCoords = inpStream.readInt();
log.debug("No of coords",noCoords);
List<Coord> points = new ArrayList<Coord>(noCoords);
for (int c = 0; c < noCoords; c++) {
int lat = inpStream.readInt();
int lon = inpStream.readInt();
points.add(new Coord(lat, lon));
}
Area elemArea = Java2DConverter.createArea(points);
if (outer) {
if (area == null) {
area = elemArea;
} else {
area.add(elemArea);
}
} else {
if (area == null) {
log.warn("Boundary: "+tags);
log.warn("Outer way is tagged incosistently as inner way. Ignoring it.");
log.warn("Points: "+points);
} else {
area.subtract(elemArea);
}
}
}
if (area != null) {
Boundary boundary = new Boundary(area, tags);
boundaryList.add(boundary);
} else {
log.warn("Boundary "+tags+" does not contain any valid area in file "+boundaryFile);
}
} else {
log.debug("Bbox does not intersect. Skip",bSize);
inpStream.skipBytes(bSize);
}
}
} catch (EOFException exp) {
// it's always thrown at the end of the file
// log.error("Got EOF at the end of the file");
}
inpStream.close();
} finally {
if (stream != null)
stream.close();
}
return boundaryList;
}
|
diff --git a/src/main/java/org/glom/web/server/database/DetailsDBAccess.java b/src/main/java/org/glom/web/server/database/DetailsDBAccess.java
index 323a78c..5b2a508 100644
--- a/src/main/java/org/glom/web/server/database/DetailsDBAccess.java
+++ b/src/main/java/org/glom/web/server/database/DetailsDBAccess.java
@@ -1,125 +1,128 @@
/*
* Copyright (C) 2011 Openismus GmbH
*
* This file is part of GWT-Glom.
*
* GWT-Glom 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.
*
* GWT-Glom 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 GWT-Glom. If not, see <http://www.gnu.org/licenses/>.
*/
package org.glom.web.server.database;
import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import org.glom.libglom.Document;
import org.glom.libglom.Field;
import org.glom.libglom.Glom;
import org.glom.libglom.LayoutFieldVector;
import org.glom.libglom.SqlBuilder;
import org.glom.libglom.Value;
import org.glom.web.server.Log;
import org.glom.web.server.Utils;
import org.glom.web.shared.DataItem;
import org.glom.web.shared.TypedDataItem;
import com.mchange.v2.c3p0.ComboPooledDataSource;
/**
* @author Ben Konrath <[email protected]>
*
*/
public class DetailsDBAccess extends DBAccess {
public DetailsDBAccess(Document document, String documentID, ComboPooledDataSource cpds, String tableName) {
super(document, documentID, cpds, tableName);
this.tableName = tableName;
}
public DataItem[] getData(TypedDataItem primaryKeyValue) {
LayoutFieldVector fieldsToGet = getFieldsToShowForSQLQuery(document
.get_data_layout_groups("details", tableName));
if (fieldsToGet == null || fieldsToGet.size() <= 0) {
Log.warn(documentID, tableName, "Didn't find any fields to show. Returning null.");
return null;
}
Field primaryKey = getPrimaryKeyField();
if (primaryKey == null) {
Log.error(documentID, tableName, "Couldn't find primary key in table. Returning null.");
return null;
}
ArrayList<DataItem[]> rowsList = new ArrayList<DataItem[]>();
Connection conn = null;
Statement st = null;
ResultSet rs = null;
+ Value gdaPrimaryKeyValue = null;
try {
// Setup the JDBC driver and get the query.
conn = cpds.getConnection();
st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
- Value gdaPrimaryKeyValue = Utils.getGlomTypeGdaValueForTypedDataItem(documentID, tableName,
+ gdaPrimaryKeyValue = Utils.getGlomTypeGdaValueForTypedDataItem(documentID, tableName,
primaryKey.get_glom_type(), primaryKeyValue);
- // Only create the query if we've created a Gda Value from the DataItem.
+ // Only create the query if we've created a Gda Value from the TypedDataItem.
if (gdaPrimaryKeyValue != null) {
SqlBuilder builder = Glom.build_sql_select_with_key(tableName, fieldsToGet, primaryKey,
gdaPrimaryKeyValue);
String query = Glom.sqlbuilder_get_full_query(builder);
rs = st.executeQuery(query);
// get the results from the ResultSet
// using 2 as a length parameter so we can log a warning if appropriate
rowsList = convertResultSetToDTO(2, fieldsToGet, rs);
}
} catch (SQLException e) {
Log.error(documentID, tableName, "Error executing database query.", e);
// TODO: somehow notify user of problem
return null;
} finally {
// cleanup everything that has been used
try {
if (rs != null)
rs.close();
if (st != null)
st.close();
if (conn != null)
conn.close();
} catch (Exception e) {
Log.error(documentID, tableName,
"Error closing database resources. Subsequent database queries may not work.", e);
}
}
if (rowsList.size() == 0) {
Log.error(documentID, tableName, "The query returned an empty ResultSet. Returning null.");
return null;
- } else if (rowsList.size() > 1 && primaryKeyValue != null && !primaryKeyValue.isEmpty()) {
- // Only log a warning if the result size is greater than 1 and the primaryKeyValue was set.
+ } else if (rowsList.size() > 1 && !gdaPrimaryKeyValue.is_null()) {
+ // Only log a warning if the result size is greater than 1 and the gdaPrimaryKeyValue is not null. When
+ // gdaPrimaryKeyValue.is_null() is true, the default query for the details view is being executed so we
+ // expect a result set that is larger than one.
Log.warn(documentID, tableName,
"The query did not return the expected unique result. Returning the first result in the set.");
}
return rowsList.get(0);
}
}
| false | true | public DataItem[] getData(TypedDataItem primaryKeyValue) {
LayoutFieldVector fieldsToGet = getFieldsToShowForSQLQuery(document
.get_data_layout_groups("details", tableName));
if (fieldsToGet == null || fieldsToGet.size() <= 0) {
Log.warn(documentID, tableName, "Didn't find any fields to show. Returning null.");
return null;
}
Field primaryKey = getPrimaryKeyField();
if (primaryKey == null) {
Log.error(documentID, tableName, "Couldn't find primary key in table. Returning null.");
return null;
}
ArrayList<DataItem[]> rowsList = new ArrayList<DataItem[]>();
Connection conn = null;
Statement st = null;
ResultSet rs = null;
try {
// Setup the JDBC driver and get the query.
conn = cpds.getConnection();
st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
Value gdaPrimaryKeyValue = Utils.getGlomTypeGdaValueForTypedDataItem(documentID, tableName,
primaryKey.get_glom_type(), primaryKeyValue);
// Only create the query if we've created a Gda Value from the DataItem.
if (gdaPrimaryKeyValue != null) {
SqlBuilder builder = Glom.build_sql_select_with_key(tableName, fieldsToGet, primaryKey,
gdaPrimaryKeyValue);
String query = Glom.sqlbuilder_get_full_query(builder);
rs = st.executeQuery(query);
// get the results from the ResultSet
// using 2 as a length parameter so we can log a warning if appropriate
rowsList = convertResultSetToDTO(2, fieldsToGet, rs);
}
} catch (SQLException e) {
Log.error(documentID, tableName, "Error executing database query.", e);
// TODO: somehow notify user of problem
return null;
} finally {
// cleanup everything that has been used
try {
if (rs != null)
rs.close();
if (st != null)
st.close();
if (conn != null)
conn.close();
} catch (Exception e) {
Log.error(documentID, tableName,
"Error closing database resources. Subsequent database queries may not work.", e);
}
}
if (rowsList.size() == 0) {
Log.error(documentID, tableName, "The query returned an empty ResultSet. Returning null.");
return null;
} else if (rowsList.size() > 1 && primaryKeyValue != null && !primaryKeyValue.isEmpty()) {
// Only log a warning if the result size is greater than 1 and the primaryKeyValue was set.
Log.warn(documentID, tableName,
"The query did not return the expected unique result. Returning the first result in the set.");
}
return rowsList.get(0);
}
| public DataItem[] getData(TypedDataItem primaryKeyValue) {
LayoutFieldVector fieldsToGet = getFieldsToShowForSQLQuery(document
.get_data_layout_groups("details", tableName));
if (fieldsToGet == null || fieldsToGet.size() <= 0) {
Log.warn(documentID, tableName, "Didn't find any fields to show. Returning null.");
return null;
}
Field primaryKey = getPrimaryKeyField();
if (primaryKey == null) {
Log.error(documentID, tableName, "Couldn't find primary key in table. Returning null.");
return null;
}
ArrayList<DataItem[]> rowsList = new ArrayList<DataItem[]>();
Connection conn = null;
Statement st = null;
ResultSet rs = null;
Value gdaPrimaryKeyValue = null;
try {
// Setup the JDBC driver and get the query.
conn = cpds.getConnection();
st = conn.createStatement(ResultSet.TYPE_FORWARD_ONLY, ResultSet.CONCUR_READ_ONLY);
gdaPrimaryKeyValue = Utils.getGlomTypeGdaValueForTypedDataItem(documentID, tableName,
primaryKey.get_glom_type(), primaryKeyValue);
// Only create the query if we've created a Gda Value from the TypedDataItem.
if (gdaPrimaryKeyValue != null) {
SqlBuilder builder = Glom.build_sql_select_with_key(tableName, fieldsToGet, primaryKey,
gdaPrimaryKeyValue);
String query = Glom.sqlbuilder_get_full_query(builder);
rs = st.executeQuery(query);
// get the results from the ResultSet
// using 2 as a length parameter so we can log a warning if appropriate
rowsList = convertResultSetToDTO(2, fieldsToGet, rs);
}
} catch (SQLException e) {
Log.error(documentID, tableName, "Error executing database query.", e);
// TODO: somehow notify user of problem
return null;
} finally {
// cleanup everything that has been used
try {
if (rs != null)
rs.close();
if (st != null)
st.close();
if (conn != null)
conn.close();
} catch (Exception e) {
Log.error(documentID, tableName,
"Error closing database resources. Subsequent database queries may not work.", e);
}
}
if (rowsList.size() == 0) {
Log.error(documentID, tableName, "The query returned an empty ResultSet. Returning null.");
return null;
} else if (rowsList.size() > 1 && !gdaPrimaryKeyValue.is_null()) {
// Only log a warning if the result size is greater than 1 and the gdaPrimaryKeyValue is not null. When
// gdaPrimaryKeyValue.is_null() is true, the default query for the details view is being executed so we
// expect a result set that is larger than one.
Log.warn(documentID, tableName,
"The query did not return the expected unique result. Returning the first result in the set.");
}
return rowsList.get(0);
}
|
diff --git a/web/src/main/java/org/eurekastreams/web/client/ui/pages/discover/ActiveStreamItemPanel.java b/web/src/main/java/org/eurekastreams/web/client/ui/pages/discover/ActiveStreamItemPanel.java
index cf36281e9..abf1ab5aa 100644
--- a/web/src/main/java/org/eurekastreams/web/client/ui/pages/discover/ActiveStreamItemPanel.java
+++ b/web/src/main/java/org/eurekastreams/web/client/ui/pages/discover/ActiveStreamItemPanel.java
@@ -1,119 +1,120 @@
/*
* Copyright (c) 2011 Lockheed Martin Corporation
*
* 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.eurekastreams.web.client.ui.pages.discover;
import org.eurekastreams.server.domain.EntityType;
import org.eurekastreams.server.domain.Page;
import org.eurekastreams.server.domain.dto.StreamDTO;
import org.eurekastreams.web.client.history.CreateUrlRequest;
import org.eurekastreams.web.client.ui.Session;
import org.eurekastreams.web.client.ui.common.avatar.AvatarLinkPanel;
import org.eurekastreams.web.client.ui.common.avatar.AvatarWidget.Size;
import org.eurekastreams.web.client.ui.pages.master.CoreCss;
import org.eurekastreams.web.client.ui.pages.master.StaticResourceBundle;
import com.google.gwt.core.client.GWT;
import com.google.gwt.dom.client.SpanElement;
import com.google.gwt.resources.client.CssResource;
import com.google.gwt.uibinder.client.UiBinder;
import com.google.gwt.uibinder.client.UiField;
import com.google.gwt.user.client.ui.Composite;
import com.google.gwt.user.client.ui.HTMLPanel;
import com.google.gwt.user.client.ui.Hyperlink;
import com.google.gwt.user.client.ui.Widget;
/**
* FlowPanel for the "Most Active Streams" panel items.
*/
public class ActiveStreamItemPanel extends Composite
{
/** Binder for building UI. */
private static LocalUiBinder binder = GWT.create(LocalUiBinder.class);
/**
* Local styles.
*/
interface LocalStyle extends CssResource
{
/** @return Apply to the follow panel to allow custom styling. */
String followPanel();
}
/** Local styles. */
@UiField
LocalStyle style;
/** Global styles. */
@UiField(provided = true)
CoreCss coreCss;
/** Avatar panel. */
@UiField(provided = true)
AvatarLinkPanel avatarPanel;
/** Panel holding the details. */
@UiField
HTMLPanel infoPanel;
/** Name link. */
@UiField
Hyperlink streamNameLink;
/** Message count display widget. */
@UiField
SpanElement messageCount;
/**
* Constructor.
*
* @param inStreamDTO
* the streamDTO to represent
*/
public ActiveStreamItemPanel(final StreamDTO inStreamDTO)
{
coreCss = StaticResourceBundle.INSTANCE.coreCss();
avatarPanel = new AvatarLinkPanel(inStreamDTO.getEntityType(), inStreamDTO.getUniqueId(), inStreamDTO.getId(),
inStreamDTO.getAvatarId(), Size.Small);
Widget main = binder.createAndBindUi(this);
initWidget(main);
// add follow controls if not the current person
if (inStreamDTO.getEntityType() != EntityType.PERSON
|| inStreamDTO.getEntityId() != Session.getInstance().getCurrentPerson().getEntityId())
{
Widget followPanel = new FollowPanel(inStreamDTO);
followPanel.addStyleName(style.followPanel());
infoPanel.add(followPanel);
}
// set text and link for name; assume group if not person
Page linkPage = (inStreamDTO.getEntityType() == EntityType.PERSON) ? Page.PEOPLE : Page.GROUPS;
String nameUrl = Session.getInstance().generateUrl(//
new CreateUrlRequest(linkPage, inStreamDTO.getUniqueId()));
streamNameLink.setTargetHistoryToken(nameUrl);
streamNameLink.setText(inStreamDTO.getDisplayName());
+ streamNameLink.setTitle(inStreamDTO.getDisplayName());
messageCount.setInnerText(inStreamDTO.getFollowersCount() == 1 ? "1 Daily Message" : Integer
.toString(inStreamDTO.getFollowersCount()) + " Daily Messages");
}
/**
* Binder for building UI.
*/
interface LocalUiBinder extends UiBinder<Widget, ActiveStreamItemPanel>
{
}
}
| true | true | public ActiveStreamItemPanel(final StreamDTO inStreamDTO)
{
coreCss = StaticResourceBundle.INSTANCE.coreCss();
avatarPanel = new AvatarLinkPanel(inStreamDTO.getEntityType(), inStreamDTO.getUniqueId(), inStreamDTO.getId(),
inStreamDTO.getAvatarId(), Size.Small);
Widget main = binder.createAndBindUi(this);
initWidget(main);
// add follow controls if not the current person
if (inStreamDTO.getEntityType() != EntityType.PERSON
|| inStreamDTO.getEntityId() != Session.getInstance().getCurrentPerson().getEntityId())
{
Widget followPanel = new FollowPanel(inStreamDTO);
followPanel.addStyleName(style.followPanel());
infoPanel.add(followPanel);
}
// set text and link for name; assume group if not person
Page linkPage = (inStreamDTO.getEntityType() == EntityType.PERSON) ? Page.PEOPLE : Page.GROUPS;
String nameUrl = Session.getInstance().generateUrl(//
new CreateUrlRequest(linkPage, inStreamDTO.getUniqueId()));
streamNameLink.setTargetHistoryToken(nameUrl);
streamNameLink.setText(inStreamDTO.getDisplayName());
messageCount.setInnerText(inStreamDTO.getFollowersCount() == 1 ? "1 Daily Message" : Integer
.toString(inStreamDTO.getFollowersCount()) + " Daily Messages");
}
| public ActiveStreamItemPanel(final StreamDTO inStreamDTO)
{
coreCss = StaticResourceBundle.INSTANCE.coreCss();
avatarPanel = new AvatarLinkPanel(inStreamDTO.getEntityType(), inStreamDTO.getUniqueId(), inStreamDTO.getId(),
inStreamDTO.getAvatarId(), Size.Small);
Widget main = binder.createAndBindUi(this);
initWidget(main);
// add follow controls if not the current person
if (inStreamDTO.getEntityType() != EntityType.PERSON
|| inStreamDTO.getEntityId() != Session.getInstance().getCurrentPerson().getEntityId())
{
Widget followPanel = new FollowPanel(inStreamDTO);
followPanel.addStyleName(style.followPanel());
infoPanel.add(followPanel);
}
// set text and link for name; assume group if not person
Page linkPage = (inStreamDTO.getEntityType() == EntityType.PERSON) ? Page.PEOPLE : Page.GROUPS;
String nameUrl = Session.getInstance().generateUrl(//
new CreateUrlRequest(linkPage, inStreamDTO.getUniqueId()));
streamNameLink.setTargetHistoryToken(nameUrl);
streamNameLink.setText(inStreamDTO.getDisplayName());
streamNameLink.setTitle(inStreamDTO.getDisplayName());
messageCount.setInnerText(inStreamDTO.getFollowersCount() == 1 ? "1 Daily Message" : Integer
.toString(inStreamDTO.getFollowersCount()) + " Daily Messages");
}
|
diff --git a/src/com/werebug/randomsequencegenerator/Rsg_main.java b/src/com/werebug/randomsequencegenerator/Rsg_main.java
index c2d6a40..77ef225 100644
--- a/src/com/werebug/randomsequencegenerator/Rsg_main.java
+++ b/src/com/werebug/randomsequencegenerator/Rsg_main.java
@@ -1,248 +1,248 @@
package com.werebug.randomsequencegenerator;
import com.werebug.randomsequencegenerator.R;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentActivity;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.RadioGroup;
import android.widget.RadioGroup.OnCheckedChangeListener;
import android.widget.TextView;
import android.widget.Toast;
import android.annotation.SuppressLint;
import android.content.ClipData;
import android.content.ClipboardManager;
import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.content.SharedPreferences.Editor;
public class Rsg_main extends FragmentActivity implements OnClickListener, OnCheckedChangeListener, SaveDialog.SaveDialogListener {
// Layout widgets
private View range_layout, manual_layout;
private Button create, copy, send_to, save_sequence;
private CheckBox digit, lowercase, uppercase, special;
private RadioGroup rg;
private TextView manual, length_textview, output;
// String used to generate the random sequence
private final String BINARY = "01";
private final String HEX = "0123456789ABCDEF";
private final String DIGIT = "0123456789";
private final String LAZ = "qwertyuiopasdfghjklzxcvbnm";
private final String CAZ = "QWERTYUIOPASDFGHJKLZXCVBNM";
private final String SPECIAL = "$%&()=?@#<>_£[]*";
// Intent to send text to other apps
private Intent send_to_intent = new Intent(Intent.ACTION_SEND);
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_rsg_main);
// Retrieving layout
this.range_layout = (View)findViewById(R.id.class_range);
this.manual_layout = (View)findViewById(R.id.manual_layout);
// Retrieving CheckBox
this.digit = (CheckBox)findViewById(R.id.range_digit);
this.lowercase = (CheckBox)findViewById(R.id.range_lowercase);
this.uppercase = (CheckBox)findViewById(R.id.range_uppercase);
this.special = (CheckBox)findViewById(R.id.range_special);
// Retrieving TextView
this.manual = (TextView)findViewById(R.id.manual);
this.length_textview = (TextView)findViewById(R.id.string_length);
this.output = (TextView)findViewById(R.id.output_textview);
// Setting Listener for buttons
this.create = (Button)findViewById(R.id.button_create);
this.create.setOnClickListener(this);
this.copy = (Button)findViewById(R.id.copy_button);
this.copy.setOnClickListener(this);
this.send_to = (Button)findViewById(R.id.send_button);
this.send_to.setOnClickListener(this);
this.save_sequence = (Button)findViewById(R.id.save_button);
this.save_sequence.setOnClickListener(this);
// Setting listener for RadioGroup
this.rg = (RadioGroup)findViewById(R.id.radio_group);
this.rg.setOnCheckedChangeListener(this);
}
// Creating menu
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.activity_main, menu);
return true;
}
// Handler for menu entries
public boolean onOptionsItemSelected(MenuItem mi){
switch (mi.getItemId()){
case R.id.show_saved:
Intent goto_saved = new Intent(this, ShowSaved.class);
this.startActivity(goto_saved);
return true;
default:
return super.onOptionsItemSelected(mi);
}
}
// Implements OnCheckedChangeListener
// This functions hides and shows widget depending on situation
public void onCheckedChanged (RadioGroup rg, int newchecked) {
switch (newchecked) {
case R.id.class_radio:
this.range_layout.setVisibility(View.VISIBLE);
this.manual_layout.setVisibility(View.GONE);
break;
case R.id.manual_radio:
this.manual_layout.setVisibility(View.VISIBLE);
this.range_layout.setVisibility(View.GONE);
break;
default:
this.manual_layout.setVisibility(View.GONE);
this.range_layout.setVisibility(View.GONE);
}
}
@SuppressLint("NewApi")
@SuppressWarnings("deprecation")
public void onClick (View v) {
int clicked = v.getId();
switch (clicked) {
case R.id.button_create:
String chars = "";
String result = "";
int selected = this.rg.getCheckedRadioButtonId();
switch (selected) {
case R.id.binary_radio:
chars = chars.concat(this.BINARY);
break;
case R.id.hex_radio:
chars = chars.concat(this.HEX);
break;
case R.id.class_radio:
if (this.digit.isChecked()) {
chars = chars.concat(this.DIGIT);
}
if (this.lowercase.isChecked()) {
chars = chars.concat(this.LAZ);
}
if (this.uppercase.isChecked()) {
chars = chars.concat(this.CAZ);
}
if (this.special.isChecked()) {
chars = chars.concat(this.SPECIAL);
}
break;
case R.id.manual_radio:
String chars_to_add = this.manual.getText().toString();
chars = chars.concat(chars_to_add);
break;
default:
break;
}
int chars_last_index = chars.length() - 1;
if (chars_last_index >= 0) {
// Showing buttons
this.copy.setVisibility(View.VISIBLE);
this.send_to.setVisibility(View.VISIBLE);
this.save_sequence.setVisibility(View.VISIBLE);
// Converting length to integer
String length_as_string = this.length_textview.getText().toString();
int selected_length = Integer.parseInt(length_as_string, 10);
// Generating the string
for (int i = selected_length; i > 0; i--) {
long random = Math.round(Math.random()*chars_last_index);
int index = (int) random;
String to_concat = String.valueOf(chars.charAt(index));
result = result.concat(to_concat);
}
}
else {
// Hiding buttons again
this.copy.setVisibility(View.GONE);
this.send_to.setVisibility(View.GONE);
- this.save_sequence.setVisibility(View.VISIBLE);
+ this.save_sequence.setVisibility(View.GONE);
}
output.setText(result);
break;
case R.id.copy_button:
int sdk = Build.VERSION.SDK_INT;
if (sdk >= 11) {
ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("rgs", this.output.getText());
clipboard.setPrimaryClip(clip);
}
else {
android.text.ClipboardManager old_cbm = (android.text.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
old_cbm.setText(this.output.getText());
}
Toast.makeText(this, R.string.copied_to_cb, Toast.LENGTH_SHORT).show();
break;
case R.id.send_button:
this.send_to_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
this.send_to_intent.setType("text/plain");
this.send_to_intent.putExtra(Intent.EXTRA_TEXT, this.output.getText());
startActivity(Intent.createChooser(this.send_to_intent, getResources().getString(R.string.send)));
break;
case R.id.save_button:
DialogFragment newFragment = new SaveDialog();
newFragment.show(getSupportFragmentManager(), "save_dialog");
break;
default:
break;
}
}
// Next two function are callback function for Save Dialog
// Saving the string if user clicked save on SaveDialog
public void onDialogPositiveClick (DialogFragment dialog, String name) {
CharSequence save_name = name;
CharSequence sequence = this.output.getText();
SharedPreferences sp = this.getSharedPreferences("saved_sequences", MODE_PRIVATE);
Editor ed = sp.edit();
ed.putString(save_name.toString(), sequence.toString());
ed.commit();
}
// Doing nothing when the user press cancel on SaveDialog
public void onDialogNegativeClick (DialogFragment dialog) {
return;
}
}
| true | true | public void onClick (View v) {
int clicked = v.getId();
switch (clicked) {
case R.id.button_create:
String chars = "";
String result = "";
int selected = this.rg.getCheckedRadioButtonId();
switch (selected) {
case R.id.binary_radio:
chars = chars.concat(this.BINARY);
break;
case R.id.hex_radio:
chars = chars.concat(this.HEX);
break;
case R.id.class_radio:
if (this.digit.isChecked()) {
chars = chars.concat(this.DIGIT);
}
if (this.lowercase.isChecked()) {
chars = chars.concat(this.LAZ);
}
if (this.uppercase.isChecked()) {
chars = chars.concat(this.CAZ);
}
if (this.special.isChecked()) {
chars = chars.concat(this.SPECIAL);
}
break;
case R.id.manual_radio:
String chars_to_add = this.manual.getText().toString();
chars = chars.concat(chars_to_add);
break;
default:
break;
}
int chars_last_index = chars.length() - 1;
if (chars_last_index >= 0) {
// Showing buttons
this.copy.setVisibility(View.VISIBLE);
this.send_to.setVisibility(View.VISIBLE);
this.save_sequence.setVisibility(View.VISIBLE);
// Converting length to integer
String length_as_string = this.length_textview.getText().toString();
int selected_length = Integer.parseInt(length_as_string, 10);
// Generating the string
for (int i = selected_length; i > 0; i--) {
long random = Math.round(Math.random()*chars_last_index);
int index = (int) random;
String to_concat = String.valueOf(chars.charAt(index));
result = result.concat(to_concat);
}
}
else {
// Hiding buttons again
this.copy.setVisibility(View.GONE);
this.send_to.setVisibility(View.GONE);
this.save_sequence.setVisibility(View.VISIBLE);
}
output.setText(result);
break;
case R.id.copy_button:
int sdk = Build.VERSION.SDK_INT;
if (sdk >= 11) {
ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("rgs", this.output.getText());
clipboard.setPrimaryClip(clip);
}
else {
android.text.ClipboardManager old_cbm = (android.text.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
old_cbm.setText(this.output.getText());
}
Toast.makeText(this, R.string.copied_to_cb, Toast.LENGTH_SHORT).show();
break;
case R.id.send_button:
this.send_to_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
this.send_to_intent.setType("text/plain");
this.send_to_intent.putExtra(Intent.EXTRA_TEXT, this.output.getText());
startActivity(Intent.createChooser(this.send_to_intent, getResources().getString(R.string.send)));
break;
case R.id.save_button:
DialogFragment newFragment = new SaveDialog();
newFragment.show(getSupportFragmentManager(), "save_dialog");
break;
default:
break;
}
}
| public void onClick (View v) {
int clicked = v.getId();
switch (clicked) {
case R.id.button_create:
String chars = "";
String result = "";
int selected = this.rg.getCheckedRadioButtonId();
switch (selected) {
case R.id.binary_radio:
chars = chars.concat(this.BINARY);
break;
case R.id.hex_radio:
chars = chars.concat(this.HEX);
break;
case R.id.class_radio:
if (this.digit.isChecked()) {
chars = chars.concat(this.DIGIT);
}
if (this.lowercase.isChecked()) {
chars = chars.concat(this.LAZ);
}
if (this.uppercase.isChecked()) {
chars = chars.concat(this.CAZ);
}
if (this.special.isChecked()) {
chars = chars.concat(this.SPECIAL);
}
break;
case R.id.manual_radio:
String chars_to_add = this.manual.getText().toString();
chars = chars.concat(chars_to_add);
break;
default:
break;
}
int chars_last_index = chars.length() - 1;
if (chars_last_index >= 0) {
// Showing buttons
this.copy.setVisibility(View.VISIBLE);
this.send_to.setVisibility(View.VISIBLE);
this.save_sequence.setVisibility(View.VISIBLE);
// Converting length to integer
String length_as_string = this.length_textview.getText().toString();
int selected_length = Integer.parseInt(length_as_string, 10);
// Generating the string
for (int i = selected_length; i > 0; i--) {
long random = Math.round(Math.random()*chars_last_index);
int index = (int) random;
String to_concat = String.valueOf(chars.charAt(index));
result = result.concat(to_concat);
}
}
else {
// Hiding buttons again
this.copy.setVisibility(View.GONE);
this.send_to.setVisibility(View.GONE);
this.save_sequence.setVisibility(View.GONE);
}
output.setText(result);
break;
case R.id.copy_button:
int sdk = Build.VERSION.SDK_INT;
if (sdk >= 11) {
ClipboardManager clipboard = (ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
ClipData clip = ClipData.newPlainText("rgs", this.output.getText());
clipboard.setPrimaryClip(clip);
}
else {
android.text.ClipboardManager old_cbm = (android.text.ClipboardManager)getSystemService(Context.CLIPBOARD_SERVICE);
old_cbm.setText(this.output.getText());
}
Toast.makeText(this, R.string.copied_to_cb, Toast.LENGTH_SHORT).show();
break;
case R.id.send_button:
this.send_to_intent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
this.send_to_intent.setType("text/plain");
this.send_to_intent.putExtra(Intent.EXTRA_TEXT, this.output.getText());
startActivity(Intent.createChooser(this.send_to_intent, getResources().getString(R.string.send)));
break;
case R.id.save_button:
DialogFragment newFragment = new SaveDialog();
newFragment.show(getSupportFragmentManager(), "save_dialog");
break;
default:
break;
}
}
|
diff --git a/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java b/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java
index 143cc7bb4..b7021cd43 100644
--- a/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java
+++ b/preflight/src/main/java/org/apache/pdfbox/preflight/process/AcroFormValidationProcess.java
@@ -1,159 +1,159 @@
/*****************************************************************************
*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you under the Apache License, Version 2.0 (the
* "License"); you may not use this file except in compliance
* with the License. You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing,
* software distributed under the License is distributed on an
* "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY
* KIND, either express or implied. See the License for the
* specific language governing permissions and limitations
* under the License.
*
****************************************************************************/
package org.apache.pdfbox.preflight.process;
import static org.apache.pdfbox.preflight.PreflightConfiguration.ANNOTATIONS_PROCESS;
import static org.apache.pdfbox.preflight.PreflightConstants.ACROFORM_DICTIONARY_KEY_NEED_APPEARANCES;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTIONS_FIELD;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_ACTION_FORBIDDEN_WIDGET_ACTION_FIELD;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_DICT_INVALID;
import static org.apache.pdfbox.preflight.PreflightConstants.ERROR_SYNTAX_NOCATALOG;
import java.io.IOException;
import java.util.List;
import org.apache.pdfbox.cos.COSBase;
import org.apache.pdfbox.cos.COSName;
import org.apache.pdfbox.pdmodel.PDDocumentCatalog;
import org.apache.pdfbox.pdmodel.interactive.action.PDFormFieldAdditionalActions;
import org.apache.pdfbox.pdmodel.interactive.annotation.PDAnnotationWidget;
import org.apache.pdfbox.pdmodel.interactive.form.PDAcroForm;
import org.apache.pdfbox.pdmodel.interactive.form.PDField;
import org.apache.pdfbox.preflight.PreflightConstants;
import org.apache.pdfbox.preflight.PreflightContext;
import org.apache.pdfbox.preflight.ValidationResult.ValidationError;
import org.apache.pdfbox.preflight.exception.ValidationException;
import org.apache.pdfbox.preflight.utils.ContextHelper;
public class AcroFormValidationProcess extends AbstractProcess
{
public void validate(PreflightContext ctx) throws ValidationException
{
PDDocumentCatalog catalog = ctx.getDocument().getDocumentCatalog();
if (catalog != null)
{
PDAcroForm acroForm = catalog.getAcroForm();
if (acroForm != null)
{
checkNeedAppearences(ctx, acroForm);
try
{
exploreFields(ctx, acroForm.getFields());
}
catch (IOException e)
{
throw new ValidationException("Unable to get the list of fields : " + e.getMessage(), e);
}
}
}
else
{
ctx.addValidationError(new ValidationError(ERROR_SYNTAX_NOCATALOG, "There are no Catalog entry in the Document."));
}
}
/**
* This method checks if the NeedAppearances entry is present. If it is, the value must be false.
*
* If the entry is invalid, the ERROR_SYNTAX_DICT_INVALID (1.2.3) error is return.
*
* @param ctx
* @param acroForm
* @param result
*/
protected void checkNeedAppearences(PreflightContext ctx, PDAcroForm acroForm)
{
if (acroForm.getDictionary().getBoolean(ACROFORM_DICTIONARY_KEY_NEED_APPEARANCES, false))
{
addValidationError(ctx, new ValidationError(ERROR_SYNTAX_DICT_INVALID,
"NeedAppearance is present with the value \"true\""));
}
}
/**
* This function explores all fields and their children to check if the A or AA entry is present.
*
* @param ctx
* @param acroForm
* @param result
* @throws IOException
*/
protected boolean exploreFields(PreflightContext ctx, List<?> lFields) throws IOException
{
if (lFields != null)
{ // the list can be null is the Field doesn't have child
for (Object obj : lFields)
{
if (!valideField(ctx, (PDField) obj))
{
return false;
}
}
}
return true;
}
/**
* A and AA field are forbidden, this method checks if they are present and checks all child of this field. If the
* an Additional Action is present the error code ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTIONS_FIELD (6.2.3) is added
* to the error list If the an Action is present (in the Widget Annotation) the error
* ERROR_ACTION_FORBIDDEN_WIDGET_ACTION_FIELD (6.2.4) is added to the error list. (Remark : The widget validation
* will be done by the AnnotationValidationHelper, but some actions are authorized in a standard Widget)
*
* @param ctx
* @param aField
* @return
* @throws IOException
*/
protected boolean valideField(PreflightContext ctx, PDField aField) throws IOException
{
boolean res = true;
PDFormFieldAdditionalActions aa = aField.getActions();
if (aa != null)
{
addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTIONS_FIELD,
"\"AA\" must not be used in a Field dictionary"));
res = false;
}
/*
* The widget validation will be done by the widget annotation, a widget contained in a Field can't have action.
*/
PDAnnotationWidget widget = aField.getWidget();
if (res && widget != null)
{
ContextHelper.validateElement(ctx, widget.getDictionary(), ANNOTATIONS_PROCESS);
COSBase act = widget.getDictionary().getDictionaryObject(COSName.A);
if (act != null)
{
addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_WIDGET_ACTION_FIELD,
- "\"A\" must not be used in a Field dictionary"));
+ "\"A\" must not be used in a widget annotation"));
res = false;
}
}
res = res && exploreFields(ctx, aField.getKids());
return res;
}
}
| true | true | protected boolean valideField(PreflightContext ctx, PDField aField) throws IOException
{
boolean res = true;
PDFormFieldAdditionalActions aa = aField.getActions();
if (aa != null)
{
addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTIONS_FIELD,
"\"AA\" must not be used in a Field dictionary"));
res = false;
}
/*
* The widget validation will be done by the widget annotation, a widget contained in a Field can't have action.
*/
PDAnnotationWidget widget = aField.getWidget();
if (res && widget != null)
{
ContextHelper.validateElement(ctx, widget.getDictionary(), ANNOTATIONS_PROCESS);
COSBase act = widget.getDictionary().getDictionaryObject(COSName.A);
if (act != null)
{
addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_WIDGET_ACTION_FIELD,
"\"A\" must not be used in a Field dictionary"));
res = false;
}
}
res = res && exploreFields(ctx, aField.getKids());
return res;
}
| protected boolean valideField(PreflightContext ctx, PDField aField) throws IOException
{
boolean res = true;
PDFormFieldAdditionalActions aa = aField.getActions();
if (aa != null)
{
addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_ADDITIONAL_ACTIONS_FIELD,
"\"AA\" must not be used in a Field dictionary"));
res = false;
}
/*
* The widget validation will be done by the widget annotation, a widget contained in a Field can't have action.
*/
PDAnnotationWidget widget = aField.getWidget();
if (res && widget != null)
{
ContextHelper.validateElement(ctx, widget.getDictionary(), ANNOTATIONS_PROCESS);
COSBase act = widget.getDictionary().getDictionaryObject(COSName.A);
if (act != null)
{
addValidationError(ctx, new ValidationError(ERROR_ACTION_FORBIDDEN_WIDGET_ACTION_FIELD,
"\"A\" must not be used in a widget annotation"));
res = false;
}
}
res = res && exploreFields(ctx, aField.getKids());
return res;
}
|
diff --git a/src/jvm/clojure/lang/ASeq.java b/src/jvm/clojure/lang/ASeq.java
index aa02aa98..0a31797c 100644
--- a/src/jvm/clojure/lang/ASeq.java
+++ b/src/jvm/clojure/lang/ASeq.java
@@ -1,74 +1,74 @@
/**
* Copyright (c) Rich Hickey. All rights reserved.
* The use and distribution terms for this software are covered by the
* Common Public License 1.0 (http://opensource.org/licenses/cpl.php)
* which can be found in the file CPL.TXT at the root of this distribution.
* By using this software in any fashion, you are agreeing to be bound by
* the terms of this license.
* You must not remove this notice, or any other, from this software.
**/
package clojure.lang;
public abstract class ASeq extends Obj implements ISeq{
transient int _hash = -1;
protected ASeq(IPersistentMap meta){
super(meta);
}
protected ASeq(){
}
public boolean equals(Object obj){
if(!(obj instanceof Sequential))
return false;
ISeq ms = ((IPersistentCollection) obj).seq();
for(ISeq s = seq(); s != null; s = s.rest(), ms = ms.rest())
{
if(ms == null || !RT.equal(s.first(), ms.first()))
return false;
}
- if(ms.rest() != null)
+ if(ms != null)
return false;
return true;
}
public int hashCode(){
if(_hash == -1)
{
int hash = 0;
for(ISeq s = seq(); s != null; s = s.rest())
{
hash = RT.hashCombine(hash, RT.hash(s.first()));
}
this._hash = hash;
}
return _hash;
}
public Object peek(){
return first();
}
public IPersistentList pop(){
return rest();
}
public int count(){
return 1 + RT.count(rest());
}
public ISeq seq(){
return this;
}
public ISeq cons(Object o){
return new Cons(o, this);
}
}
| true | true | public boolean equals(Object obj){
if(!(obj instanceof Sequential))
return false;
ISeq ms = ((IPersistentCollection) obj).seq();
for(ISeq s = seq(); s != null; s = s.rest(), ms = ms.rest())
{
if(ms == null || !RT.equal(s.first(), ms.first()))
return false;
}
if(ms.rest() != null)
return false;
return true;
}
| public boolean equals(Object obj){
if(!(obj instanceof Sequential))
return false;
ISeq ms = ((IPersistentCollection) obj).seq();
for(ISeq s = seq(); s != null; s = s.rest(), ms = ms.rest())
{
if(ms == null || !RT.equal(s.first(), ms.first()))
return false;
}
if(ms != null)
return false;
return true;
}
|
diff --git a/src/main/java/edu/cshl/schatz/jnomics/manager/client/GlobusPasswordPrompter.java b/src/main/java/edu/cshl/schatz/jnomics/manager/client/GlobusPasswordPrompter.java
index 13fbcee..c08b317 100644
--- a/src/main/java/edu/cshl/schatz/jnomics/manager/client/GlobusPasswordPrompter.java
+++ b/src/main/java/edu/cshl/schatz/jnomics/manager/client/GlobusPasswordPrompter.java
@@ -1,93 +1,99 @@
package edu.cshl.schatz.jnomics.manager.client;
import com.mongodb.DBObject;
import com.mongodb.util.JSON;
import org.apache.commons.codec.binary.Base64;
import javax.net.ssl.*;
import java.io.*;
import java.net.URL;
import java.security.SecureRandom;
import java.security.cert.X509Certificate;
import java.util.Properties;
/**
* User: james
*/
public class GlobusPasswordPrompter {
public static String GLOBUS_API_URL = "https://nexus.api.globusonline.org/goauth/token?grant_type=client_credentials";
private static TrustManager[] trustAllCerts = new TrustManager[] {
new X509TrustManager() {
public X509Certificate[] getAcceptedIssuers() {
return new X509Certificate[0];
}
public void checkClientTrusted(X509Certificate[] certs, String authType) {}
public void checkServerTrusted(X509Certificate[] certs, String authType) {}
}};
// Ignore differences between given hostname and certificate hostname
private static HostnameVerifier hostVerifier = new HostnameVerifier() {
public boolean verify(String hostname, SSLSession session) { return true; }
};
private static String readData(InputStream stream) throws IOException {
byte []data = new byte[10240];
StringBuilder builder = new StringBuilder();
while(-1 != stream.read(data)){
builder.append(new String(data));
}
return builder.toString();
}
public static void getPasswordFromUser() throws Exception {
Console console = System.console();
System.out.println();
System.out.println("Please authenticate with Globus Online:");
String username = console.readLine("[%s]","Username:");
String passwd = new String(console.readPassword("[%s]", "Password:"));
getPasswordFromUser(username,passwd);
}
public static void getPasswordFromUser(String user, String passwd) throws Exception{
URL url = new URL(GLOBUS_API_URL);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hostVerifier);
String up_str = user + ":" + passwd;
String up_encoded = new String(Base64.encodeBase64(up_str.getBytes()));
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Authorization","Basic " + up_encoded );
- InputStream inStream = conn.getInputStream();
+ InputStream inStream = null;
+ try{
+ inStream = conn.getInputStream();
+ }catch(Exception e){
+ System.out.println("Bad username/password");
+ System.exit(1);
+ }
String data = readData(inStream);
DBObject jobject = (DBObject) JSON.parse(data);
String token = (String)jobject.get("access_token");
File jconf_dir = JnomicsClientEnvironment.USER_CONF_DIR;
if(!jconf_dir.exists()){
jconf_dir.mkdir();
}
File auth_file = JnomicsClientEnvironment.USER_AUTH_FILE;
Properties properties = new Properties();
if(!auth_file.exists()){
System.out.println(auth_file);
auth_file.createNewFile();
}else{
properties.load(new FileInputStream(auth_file));
}
properties.setProperty("token",token);
properties.store(new FileOutputStream(auth_file),"Globus Online Authentication Token");
}
}
| true | true | public static void getPasswordFromUser(String user, String passwd) throws Exception{
URL url = new URL(GLOBUS_API_URL);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hostVerifier);
String up_str = user + ":" + passwd;
String up_encoded = new String(Base64.encodeBase64(up_str.getBytes()));
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Authorization","Basic " + up_encoded );
InputStream inStream = conn.getInputStream();
String data = readData(inStream);
DBObject jobject = (DBObject) JSON.parse(data);
String token = (String)jobject.get("access_token");
File jconf_dir = JnomicsClientEnvironment.USER_CONF_DIR;
if(!jconf_dir.exists()){
jconf_dir.mkdir();
}
File auth_file = JnomicsClientEnvironment.USER_AUTH_FILE;
Properties properties = new Properties();
if(!auth_file.exists()){
System.out.println(auth_file);
auth_file.createNewFile();
}else{
properties.load(new FileInputStream(auth_file));
}
properties.setProperty("token",token);
properties.store(new FileOutputStream(auth_file),"Globus Online Authentication Token");
}
| public static void getPasswordFromUser(String user, String passwd) throws Exception{
URL url = new URL(GLOBUS_API_URL);
SSLContext sc = SSLContext.getInstance("SSL");
sc.init(null, trustAllCerts, new SecureRandom());
HttpsURLConnection.setDefaultSSLSocketFactory(sc.getSocketFactory());
HttpsURLConnection.setDefaultHostnameVerifier(hostVerifier);
String up_str = user + ":" + passwd;
String up_encoded = new String(Base64.encodeBase64(up_str.getBytes()));
HttpsURLConnection conn = (HttpsURLConnection) url.openConnection();
conn.setRequestProperty("Authorization","Basic " + up_encoded );
InputStream inStream = null;
try{
inStream = conn.getInputStream();
}catch(Exception e){
System.out.println("Bad username/password");
System.exit(1);
}
String data = readData(inStream);
DBObject jobject = (DBObject) JSON.parse(data);
String token = (String)jobject.get("access_token");
File jconf_dir = JnomicsClientEnvironment.USER_CONF_DIR;
if(!jconf_dir.exists()){
jconf_dir.mkdir();
}
File auth_file = JnomicsClientEnvironment.USER_AUTH_FILE;
Properties properties = new Properties();
if(!auth_file.exists()){
System.out.println(auth_file);
auth_file.createNewFile();
}else{
properties.load(new FileInputStream(auth_file));
}
properties.setProperty("token",token);
properties.store(new FileOutputStream(auth_file),"Globus Online Authentication Token");
}
|
diff --git a/src/main/java/org/wikipathways/cytoscapeapp/internal/io/GpmlVizStyle.java b/src/main/java/org/wikipathways/cytoscapeapp/internal/io/GpmlVizStyle.java
index 9ddf3a1..825f92f 100644
--- a/src/main/java/org/wikipathways/cytoscapeapp/internal/io/GpmlVizStyle.java
+++ b/src/main/java/org/wikipathways/cytoscapeapp/internal/io/GpmlVizStyle.java
@@ -1,30 +1,31 @@
package org.wikipathways.cytoscapeapp.internal.io;
import org.cytoscape.view.model.CyNetworkView;
import org.cytoscape.view.vizmap.VisualStyleFactory;
import org.cytoscape.view.vizmap.VisualMappingManager;
import org.cytoscape.view.vizmap.VisualStyle;
import org.cytoscape.view.presentation.property.BasicVisualLexicon;
import java.awt.Color;
public class GpmlVizStyle {
final VisualMappingManager vizMapMgr;
final VisualStyle vizStyle;
public GpmlVizStyle(final VisualStyleFactory vizStyleFactory, final VisualMappingManager vizMapMgr) {
this.vizMapMgr = vizMapMgr;
this.vizStyle = create(vizStyleFactory, vizMapMgr);
}
private static VisualStyle create(final VisualStyleFactory vizStyleFactory, final VisualMappingManager vizMapMgr) {
final VisualStyle vizStyle = vizStyleFactory.createVisualStyle(vizMapMgr.getDefaultVisualStyle());
vizStyle.setTitle("WikiPathways");
vizStyle.setDefaultValue(BasicVisualLexicon.NODE_FILL_COLOR, Color.WHITE);
+ vizStyle.setDefaultValue(BasicVisualLexicon.NODE_LABEL_COLOR, Color.BLACK);
vizMapMgr.addVisualStyle(vizStyle);
return vizStyle;
}
public void apply(final CyNetworkView view) {
vizMapMgr.setVisualStyle(vizStyle, view);
}
}
| true | true | private static VisualStyle create(final VisualStyleFactory vizStyleFactory, final VisualMappingManager vizMapMgr) {
final VisualStyle vizStyle = vizStyleFactory.createVisualStyle(vizMapMgr.getDefaultVisualStyle());
vizStyle.setTitle("WikiPathways");
vizStyle.setDefaultValue(BasicVisualLexicon.NODE_FILL_COLOR, Color.WHITE);
vizMapMgr.addVisualStyle(vizStyle);
return vizStyle;
}
| private static VisualStyle create(final VisualStyleFactory vizStyleFactory, final VisualMappingManager vizMapMgr) {
final VisualStyle vizStyle = vizStyleFactory.createVisualStyle(vizMapMgr.getDefaultVisualStyle());
vizStyle.setTitle("WikiPathways");
vizStyle.setDefaultValue(BasicVisualLexicon.NODE_FILL_COLOR, Color.WHITE);
vizStyle.setDefaultValue(BasicVisualLexicon.NODE_LABEL_COLOR, Color.BLACK);
vizMapMgr.addVisualStyle(vizStyle);
return vizStyle;
}
|
diff --git a/src/web/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java b/src/web/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java
index f8fb1967f..2415eb717 100644
--- a/src/web/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java
+++ b/src/web/org/codehaus/groovy/grails/web/servlet/GrailsDispatcherServlet.java
@@ -1,101 +1,102 @@
/*
* Copyright 2004-2005 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.codehaus.groovy.grails.web.servlet;
import org.codehaus.groovy.grails.commons.GrailsApplication;
import org.codehaus.groovy.grails.commons.GrailsBootstrapClass;
import org.codehaus.groovy.grails.commons.spring.SpringConfig;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.util.StringUtils;
import org.springframework.web.context.ConfigurableWebApplicationContext;
import org.springframework.web.context.WebApplicationContext;
import org.springframework.web.context.support.XmlWebApplicationContext;
import org.springframework.web.servlet.DispatcherServlet;
import org.springmodules.beans.factory.drivers.xml.XmlWebApplicationContextDriver;
/**
* <p>Servlet that handles incoming requests for Grails.
* <p/>
* <p>This servlet loads the Spring configuration based on the Grails application
* in the parent application context.
*
* @author Steven Devijver
* @since Jul 2, 2005
*/
public class GrailsDispatcherServlet extends DispatcherServlet {
private static final String GRAILS_APPLICATION_ID = "grailsApplication";
private static final String GRAILS_APPLICATION_CONTEXT = "grailsApplicationContext";
public GrailsDispatcherServlet() {
super();
}
protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException {
// use config file locations if available
ApplicationContext grailsContext = (ApplicationContext)getServletContext().getAttribute(GRAILS_APPLICATION_CONTEXT );
GrailsApplication application;
WebApplicationContext webContext;
if(grailsContext != null) {
XmlWebApplicationContext xmlContext = new XmlWebApplicationContext();
xmlContext.setParent(grailsContext);
webContext = xmlContext;
application = (GrailsApplication) webContext.getBean(GRAILS_APPLICATION_ID, GrailsApplication.class);
}
else {
String[] locations = null;
if (null != getContextConfigLocation()) {
locations = StringUtils.tokenizeToStringArray(
getContextConfigLocation(),
ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS);
}
// construct the SpringConfig for the container managed application
application = (GrailsApplication) parent.getBean(GRAILS_APPLICATION_ID, GrailsApplication.class);
SpringConfig springConfig = new SpringConfig(application);
// return a context that obeys grails' settings
webContext = new XmlWebApplicationContextDriver().getWebApplicationContext(
springConfig.getBeanReferences(),
parent,
getServletContext(),
getNamespace(),
locations);
+ getServletContext().setAttribute(GRAILS_APPLICATION_CONTEXT,webContext );
}
// init the Grails application
GrailsBootstrapClass[] bootstraps = application.getGrailsBootstrapClasses();
for (int i = 0; i < bootstraps.length; i++) {
bootstraps[i].callInit( getServletContext() );
}
return webContext;
}
public void destroy() {
WebApplicationContext webContext = getWebApplicationContext();
GrailsApplication application = (GrailsApplication) webContext.getBean(GRAILS_APPLICATION_ID, GrailsApplication.class);
GrailsBootstrapClass[] bootstraps = application.getGrailsBootstrapClasses();
for (int i = 0; i < bootstraps.length; i++) {
bootstraps[i].callDestroy();
}
// call super
super.destroy();
}
}
| true | true | protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException {
// use config file locations if available
ApplicationContext grailsContext = (ApplicationContext)getServletContext().getAttribute(GRAILS_APPLICATION_CONTEXT );
GrailsApplication application;
WebApplicationContext webContext;
if(grailsContext != null) {
XmlWebApplicationContext xmlContext = new XmlWebApplicationContext();
xmlContext.setParent(grailsContext);
webContext = xmlContext;
application = (GrailsApplication) webContext.getBean(GRAILS_APPLICATION_ID, GrailsApplication.class);
}
else {
String[] locations = null;
if (null != getContextConfigLocation()) {
locations = StringUtils.tokenizeToStringArray(
getContextConfigLocation(),
ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS);
}
// construct the SpringConfig for the container managed application
application = (GrailsApplication) parent.getBean(GRAILS_APPLICATION_ID, GrailsApplication.class);
SpringConfig springConfig = new SpringConfig(application);
// return a context that obeys grails' settings
webContext = new XmlWebApplicationContextDriver().getWebApplicationContext(
springConfig.getBeanReferences(),
parent,
getServletContext(),
getNamespace(),
locations);
}
// init the Grails application
GrailsBootstrapClass[] bootstraps = application.getGrailsBootstrapClasses();
for (int i = 0; i < bootstraps.length; i++) {
bootstraps[i].callInit( getServletContext() );
}
return webContext;
}
| protected WebApplicationContext createWebApplicationContext(WebApplicationContext parent) throws BeansException {
// use config file locations if available
ApplicationContext grailsContext = (ApplicationContext)getServletContext().getAttribute(GRAILS_APPLICATION_CONTEXT );
GrailsApplication application;
WebApplicationContext webContext;
if(grailsContext != null) {
XmlWebApplicationContext xmlContext = new XmlWebApplicationContext();
xmlContext.setParent(grailsContext);
webContext = xmlContext;
application = (GrailsApplication) webContext.getBean(GRAILS_APPLICATION_ID, GrailsApplication.class);
}
else {
String[] locations = null;
if (null != getContextConfigLocation()) {
locations = StringUtils.tokenizeToStringArray(
getContextConfigLocation(),
ConfigurableWebApplicationContext.CONFIG_LOCATION_DELIMITERS);
}
// construct the SpringConfig for the container managed application
application = (GrailsApplication) parent.getBean(GRAILS_APPLICATION_ID, GrailsApplication.class);
SpringConfig springConfig = new SpringConfig(application);
// return a context that obeys grails' settings
webContext = new XmlWebApplicationContextDriver().getWebApplicationContext(
springConfig.getBeanReferences(),
parent,
getServletContext(),
getNamespace(),
locations);
getServletContext().setAttribute(GRAILS_APPLICATION_CONTEXT,webContext );
}
// init the Grails application
GrailsBootstrapClass[] bootstraps = application.getGrailsBootstrapClasses();
for (int i = 0; i < bootstraps.length; i++) {
bootstraps[i].callInit( getServletContext() );
}
return webContext;
}
|
diff --git a/src/main/java/org/utgenome/weaver/align/BitParallelSmithWaterman.java b/src/main/java/org/utgenome/weaver/align/BitParallelSmithWaterman.java
index f1db812..b98d6c9 100755
--- a/src/main/java/org/utgenome/weaver/align/BitParallelSmithWaterman.java
+++ b/src/main/java/org/utgenome/weaver/align/BitParallelSmithWaterman.java
@@ -1,621 +1,622 @@
/*--------------------------------------------------------------------------
* Copyright 2011 utgenome.org
*
* 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.
*--------------------------------------------------------------------------*/
//--------------------------------------
// genome-weaver Project
//
// BitParallelSmithWaterman.java
// Since: 2011/07/28
//
// $URL$
// $Author$
//--------------------------------------
package org.utgenome.weaver.align;
import java.util.Arrays;
import org.utgenome.weaver.align.SmithWatermanAligner.Alignment;
import org.utgenome.weaver.align.SmithWatermanAligner.Trace;
import org.utgenome.weaver.align.record.SWResult;
import org.xerial.util.log.Logger;
/**
* Bit-parallel algorithm for Smith-Waterman alignment
*
* <h3>References</h3>
*
* <ul>
* <li>Myers, G. (1999). A fast bit-vector algorithm for approximate string
* matching based on dynamic programming. Journal of the ACM (JACM).</li>
* <li>H. Hyyrö and G. Navarro. Faster Bit-parallel Approximate String
* Matching In Proc. 13th Combinatorial Pattern Matching (CPM'2002), LNCS 2373
* http://sunsite.dcc.uchile.cl/ftp/users/gnavarro/hn02.ps.gz</li>
* </ul>
*
* @author leo
*
*/
public class BitParallelSmithWaterman
{
private static Logger _logger = Logger.getLogger(BitParallelSmithWaterman.class);
public static void align64(ACGTSequence ref, ACGTSequence query, int numAllowedDiff) {
new Align64(ref, query).globalMatch(numAllowedDiff);
}
public static void localAlign64(ACGTSequence ref, ACGTSequence query, int numAllowedDiff) {
new Align64(ref, query).localMatch(numAllowedDiff);
}
public static class Align64
{
private final ACGTSequence ref;
private final ACGTSequence query;
private final long[] pm;
private final int m;
private final int n;
public Align64(ACGTSequence ref, ACGTSequence query) {
this.ref = ref;
this.query = query;
this.m = (int) query.textSize();
this.n = (int) ref.textSize();
// Preprocessing
pm = new long[ACGT.values().length];
int m = Math.min(64, (int) query.textSize());
for (int i = 0; i < m; ++i) {
pm[query.getACGT(i).code] |= 1L << i;
}
}
public void globalMatch(int k) {
align(m, ~0L, 0L, k);
}
public void localMatch(int k) {
align(0, 0L, 0L, k);
}
protected void align(int score, long vp, long vn, int k) {
// if (_logger.isDebugEnabled()) {
// for (ACGT ch : ACGT.exceptN) {
// _logger.debug("peq[%s]:%s", ch, toBinary(pm[ch.code], m));
// }
// }
for (int j = 0; j < n; ++j) {
long x = pm[ref.getACGT(j).code];
long d0 = ((vp + (x & vp)) ^ vp) | x | vn;
long hp = (vn | ~(vp | d0));
long hn = vp & d0;
x = (hp << 1);
vn = x & d0;
vp = (hn << 1) | ~(x | d0);
// diff represents the last row (C[m, j]) of the DP matrix
score += (int) ((hp >>> (m - 1)) & 1L);
score -= (int) ((hn >>> (m - 1)) & 1L);
// if (_logger.isDebugEnabled()) {
// _logger.debug("[%s] j:%2d, score:%2d %1s hp:%s, hn:%s, vp:%s, vn:%s, d0:%s", ref.getACGT(j), j,
// score, score <= k ? "*" : "", toBinary(hp, m), toBinary(hn, m), toBinary(vp, m),
// toBinary(vn, m), toBinary(d0, m));
// }
}
}
}
public static String toBinary(long v, int m) {
StringBuilder s = new StringBuilder();
for (int i = m - 1; i >= 0; --i) {
s.append((v & (1L << i)) > 0 ? "1" : "0");
}
return s.toString();
}
public static SWResult alignBlock(String ref, String query, int k) {
return alignBlock(new ACGTSequence(ref), new ACGTSequence(query), k);
}
public static SWResult alignBlock(ACGTSequence ref, ACGTSequence query, int k) {
AlignBlocks a = new AlignBlocks((int) query.textSize(), k);
SWResult sw = a.align(ref, query);
return sw;
}
public static Alignment alignBlockDetailed(String ref, String query, int k) {
return alignBlockDetailed(new ACGTSequence(ref), new ACGTSequence(query), k);
}
public static Alignment alignBlockDetailed(ACGTSequence ref, ACGTSequence query, int k) {
AlignBlocksDetailed a = new AlignBlocksDetailed((int) query.textSize(), k);
SWResult bestHit = a.align(ref, query);
return a.traceback(ref, query, bestHit);
}
public static void alignBlockDetailedNoTraceBack(ACGTSequence ref, ACGTSequence query, int k) {
AlignBlocksDetailed a = new AlignBlocksDetailed((int) query.textSize(), k);
SWResult bestHit = a.align(ref, query);
//return a.traceback(ref, query, bestHit);
}
static SWResult alignBlock(ACGTSequence ref, ACGTSequence query, int k, int w) {
AlignBlocks a = new AlignBlocks(w, (int) query.textSize(), k);
return a.align(ref, query);
}
/**
* Block-based aligment for more than 64-bit queries
*
* @author leo
*
*/
public static class AlignBlocks
{
private static final int Z = ACGT.values().length; // alphabet size
private final int w; // word size
private final int k;
private final int m;
private final int bMax;
private long[] vp;
private long[] vn;
private long[][] peq; // [A, C, G, T][# of block]
private int[] D; // D[block]
public AlignBlocks(int m, int k) {
this(64, m, k);
}
public AlignBlocks(int w, int m, int k) {
this.w = w;
this.m = m;
this.k = k;
bMax = Math.max(1, (m + w - 1) / w);
vp = new long[bMax];
vn = new long[bMax];
peq = new long[Z][bMax];
D = new int[bMax];
}
public void clear() {
Arrays.fill(vp, 0L);
Arrays.fill(vn, 0L);
for (int i = 0; i < Z; ++i)
for (int j = 0; j < bMax; ++j)
peq[i][j] = 0L;
}
public SWResult align(ACGTSequence ref, ACGTSequence query) {
QueryMask qm = new QueryMask(query);
return align(ref, qm);
}
public SWResult align(ACGTSequence ref, QueryMask qMask) {
// Peq bit-vector holds flags of the character occurrence positions in the query
for (ACGT ch : ACGT.exceptN) {
for (int i = 0; i < bMax; ++i) {
peq[ch.code][i] = qMask.getPatternMaskIn64bit(ch, i, w);
}
}
// Fill the flanking region with 1s
{
int f = m % w;
long mask = f == 0 ? 0L : (~0L << f);
for (int i = 0; i < Z; ++i) {
//peq[i][bMax - 1] |= mask;
}
}
// if (_logger.isTraceEnabled()) {
// _logger.trace("peq:%s", qMask);
// }
return align(ref);
}
private SWResult align(ACGTSequence ref) {
SWResult bestHit = null;
final int N = (int) ref.textSize();
final int W = w - (int) ref.textSize() % w;
// Initialize the vertical input
for (int r = 0; r < bMax; ++r) {
vp[r] = ~0L; // all 1s
vn[r] = 0L; // all 0s
}
// Init the score
D[0] = w;
int b = Math.max(1, (k + w - 1) / w);
for (int j = 0; j < N; ++j) {
ACGT ch = ref.getACGT(j);
int carry = 0;
for (int r = 0; r < b; ++r) {
int nextScore = alignBlock(j, ch, r, carry);
D[r] += nextScore;
// if (_logger.isTraceEnabled()) {
// _logger.trace("j:%d[%s], hin:%2d, hout:%2d, D%d:%d", j, ref.getACGT(j), carry, nextScore, r,
// D[r]);
// }
carry = nextScore;
}
if (b < bMax && D[b - 1] - carry <= k && (((peq[ch.code][b] & 1L) != 0L) | carry < 0)) {
b++;
int nextScore = alignBlock(j, ch, b - 1, carry);
D[b - 1] = D[b - 2] + w - carry + nextScore;
// if (_logger.isTraceEnabled()) {
// _logger.trace("j:%d[%s], hin:%2d, hout:%2d, D%d:%d", j, ref.getACGT(j), carry, nextScore,
// b - 1, D[b - 1]);
// }
}
else {
while (b > 1 && D[b - 1] >= k + w) {
--b;
}
}
if (b == bMax) {
// if (D[b - 1] <= W + k) {
// if (_logger.isTraceEnabled())
// _logger.trace("match at %d", j);
// }
if (bestHit == null) {
bestHit = new SWResult(j, D[b - 1] - W);
continue;
}
if (bestHit.diff > D[b - 1] - W) {
bestHit = new SWResult(j, D[b - 1] - W);
}
}
}
return bestHit;
}
private int alignBlock(int j, ACGT ch, int r, int hin) {
long vp = this.vp[r];
long vn = this.vn[r];
long x = this.peq[ch.code][r];
if (hin < 0)
x |= 1L;
long d0 = ((vp + (x & vp)) ^ vp) | x | vn;
long hn = vp & d0;
long hp = (vn | ~(vp | d0));
int hout = 0;
hout += (int) ((hp >>> (w - 1)) & 1L);
hout -= (int) ((hn >>> (w - 1)) & 1L);
long hp2 = (hp << 1);
long hn2 = (hn << 1);
if (hin < 0)
hn2 |= 1L;
if (hin > 0)
hp2 |= 1L;
this.vp[r] = hn2 | ~(hp2 | d0);
this.vn[r] = hp2 & d0;
// if (_logger.isTraceEnabled()) {
// _logger.trace("[%s] j:%2d, block:%d, hin:%2d, hout:%2d, hp:%s, hn:%s, vp:%s, vn:%s, d0:%s", ch, j, r,
// hin, hout, toBinary(hp, w), toBinary(hn, w), toBinary(this.vp[r], w), toBinary(this.vn[r], w),
// toBinary(d0, w));
// }
return hout;
}
}
/**
* Extension of the AlignBlock algorithm to calculate the actual alignment
* (CIGAR)
*
* @author leo
*
*/
public static class AlignBlocksDetailed
{
private static final int Z = ACGT.values().length; // alphabet size
private final int w; // word size
private final int k;
private final int m;
private final int bMax;
private long[][] peq; // [A, C, G, T][# of block]
private int[] D; // D[block]
private long[][] vp;
private long[][] vn;
public AlignBlocksDetailed(int m, int k) {
this(64, m, k);
}
public AlignBlocksDetailed(int w, int m, int k) {
this.w = w;
this.m = m;
this.k = k;
bMax = Math.max(1, (m + w - 1) / w);
peq = new long[Z][bMax];
D = new int[bMax];
}
public SWResult align(ACGTSequence ref, ACGTSequence query) {
QueryMask qm = new QueryMask(query);
return align(ref, qm);
}
public SWResult align(ACGTSequence ref, QueryMask qMask) {
// Peq bit-vector holds flags of the character occurrence positions in the query
for (ACGT ch : ACGT.exceptN) {
for (int i = 0; i < bMax; ++i) {
peq[ch.code][i] = qMask.getPatternMaskIn64bit(ch, i, w);
}
}
return align(ref);
}
private SWResult align(ACGTSequence ref) {
SWResult bestHit = null;
final int N = (int) ref.textSize();
final int W = w - (int) ref.textSize() % w;
// Prepare the score matrix
vp = new long[bMax][N + 1];
vn = new long[bMax][N + 1];
// Initialize the vertical input
for (int r = 0; r < bMax; ++r) {
vp[r][0] = ~0L; // all 1s
vn[r][0] = 0L; // all 0s
}
// Init the score
D[0] = w;
int b = Math.max(1, (k + w - 1) / w);
for (int j = 0; j < N; ++j) {
ACGT ch = ref.getACGT(j);
int carry = 0;
for (int r = 0; r < b; ++r) {
int nextScore = alignBlock(j, ch, r, carry);
D[r] += nextScore;
carry = nextScore;
}
if (b < bMax && D[b - 1] - carry <= k && (((peq[ch.code][b] & 1L) != 0L) | carry < 0)) {
b++;
int nextScore = alignBlock(j, ch, b - 1, carry);
D[b - 1] = D[b - 2] + w - carry + nextScore;
}
else {
while (b > 1 && D[b - 1] >= k + w) {
--b;
}
}
if (b == bMax) {
if (bestHit == null) {
bestHit = new SWResult(j, D[b - 1] - W);
continue;
}
if (bestHit.diff > D[b - 1] - W) {
bestHit = new SWResult(j, D[b - 1] - W);
}
}
}
return bestHit;
}
private int alignBlock(int j, ACGT ch, int r, int hin) {
long vp = this.vp[r][j];
long vn = this.vn[r][j];
long x = this.peq[ch.code][r];
if (hin < 0)
x |= 1L;
long d0 = ((vp + (x & vp)) ^ vp) | x | vn;
long hn = vp & d0;
long hp = (vn | ~(vp | d0));
int hout = 0;
hout += (int) ((hp >>> (w - 1)) & 1L);
hout -= (int) ((hn >>> (w - 1)) & 1L);
long hp2 = (hp << 1);
long hn2 = (hn << 1);
if (hin < 0)
hn2 |= 1L;
if (hin > 0)
hp2 |= 1L;
this.vp[r][j + 1] = hn2 | ~(hp2 | d0);
this.vn[r][j + 1] = hp2 & d0;
return hout;
}
public Alignment traceback(ACGTSequence ref, ACGTSequence query, SWResult bestHit) {
if (bestHit == null)
return null;
final int N = (int) ref.textSize();
int maxRow = m - 1;
int maxCol = bestHit.tailPos;
StringBuilder cigar = new StringBuilder();
StringBuilder a1 = new StringBuilder();
StringBuilder a2 = new StringBuilder();
int leftMostPos = 0; // in reference seq
// Append soft-clipped part in the query sequence
for (int i = m - 1; i > maxRow; --i) {
cigar.append("S");
}
int row = m - 1;
int col = N - 1;
// Append clipped sequences
while (col > maxCol) {
a1.append(ref.charAt(col - 1));
col--;
}
while (row > maxRow) {
a2.append(query.getACGT(row - 1).toChar());
row--;
}
// Trace back
int diff = 0;
traceback: for (col = maxCol, row = maxRow;;) {
Trace path = Trace.NONE;
// Calculate path
if (col >= 0 && row >= 0) {
int block = row / w;
int offset = row % w;
long vpf = vp[block][col] & (1L << offset);
long vnf = vn[block][col] & (1L << offset);
if (ref.getACGT(col) == query.getACGT(row)) {
path = Trace.DIAGONAL;
}
else if (vpf != 0L) {
path = Trace.UP;
diff++;
}
else if (vnf == 0L) {
+ // TODO no path to this. Fix me
path = Trace.DIAGONAL;
diff++;
}
else {
path = Trace.LEFT;
diff++;
}
}
switch (path) {
case DIAGONAL:
// match
cigar.append("M");
a1.append(ref.charAt(col));
a2.append(query.charAt(row));
leftMostPos = col;
col--;
row--;
break;
case UP:
// insertion
cigar.append("I");
a1.append("-");
a2.append(query.charAt(row));
leftMostPos = col + 1;
row--;
break;
case LEFT:
cigar.append("D");
a1.append(ref.charAt(col));
a2.append("-");
col--;
break;
case NONE:
while (col >= 0 || row >= 0) {
if (row >= 0) {
cigar.append("S");
a1.append(col >= 0 ? ref.charAt(col) : ' ');
a2.append(Character.toLowerCase(query.charAt(row)));
}
else {
a1.append(col >= 0 ? ref.charAt(col) : ' ');
a2.append(' ');
}
col--;
row--;
}
break traceback; // exit the loop
}
}
String cigarStr = cigar.reverse().toString();
{
// Remove indels at both of the read ends
int left = 0, right = 0;
for (int i = 0; i < cigarStr.length(); ++i) {
char t = cigarStr.charAt(i);
if (t == 'S' || t == 'I' || t == 'D') {
left++;
}
else
break;
}
for (int i = cigarStr.length() - 1; i >= left; --i) {
char t = cigarStr.charAt(i);
if (t == 'S' || t == 'I' || t == 'D') {
right++;
}
else
break;
}
StringBuilder newCigar = new StringBuilder();
for (int i = 0; i < left; ++i)
newCigar.append('S');
newCigar.append(cigarStr.substring(left, cigarStr.length() - right));
for (int i = 0; i < right; ++i)
newCigar.append('S');
cigarStr = newCigar.toString();
}
// create cigar string
char prev = cigarStr.charAt(0);
int count = 1;
StringBuilder compactCigar = new StringBuilder();
for (int i = 1; i < cigarStr.length(); ++i) {
char c = cigarStr.charAt(i);
if (prev == c) {
count++;
}
else {
compactCigar.append(Integer.toString(count));
compactCigar.append(prev);
prev = c;
count = 1;
}
}
if (count > 0) {
compactCigar.append(Integer.toString(count));
compactCigar.append(prev);
}
return new Alignment(compactCigar.toString(), m - diff, a1.reverse().toString(), leftMostPos, a2.reverse()
.toString());
}
}
}
| true | true | public Alignment traceback(ACGTSequence ref, ACGTSequence query, SWResult bestHit) {
if (bestHit == null)
return null;
final int N = (int) ref.textSize();
int maxRow = m - 1;
int maxCol = bestHit.tailPos;
StringBuilder cigar = new StringBuilder();
StringBuilder a1 = new StringBuilder();
StringBuilder a2 = new StringBuilder();
int leftMostPos = 0; // in reference seq
// Append soft-clipped part in the query sequence
for (int i = m - 1; i > maxRow; --i) {
cigar.append("S");
}
int row = m - 1;
int col = N - 1;
// Append clipped sequences
while (col > maxCol) {
a1.append(ref.charAt(col - 1));
col--;
}
while (row > maxRow) {
a2.append(query.getACGT(row - 1).toChar());
row--;
}
// Trace back
int diff = 0;
traceback: for (col = maxCol, row = maxRow;;) {
Trace path = Trace.NONE;
// Calculate path
if (col >= 0 && row >= 0) {
int block = row / w;
int offset = row % w;
long vpf = vp[block][col] & (1L << offset);
long vnf = vn[block][col] & (1L << offset);
if (ref.getACGT(col) == query.getACGT(row)) {
path = Trace.DIAGONAL;
}
else if (vpf != 0L) {
path = Trace.UP;
diff++;
}
else if (vnf == 0L) {
path = Trace.DIAGONAL;
diff++;
}
else {
path = Trace.LEFT;
diff++;
}
}
switch (path) {
case DIAGONAL:
// match
cigar.append("M");
a1.append(ref.charAt(col));
a2.append(query.charAt(row));
leftMostPos = col;
col--;
row--;
break;
case UP:
// insertion
cigar.append("I");
a1.append("-");
a2.append(query.charAt(row));
leftMostPos = col + 1;
row--;
break;
case LEFT:
cigar.append("D");
a1.append(ref.charAt(col));
a2.append("-");
col--;
break;
case NONE:
while (col >= 0 || row >= 0) {
if (row >= 0) {
cigar.append("S");
a1.append(col >= 0 ? ref.charAt(col) : ' ');
a2.append(Character.toLowerCase(query.charAt(row)));
}
else {
a1.append(col >= 0 ? ref.charAt(col) : ' ');
a2.append(' ');
}
col--;
row--;
}
break traceback; // exit the loop
}
}
String cigarStr = cigar.reverse().toString();
{
// Remove indels at both of the read ends
int left = 0, right = 0;
for (int i = 0; i < cigarStr.length(); ++i) {
char t = cigarStr.charAt(i);
if (t == 'S' || t == 'I' || t == 'D') {
left++;
}
else
break;
}
for (int i = cigarStr.length() - 1; i >= left; --i) {
char t = cigarStr.charAt(i);
if (t == 'S' || t == 'I' || t == 'D') {
right++;
}
else
break;
}
StringBuilder newCigar = new StringBuilder();
for (int i = 0; i < left; ++i)
newCigar.append('S');
newCigar.append(cigarStr.substring(left, cigarStr.length() - right));
for (int i = 0; i < right; ++i)
newCigar.append('S');
cigarStr = newCigar.toString();
}
// create cigar string
char prev = cigarStr.charAt(0);
int count = 1;
StringBuilder compactCigar = new StringBuilder();
for (int i = 1; i < cigarStr.length(); ++i) {
char c = cigarStr.charAt(i);
if (prev == c) {
count++;
}
else {
compactCigar.append(Integer.toString(count));
compactCigar.append(prev);
prev = c;
count = 1;
}
}
if (count > 0) {
compactCigar.append(Integer.toString(count));
compactCigar.append(prev);
}
return new Alignment(compactCigar.toString(), m - diff, a1.reverse().toString(), leftMostPos, a2.reverse()
.toString());
}
| public Alignment traceback(ACGTSequence ref, ACGTSequence query, SWResult bestHit) {
if (bestHit == null)
return null;
final int N = (int) ref.textSize();
int maxRow = m - 1;
int maxCol = bestHit.tailPos;
StringBuilder cigar = new StringBuilder();
StringBuilder a1 = new StringBuilder();
StringBuilder a2 = new StringBuilder();
int leftMostPos = 0; // in reference seq
// Append soft-clipped part in the query sequence
for (int i = m - 1; i > maxRow; --i) {
cigar.append("S");
}
int row = m - 1;
int col = N - 1;
// Append clipped sequences
while (col > maxCol) {
a1.append(ref.charAt(col - 1));
col--;
}
while (row > maxRow) {
a2.append(query.getACGT(row - 1).toChar());
row--;
}
// Trace back
int diff = 0;
traceback: for (col = maxCol, row = maxRow;;) {
Trace path = Trace.NONE;
// Calculate path
if (col >= 0 && row >= 0) {
int block = row / w;
int offset = row % w;
long vpf = vp[block][col] & (1L << offset);
long vnf = vn[block][col] & (1L << offset);
if (ref.getACGT(col) == query.getACGT(row)) {
path = Trace.DIAGONAL;
}
else if (vpf != 0L) {
path = Trace.UP;
diff++;
}
else if (vnf == 0L) {
// TODO no path to this. Fix me
path = Trace.DIAGONAL;
diff++;
}
else {
path = Trace.LEFT;
diff++;
}
}
switch (path) {
case DIAGONAL:
// match
cigar.append("M");
a1.append(ref.charAt(col));
a2.append(query.charAt(row));
leftMostPos = col;
col--;
row--;
break;
case UP:
// insertion
cigar.append("I");
a1.append("-");
a2.append(query.charAt(row));
leftMostPos = col + 1;
row--;
break;
case LEFT:
cigar.append("D");
a1.append(ref.charAt(col));
a2.append("-");
col--;
break;
case NONE:
while (col >= 0 || row >= 0) {
if (row >= 0) {
cigar.append("S");
a1.append(col >= 0 ? ref.charAt(col) : ' ');
a2.append(Character.toLowerCase(query.charAt(row)));
}
else {
a1.append(col >= 0 ? ref.charAt(col) : ' ');
a2.append(' ');
}
col--;
row--;
}
break traceback; // exit the loop
}
}
String cigarStr = cigar.reverse().toString();
{
// Remove indels at both of the read ends
int left = 0, right = 0;
for (int i = 0; i < cigarStr.length(); ++i) {
char t = cigarStr.charAt(i);
if (t == 'S' || t == 'I' || t == 'D') {
left++;
}
else
break;
}
for (int i = cigarStr.length() - 1; i >= left; --i) {
char t = cigarStr.charAt(i);
if (t == 'S' || t == 'I' || t == 'D') {
right++;
}
else
break;
}
StringBuilder newCigar = new StringBuilder();
for (int i = 0; i < left; ++i)
newCigar.append('S');
newCigar.append(cigarStr.substring(left, cigarStr.length() - right));
for (int i = 0; i < right; ++i)
newCigar.append('S');
cigarStr = newCigar.toString();
}
// create cigar string
char prev = cigarStr.charAt(0);
int count = 1;
StringBuilder compactCigar = new StringBuilder();
for (int i = 1; i < cigarStr.length(); ++i) {
char c = cigarStr.charAt(i);
if (prev == c) {
count++;
}
else {
compactCigar.append(Integer.toString(count));
compactCigar.append(prev);
prev = c;
count = 1;
}
}
if (count > 0) {
compactCigar.append(Integer.toString(count));
compactCigar.append(prev);
}
return new Alignment(compactCigar.toString(), m - diff, a1.reverse().toString(), leftMostPos, a2.reverse()
.toString());
}
|
diff --git a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBBrowserWidget.java b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBBrowserWidget.java
index bc804342e..988cbaca7 100644
--- a/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBBrowserWidget.java
+++ b/flexodesktop/GUI/flexointerfacebuilder/src/main/java/org/openflexo/fib/view/widget/FIBBrowserWidget.java
@@ -1,504 +1,512 @@
/*
* (c) Copyright 2010-2011 AgileBirds
*
* This file is part of OpenFlexo.
*
* OpenFlexo 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.
*
* OpenFlexo 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 OpenFlexo. If not, see <http://www.gnu.org/licenses/>.
*
*/
package org.openflexo.fib.view.widget;
import java.awt.BorderLayout;
import java.awt.event.MouseListener;
import java.util.Collection;
import java.util.List;
import java.util.Vector;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JPanel;
import javax.swing.JScrollPane;
import javax.swing.JTree;
import javax.swing.SwingUtilities;
import javax.swing.ToolTipManager;
import javax.swing.event.TreeModelEvent;
import javax.swing.event.TreeModelListener;
import javax.swing.event.TreeSelectionEvent;
import javax.swing.event.TreeSelectionListener;
import javax.swing.tree.TreePath;
import javax.swing.tree.TreeSelectionModel;
import org.openflexo.antar.binding.AbstractBinding;
import org.openflexo.fib.controller.FIBBrowserDynamicModel;
import org.openflexo.fib.controller.FIBController;
import org.openflexo.fib.controller.FIBSelectable;
import org.openflexo.fib.model.FIBBrowser;
import org.openflexo.fib.view.FIBWidgetView;
import org.openflexo.fib.view.widget.browser.FIBBrowserCellEditor;
import org.openflexo.fib.view.widget.browser.FIBBrowserCellRenderer;
import org.openflexo.fib.view.widget.browser.FIBBrowserModel;
import org.openflexo.fib.view.widget.browser.FIBBrowserModel.BrowserCell;
import org.openflexo.fib.view.widget.browser.FIBBrowserWidgetFooter;
/**
* Widget allowing to display a browser (a tree of various objects)
*
* @author sguerin
*/
public class FIBBrowserWidget extends FIBWidgetView<FIBBrowser, JTree, Object> implements FIBSelectable, TreeModelListener,
TreeSelectionListener {
private static final Logger logger = Logger.getLogger(FIBBrowserWidget.class.getPackage().getName());
// private static final int DEFAULT_WIDTH = 200;
private JTree _tree;
private final JPanel _dynamicComponent;
private final FIBBrowser _fibBrowser;
private FIBBrowserModel _browserModel;
private FIBBrowserWidgetFooter _footer;
// private ListSelectionModel _listSelectionModel;
private JScrollPane scrollPane;
private Object selectedObject;
private final Vector<Object> selection;
public FIBBrowserWidget(FIBBrowser fibBrowser, FIBController controller) {
super(fibBrowser, controller);
_fibBrowser = fibBrowser;
_dynamicComponent = new JPanel();
_dynamicComponent.setOpaque(false);
_dynamicComponent.setLayout(new BorderLayout());
selection = new Vector<Object>();
_footer = new FIBBrowserWidgetFooter(this);
buildBrowser();
}
@Override
public synchronized void delete() {
_footer.delete();
super.delete();
}
public FIBBrowser getBrowser() {
return _fibBrowser;
}
public FIBBrowserModel getBrowserModel() {
if (_browserModel == null) {
_browserModel = new FIBBrowserModel(_fibBrowser, this, getController());
}
return _browserModel;
}
public JTree getJTree() {
return _tree;
}
public FIBBrowserWidgetFooter getFooter() {
return _footer;
}
public Object getRootValue() {
return getWidget().getRoot().getBindingValue(getController());
}
// private static final Vector EMPTY_VECTOR = new Vector();
@Override
public synchronized boolean updateWidgetFromModel() {
// List valuesBeforeUpdating = getBrowserModel().getValues();
Object wasSelected = getSelectedObject();
// boolean debug = false;
// if (getWidget().getName() != null && getWidget().getName().equals("PatternRoleTable")) debug=true;
// if (debug) System.out.println("valuesBeforeUpdating: "+valuesBeforeUpdating);
// if (debug) System.out.println("wasSelected: "+wasSelected);
if (_tree.isEditing()) {
if (logger.isLoggable(Level.FINE)) {
logger.fine(getComponent().getName() + " - Tree is currently editing");
}
_tree.getCellEditor().cancelCellEditing();
} else {
if (logger.isLoggable(Level.FINE)) {
logger.fine(getComponent().getName() + " - Tree is NOT currently edited ");
}
}
if (logger.isLoggable(Level.FINE)) {
logger.fine(getComponent().getName() + " updateWidgetFromModel() with " + getValue() + " dataObject=" + getDataObject());
}
boolean returned = getBrowserModel().updateRootObject(getRootValue());
if (!getBrowser().getRootVisible() && ((BrowserCell) getBrowserModel().getRoot()).getChildCount() == 1) {
// Only one cell and roots are hidden, expand this first cell
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
getJTree().expandPath(
new TreePath(new Object[] { (BrowserCell) getBrowserModel().getRoot(),
((BrowserCell) getBrowserModel().getRoot()).getChildAt(0) }));
}
});
}
// getBrowserModel().setModel(getDataObject());
// We restore value if and only if we represent same browser
/*if (getBrowserModel().getValues() == valuesBeforeUpdating && wasSelected != null) {
setSelectedObject(wasSelected);
}
else {*/
// logger.info("Bon, je remets a jour la selection du browser, value="+getComponent().getSelected().getBindingValue(getController())+" was: "+getSelectedObject());
// System.out.println("getComponent().getSelected()="+getComponent().getSelected());
// System.out.println("getComponent().getSelected().isValid()="+getComponent().getSelected().isValid());
// System.out.println("value="+getComponent().getSelected().getBindingValue(getController()));
if (getComponent().getSelected().isValid() && getComponent().getSelected().getBindingValue(getController()) != null) {
Object newSelectedObject = getComponent().getSelected().getBindingValue(getController());
if (returned = notEquals(newSelectedObject, getSelectedObject())) {
setSelectedObject(newSelectedObject);
}
}
// }
return returned;
}
public TreeSelectionModel getTreeSelectionModel() {
return _tree.getSelectionModel();
}
public void setSelectedObject(Object object) {
setSelectedObject(object, false);
}
public void setSelectedObject(Object object, boolean force) {
// logger.info("Select " + object);
if (getRootValue() == null) {
return;
}
if (object == getSelectedObject() && !force) {
logger.fine("Ignore set selected object");
return;
}
// logger.info("---------------------> FIBBrowserWidget, setSelectedObject from "+getSelectedObject()+" to "+object);
if (object != null) {
Collection<BrowserCell> cells = getBrowserModel().getBrowserCell(object);
// logger.info("Select " + cells);
getTreeSelectionModel().clearSelection();
if (cells != null) {
TreePath scrollTo = null;
for (BrowserCell cell : cells) {
TreePath treePath = cell.getTreePath();
if (scrollTo == null) {
scrollTo = treePath;
}
getTreeSelectionModel().addSelectionPath(treePath);
}
if (scrollTo != null) {
_tree.scrollPathToVisible(scrollTo);
}
}
} else {
clearSelection();
}
}
public void clearSelection() {
getTreeSelectionModel().clearSelection();
}
@Override
public List<AbstractBinding> getDependencyBindings() {
List<AbstractBinding> returned = super.getDependencyBindings();
appendToDependingObjects(getWidget().getSelected(), returned);
appendToDependingObjects(getWidget().getRoot(), returned);
return returned;
}
@Override
public synchronized boolean updateModelFromWidget() {
return false;
}
@Override
public JPanel getJComponent() {
return _dynamicComponent;
}
@Override
public JTree getDynamicJComponent() {
return _tree;
}
@Override
public FIBBrowserDynamicModel createDynamicModel() {
return new FIBBrowserDynamicModel(null);
}
@Override
public FIBBrowserDynamicModel getDynamicModel() {
return (FIBBrowserDynamicModel) super.getDynamicModel();
}
@Override
public void updateLanguage() {
super.updateLanguage();
updateBrowser();
System.out.println("Ne pas oublier de localiser les actions ici");
/*for (FIBTableAction a : getWidget().getActions()) {
if (getWidget().getLocalize()) getLocalized(a.getName());
}*/
}
public void updateBrowser() {
deleteBrowser();
if (_browserModel != null) {
_browserModel.removeTreeModelListener(this);
_browserModel.delete();
_browserModel = null;
}
buildBrowser();
updateDataObject(getDataObject());
}
private void deleteBrowser() {
if (_tree != null) {
_tree.removeFocusListener(this);
}
for (MouseListener l : _tree.getMouseListeners()) {
_tree.removeMouseListener(l);
}
}
private void buildBrowser() {
getBrowserModel().addTreeModelListener(this);
_tree = new JTree(getBrowserModel());
_tree.putClientProperty("terminateEditOnFocusLost", Boolean.TRUE);
_tree.addFocusListener(this);
FIBBrowserCellRenderer renderer = new FIBBrowserCellRenderer(this);
_tree.setCellRenderer(renderer);
_tree.setCellEditor(new FIBBrowserCellEditor(_tree, renderer));
_tree.setEditable(true);
_tree.setScrollsOnExpand(true);
// _tree.setBorder(BorderFactory.createEmptyBorder(3, 3, 0, 0));
_tree.setRootVisible(getBrowser().getRootVisible());
_tree.setShowsRootHandles(getBrowser().getShowRootsHandle());
_tree.setAutoscrolls(true);
ToolTipManager.sharedInstance().registerComponent(_tree);
if (_fibBrowser.getRowHeight() != null) {
_tree.setRowHeight(_fibBrowser.getRowHeight());
}
getTreeSelectionModel().setSelectionMode(getBrowser().getSelectionMode().getMode());
getTreeSelectionModel().addTreeSelectionListener(this);
scrollPane = new JScrollPane(_tree);
/*_tree.addMouseListener(new MouseAdapter() {
@Override
public void mouseClicked(MouseEvent e)
{
getController().fireMouseClicked(getDynamicModel(),e.getClickCount());
}
});*/
_dynamicComponent.removeAll();
_dynamicComponent.add(scrollPane, BorderLayout.CENTER);
if (_fibBrowser.getShowFooter()) {
_dynamicComponent.add(getFooter(), BorderLayout.SOUTH);
}
if (_fibBrowser.getVisibleRowCount() != null) {
_tree.setVisibleRowCount(_fibBrowser.getVisibleRowCount());
}
_dynamicComponent.revalidate();
_dynamicComponent.repaint();
}
@Override
public boolean synchronizedWithSelection() {
return getWidget().getBoundToSelectionManager();
}
public boolean isLastFocusedSelectable() {
return getController().getLastFocusedSelectable() == this;
}
@Override
public boolean mayRepresent(Object o) {
return _browserModel.containsObject(o);
}
@Override
public void objectAddedToSelection(Object o) {
addToSelectionNoNotification(o);
}
@Override
public void objectRemovedFromSelection(Object o) {
removeFromSelectionNoNotification(o);
}
@Override
public void selectionResetted() {
resetSelectionNoNotification();
}
@Override
public void treeNodesChanged(TreeModelEvent e) {
// logger.fine("treeNodesChanged "+e);
}
@Override
public void treeNodesInserted(TreeModelEvent e) {
// logger.fine("treeNodesInserted "+e);
}
@Override
public void treeNodesRemoved(TreeModelEvent e) {
// logger.fine("treeNodesRemoved "+e);
// Here maybe check if objects represented by the removed nodes should be removed from current selection/selectedObject
}
@Override
public void treeStructureChanged(TreeModelEvent e) {
// logger.fine("treeStructureChanged "+e);
}
@Override
public void updateDataObject(final Object dataObject) {
if (!SwingUtilities.isEventDispatchThread()) {
if (logger.isLoggable(Level.WARNING)) {
logger.warning("Update data object invoked outside the EDT!!! please investigate and make sure this is no longer the case. \n\tThis is a very SERIOUS problem! Do not let this pass.");
}
SwingUtilities.invokeLater(new Runnable() {
@Override
public void run() {
updateDataObject(dataObject);
}
});
return;
}
super.updateDataObject(dataObject);
getBrowserModel().fireTreeRestructured();
}
@Override
public Object getSelectedObject() {
return selectedObject;
}
@Override
public Vector<Object> getSelection() {
return selection;
}
private boolean ignoreNotifications = false;
public synchronized void addToSelectionNoNotification(Object o) {
ignoreNotifications = true;
addToSelection(o);
ignoreNotifications = false;
}
public synchronized void removeFromSelectionNoNotification(Object o) {
ignoreNotifications = true;
removeFromSelection(o);
ignoreNotifications = false;
}
public synchronized void resetSelectionNoNotification() {
ignoreNotifications = true;
resetSelection();
ignoreNotifications = false;
}
@Override
public void addToSelection(Object o) {
for (TreePath path : getBrowserModel().getPaths(o)) {
getTreeSelectionModel().addSelectionPath(path);
getJTree().scrollPathToVisible(path);
}
}
@Override
public void removeFromSelection(Object o) {
for (TreePath path : getBrowserModel().getPaths(o)) {
getTreeSelectionModel().removeSelectionPath(path);
}
}
@Override
public void resetSelection() {
getTreeSelectionModel().clearSelection();
}
@Override
public synchronized void valueChanged(TreeSelectionEvent e) {
Vector<Object> oldSelection = new Vector<Object>();
oldSelection.addAll(selection);
/*System.out.println("Selection: "+e);
System.out.println("Paths="+e.getPaths());
for (TreePath tp : e.getPaths()) {
System.out.println("> "+tp.getLastPathComponent()+" added="+e.isAddedPath(tp));
}
System.out.println("New LEAD="+(e.getNewLeadSelectionPath()!=null?e.getNewLeadSelectionPath().getLastPathComponent():"null"));
System.out.println("Old LEAD="+(e.getOldLeadSelectionPath()!=null?e.getOldLeadSelectionPath().getLastPathComponent():"null"));
*/
if (e.getNewLeadSelectionPath() == null || (BrowserCell) e.getNewLeadSelectionPath().getLastPathComponent() == null) {
selectedObject = null;
} else {
selectedObject = ((BrowserCell) e.getNewLeadSelectionPath().getLastPathComponent()).getRepresentedObject();
}
for (TreePath tp : e.getPaths()) {
- if (e.isAddedPath(tp)) {
- selection.add(((BrowserCell) tp.getLastPathComponent()).getRepresentedObject());
- } else {
- selection.remove(((BrowserCell) tp.getLastPathComponent()).getRepresentedObject());
+ Object obj = ((BrowserCell) tp.getLastPathComponent()).getRepresentedObject();
+ if (obj != null
+ && (getBrowser().getIteratorClass() == null || getBrowser().getIteratorClass().isAssignableFrom(obj.getClass()))) {
+ if (e.isAddedPath(tp)) {
+ selection.add(obj);
+ } else {
+ selection.remove(obj);
+ }
}
}
// logger.info("BrowserModel, selected object is now "+selectedObject);
- getDynamicModel().selected = selectedObject;
+ if (selectedObject == null) {
+ getDynamicModel().selected = null;
+ } else if (getBrowser().getIteratorClass() == null || getBrowser().getIteratorClass().isAssignableFrom(selectedObject.getClass())) {
+ getDynamicModel().selected = selectedObject;
+ }
getDynamicModel().selection = selection;
notifyDynamicModelChanged();
if (getComponent().getSelected().isValid()) {
logger.fine("Sets SELECTED binding with " + selectedObject);
getComponent().getSelected().setBindingValue(selectedObject, getController());
}
updateFont();
if (!ignoreNotifications) {
getController().updateSelection(this, oldSelection, selection);
}
_footer.setFocusedObject(selectedObject);
}
}
| false | true | public synchronized void valueChanged(TreeSelectionEvent e) {
Vector<Object> oldSelection = new Vector<Object>();
oldSelection.addAll(selection);
/*System.out.println("Selection: "+e);
System.out.println("Paths="+e.getPaths());
for (TreePath tp : e.getPaths()) {
System.out.println("> "+tp.getLastPathComponent()+" added="+e.isAddedPath(tp));
}
System.out.println("New LEAD="+(e.getNewLeadSelectionPath()!=null?e.getNewLeadSelectionPath().getLastPathComponent():"null"));
System.out.println("Old LEAD="+(e.getOldLeadSelectionPath()!=null?e.getOldLeadSelectionPath().getLastPathComponent():"null"));
*/
if (e.getNewLeadSelectionPath() == null || (BrowserCell) e.getNewLeadSelectionPath().getLastPathComponent() == null) {
selectedObject = null;
} else {
selectedObject = ((BrowserCell) e.getNewLeadSelectionPath().getLastPathComponent()).getRepresentedObject();
}
for (TreePath tp : e.getPaths()) {
if (e.isAddedPath(tp)) {
selection.add(((BrowserCell) tp.getLastPathComponent()).getRepresentedObject());
} else {
selection.remove(((BrowserCell) tp.getLastPathComponent()).getRepresentedObject());
}
}
// logger.info("BrowserModel, selected object is now "+selectedObject);
getDynamicModel().selected = selectedObject;
getDynamicModel().selection = selection;
notifyDynamicModelChanged();
if (getComponent().getSelected().isValid()) {
logger.fine("Sets SELECTED binding with " + selectedObject);
getComponent().getSelected().setBindingValue(selectedObject, getController());
}
updateFont();
if (!ignoreNotifications) {
getController().updateSelection(this, oldSelection, selection);
}
_footer.setFocusedObject(selectedObject);
}
| public synchronized void valueChanged(TreeSelectionEvent e) {
Vector<Object> oldSelection = new Vector<Object>();
oldSelection.addAll(selection);
/*System.out.println("Selection: "+e);
System.out.println("Paths="+e.getPaths());
for (TreePath tp : e.getPaths()) {
System.out.println("> "+tp.getLastPathComponent()+" added="+e.isAddedPath(tp));
}
System.out.println("New LEAD="+(e.getNewLeadSelectionPath()!=null?e.getNewLeadSelectionPath().getLastPathComponent():"null"));
System.out.println("Old LEAD="+(e.getOldLeadSelectionPath()!=null?e.getOldLeadSelectionPath().getLastPathComponent():"null"));
*/
if (e.getNewLeadSelectionPath() == null || (BrowserCell) e.getNewLeadSelectionPath().getLastPathComponent() == null) {
selectedObject = null;
} else {
selectedObject = ((BrowserCell) e.getNewLeadSelectionPath().getLastPathComponent()).getRepresentedObject();
}
for (TreePath tp : e.getPaths()) {
Object obj = ((BrowserCell) tp.getLastPathComponent()).getRepresentedObject();
if (obj != null
&& (getBrowser().getIteratorClass() == null || getBrowser().getIteratorClass().isAssignableFrom(obj.getClass()))) {
if (e.isAddedPath(tp)) {
selection.add(obj);
} else {
selection.remove(obj);
}
}
}
// logger.info("BrowserModel, selected object is now "+selectedObject);
if (selectedObject == null) {
getDynamicModel().selected = null;
} else if (getBrowser().getIteratorClass() == null || getBrowser().getIteratorClass().isAssignableFrom(selectedObject.getClass())) {
getDynamicModel().selected = selectedObject;
}
getDynamicModel().selection = selection;
notifyDynamicModelChanged();
if (getComponent().getSelected().isValid()) {
logger.fine("Sets SELECTED binding with " + selectedObject);
getComponent().getSelected().setBindingValue(selectedObject, getController());
}
updateFont();
if (!ignoreNotifications) {
getController().updateSelection(this, oldSelection, selection);
}
_footer.setFocusedObject(selectedObject);
}
|
diff --git a/fizzbuzz/src/test/java/org/bonitasoft/dojo/fizzbuzz/FizzBuzzGameTest2.java b/fizzbuzz/src/test/java/org/bonitasoft/dojo/fizzbuzz/FizzBuzzGameTest2.java
index 77f1d0d..3075d0a 100644
--- a/fizzbuzz/src/test/java/org/bonitasoft/dojo/fizzbuzz/FizzBuzzGameTest2.java
+++ b/fizzbuzz/src/test/java/org/bonitasoft/dojo/fizzbuzz/FizzBuzzGameTest2.java
@@ -1,44 +1,44 @@
/**
* Copyright (C) 2012 BonitaSoft S.A.
*
* BonitaSoft, 32 rue Gustave Eiffel - 38000 Grenoble
* 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.0 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.bonitasoft.dojo.fizzbuzz;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.is;
import org.junit.Before;
import org.junit.Test;
public class FizzBuzzGameTest2 {
private FizzBuzzGame fizzBuzzGame;
@Before
public void intializeFizzBuzzGame() {
fizzBuzzGame = new FizzBuzzGame(new FizzBuzzer());
}
@Test
public void testPlayUntil() throws Exception {
- String expectedGameResult = "1 2 Fizz 4 5 6 Buzz 8 Fizz 10 11 Fizz 13 Buzz Fizz 16 Buzz Fizz 19 20 FizzBuzz 22 " +
- "Fizz Fizz 25 26 Buzz Fizz 29 Fizz Fizz Fizz Fizz Fizz Fizz Fizz FizzBuzz Fizz Fizz 40 41";
+ String expectedGameResult = "1 2 Fizz 4 5 Fizz Buzz 8 Fizz 10 11 Fizz Fizz Buzz Fizz 16 Buzz Fizz 19 20 FizzBuzz 22 " +
+ "Fizz Fizz 25 26 FizzBuzz Buzz 29 Fizz Fizz Fizz Fizz Fizz FizzBuzz Fizz FizzBuzz Fizz Fizz 40 41";
String gameResult = fizzBuzzGame.playUntil(41);
assertThat(gameResult, is(expectedGameResult));
}
}
| true | true | public void testPlayUntil() throws Exception {
String expectedGameResult = "1 2 Fizz 4 5 6 Buzz 8 Fizz 10 11 Fizz 13 Buzz Fizz 16 Buzz Fizz 19 20 FizzBuzz 22 " +
"Fizz Fizz 25 26 Buzz Fizz 29 Fizz Fizz Fizz Fizz Fizz Fizz Fizz FizzBuzz Fizz Fizz 40 41";
String gameResult = fizzBuzzGame.playUntil(41);
assertThat(gameResult, is(expectedGameResult));
}
| public void testPlayUntil() throws Exception {
String expectedGameResult = "1 2 Fizz 4 5 Fizz Buzz 8 Fizz 10 11 Fizz Fizz Buzz Fizz 16 Buzz Fizz 19 20 FizzBuzz 22 " +
"Fizz Fizz 25 26 FizzBuzz Buzz 29 Fizz Fizz Fizz Fizz Fizz FizzBuzz Fizz FizzBuzz Fizz Fizz 40 41";
String gameResult = fizzBuzzGame.playUntil(41);
assertThat(gameResult, is(expectedGameResult));
}
|
diff --git a/plugins/org.bigraph.model/src/org/bigraph/model/Layoutable.java b/plugins/org.bigraph.model/src/org/bigraph/model/Layoutable.java
index 2bcdd21a..ac166eff 100644
--- a/plugins/org.bigraph.model/src/org/bigraph/model/Layoutable.java
+++ b/plugins/org.bigraph.model/src/org/bigraph/model/Layoutable.java
@@ -1,167 +1,167 @@
package org.bigraph.model;
import org.bigraph.model.ModelObject;
import org.bigraph.model.assistants.ExecutorManager;
import org.bigraph.model.assistants.PropertyScratchpad;
import org.bigraph.model.assistants.RedProperty;
import org.bigraph.model.changes.Change;
import org.bigraph.model.changes.IChange;
import org.bigraph.model.names.Namespace;
/**
* All of the objects which can actually appear as part of a bigraph are
* instances of <strong>Layoutable</strong>.
* @author alec
* @see ModelObject
*/
public abstract class Layoutable extends NamedModelObject {
/**
* The property name fired when the parent changes.
*/
@RedProperty(fired = Container.class, retrieved = Container.class)
public static final String PROPERTY_PARENT = "LayoutableParent";
abstract class LayoutableChange extends ModelObjectChange {
@Override
public Layoutable getCreator() {
return Layoutable.this;
}
}
abstract static class LayoutableChangeDescriptor
extends NamedModelObjectChangeDescriptor {
}
@Override
protected Namespace<Layoutable> getGoverningNamespace(
PropertyScratchpad context) {
return getBigraph(context).getNamespace(this);
}
public final class ChangeRemove extends LayoutableChange {
private String oldName;
private Container oldParent;
@Override
public void beforeApply() {
Layoutable l = getCreator();
oldName = l.getName();
oldParent = l.getParent();
}
@Override
public boolean canInvert() {
return (oldName != null && oldParent != null);
}
@Override
public Change inverse() {
return oldParent.new ChangeAddChild(getCreator(), oldName);
}
@Override
public String toString() {
return "Change(remove child " + getCreator() + ")";
}
@Override
public void simulate(PropertyScratchpad context) {
Layoutable l = getCreator();
Container c = l.getParent(context);
- context.<Layoutable>getModifiableList(
+ context.<Layoutable>getModifiableSet(
c, Container.PROPERTY_CHILD, c.getChildren()).
remove(l);
context.setProperty(l, Layoutable.PROPERTY_PARENT, null);
c.getBigraph(context).getNamespace(l).
remove(context, l.getName(context));
context.setProperty(l, Layoutable.PROPERTY_NAME, null);
}
}
static {
ExecutorManager.getInstance().addHandler(new LayoutableHandler());
}
private Container parent = null;
/**
* Returns the {@link Bigraph} that ultimately contains this object.
* @return a Bigraph
*/
public Bigraph getBigraph() {
return getBigraph(null);
}
public Bigraph getBigraph(PropertyScratchpad context) {
if (getParent(context) == null) {
return null;
} else return getParent(context).getBigraph(context);
}
/**
* Returns the parent of this object.
* @return an {@link Container}
*/
public Container getParent() {
return parent;
}
public Container getParent(PropertyScratchpad context) {
return getProperty(context, PROPERTY_PARENT, Container.class);
}
/**
* Changes the parent of this object.
* @param p the new parent {@link Container}
*/
void setParent(Container parent) {
Container oldParent = this.parent;
this.parent = parent;
firePropertyChange(PROPERTY_PARENT, oldParent, parent);
}
protected Layoutable clone(Bigraph m) {
Layoutable l = (Layoutable)super.clone();
m.getNamespace(l).put(getName(), l);
return l;
}
public IChange changeRemove() {
return new ChangeRemove();
}
@Override
protected Object getProperty(String name) {
if (PROPERTY_PARENT.equals(name)) {
return getParent();
} else return super.getProperty(name);
}
@Override
public void dispose() {
parent = null;
super.dispose();
}
@Override
public abstract Identifier getIdentifier();
@Override
public abstract Identifier getIdentifier(PropertyScratchpad context);
public static abstract class Identifier
extends NamedModelObject.Identifier {
public Identifier(String name) {
super(name);
}
@Override
public abstract Layoutable lookup(
PropertyScratchpad context, Resolver r);
@Override
public abstract Identifier getRenamed(String name);
}
}
| true | true | public void simulate(PropertyScratchpad context) {
Layoutable l = getCreator();
Container c = l.getParent(context);
context.<Layoutable>getModifiableList(
c, Container.PROPERTY_CHILD, c.getChildren()).
remove(l);
context.setProperty(l, Layoutable.PROPERTY_PARENT, null);
c.getBigraph(context).getNamespace(l).
remove(context, l.getName(context));
context.setProperty(l, Layoutable.PROPERTY_NAME, null);
}
| public void simulate(PropertyScratchpad context) {
Layoutable l = getCreator();
Container c = l.getParent(context);
context.<Layoutable>getModifiableSet(
c, Container.PROPERTY_CHILD, c.getChildren()).
remove(l);
context.setProperty(l, Layoutable.PROPERTY_PARENT, null);
c.getBigraph(context).getNamespace(l).
remove(context, l.getName(context));
context.setProperty(l, Layoutable.PROPERTY_NAME, null);
}
|
diff --git a/com.toedter.e4.ui.workbench.renderers.javafx/src/com/toedter/e4/ui/workbench/renderers/javafx/ToolBarRenderer.java b/com.toedter.e4.ui.workbench.renderers.javafx/src/com/toedter/e4/ui/workbench/renderers/javafx/ToolBarRenderer.java
index 13515bf..f826ef3 100644
--- a/com.toedter.e4.ui.workbench.renderers.javafx/src/com/toedter/e4/ui/workbench/renderers/javafx/ToolBarRenderer.java
+++ b/com.toedter.e4.ui.workbench.renderers.javafx/src/com/toedter/e4/ui/workbench/renderers/javafx/ToolBarRenderer.java
@@ -1,82 +1,83 @@
/*******************************************************************************
* Copyright (c) 2011 Kai Toedter 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:
* Kai Toedter - initial API and implementation
******************************************************************************/
package com.toedter.e4.ui.workbench.renderers.javafx;
import javafx.geometry.Orientation;
import javafx.scene.control.Button;
import javafx.scene.control.Separator;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Pane;
import javafx.scene.layout.VBox;
import org.eclipse.e4.ui.model.application.ui.MElementContainer;
import org.eclipse.e4.ui.model.application.ui.MUIElement;
import org.eclipse.e4.ui.model.application.ui.SideValue;
import org.eclipse.e4.ui.model.application.ui.basic.MTrimBar;
import org.eclipse.e4.ui.model.application.ui.menu.MDirectToolItem;
import org.eclipse.e4.ui.model.application.ui.menu.MHandledToolItem;
import org.eclipse.e4.ui.model.application.ui.menu.MToolBar;
import org.eclipse.e4.ui.model.application.ui.menu.MToolBarSeparator;
import com.toedter.e4.ui.workbench.generic.GenericRenderer;
@SuppressWarnings("restriction")
public class ToolBarRenderer extends GenericRenderer {
@Override
public void createWidget(MUIElement element, MElementContainer<MUIElement> parent) {
if (!(element instanceof MToolBar)) {
return;
}
Orientation orientation = getOrientation(element);
if (orientation == Orientation.VERTICAL) {
VBox toolBar = new VBox();
element.setWidget(toolBar);
+ return;
}
// Since we use a JavaFX ToolBar for the TrimBar, each e4 tool bar is
// rendered as JavaFX HBox
HBox toolBar = new HBox();
element.setWidget(toolBar);
}
@Override
public void processContents(final MElementContainer<MUIElement> container) {
Pane toolBar = (Pane) container.getWidget();
for (MUIElement element : container.getChildren()) {
if (element instanceof MHandledToolItem || element instanceof MDirectToolItem) {
toolBar.getChildren().add((Button) element.getWidget());
} else if (element instanceof MToolBarSeparator) {
Separator separator = (Separator) element.getWidget();
if (separator != null) {
separator.setOrientation(getOrientation(container) == Orientation.VERTICAL ? Orientation.HORIZONTAL
: Orientation.VERTICAL);
toolBar.getChildren().add(separator);
}
}
}
}
private Orientation getOrientation(final MUIElement element) {
MUIElement theParent = element.getParent();
if (theParent instanceof MTrimBar) {
MTrimBar trimContainer = (MTrimBar) theParent;
SideValue side = trimContainer.getSide();
if (side.getValue() == SideValue.LEFT_VALUE || side.getValue() == SideValue.RIGHT_VALUE) {
return Orientation.VERTICAL;
}
}
return Orientation.HORIZONTAL;
}
}
| true | true | public void createWidget(MUIElement element, MElementContainer<MUIElement> parent) {
if (!(element instanceof MToolBar)) {
return;
}
Orientation orientation = getOrientation(element);
if (orientation == Orientation.VERTICAL) {
VBox toolBar = new VBox();
element.setWidget(toolBar);
}
// Since we use a JavaFX ToolBar for the TrimBar, each e4 tool bar is
// rendered as JavaFX HBox
HBox toolBar = new HBox();
element.setWidget(toolBar);
}
| public void createWidget(MUIElement element, MElementContainer<MUIElement> parent) {
if (!(element instanceof MToolBar)) {
return;
}
Orientation orientation = getOrientation(element);
if (orientation == Orientation.VERTICAL) {
VBox toolBar = new VBox();
element.setWidget(toolBar);
return;
}
// Since we use a JavaFX ToolBar for the TrimBar, each e4 tool bar is
// rendered as JavaFX HBox
HBox toolBar = new HBox();
element.setWidget(toolBar);
}
|
diff --git a/src/simpleserver/stream/StreamTunnel.java b/src/simpleserver/stream/StreamTunnel.java
index 828a76c..383bd9b 100644
--- a/src/simpleserver/stream/StreamTunnel.java
+++ b/src/simpleserver/stream/StreamTunnel.java
@@ -1,1422 +1,1422 @@
/*
* 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.stream;
import static simpleserver.lang.Translations.t;
import static simpleserver.util.Util.print;
import static simpleserver.util.Util.println;
import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.DataInput;
import java.io.DataInputStream;
import java.io.DataOutput;
import java.io.DataOutputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import simpleserver.Authenticator.AuthRequest;
import simpleserver.Color;
import simpleserver.Coordinate;
import simpleserver.Coordinate.Dimension;
import simpleserver.Main;
import simpleserver.Player;
import simpleserver.Server;
import simpleserver.command.PlayerListCommand;
import simpleserver.config.data.Chests.Chest;
import simpleserver.config.xml.Config.BlockPermission;
public class StreamTunnel {
private static final boolean EXPENSIVE_DEBUG_LOGGING = Boolean.getBoolean("EXPENSIVE_DEBUG_LOGGING");
private static final int IDLE_TIME = 30000;
private static final int BUFFER_SIZE = 1024;
private static final byte BLOCK_DESTROYED_STATUS = 2;
private static final Pattern MESSAGE_PATTERN = Pattern.compile("^<([^>]+)> (.*)$");
private static final Pattern COLOR_PATTERN = Pattern.compile("\u00a7[0-9a-z]");
private static final Pattern JOIN_PATTERN = Pattern.compile("\u00a7.((\\d|\\w)*) (joined|left) the game.");
private static final String CONSOLE_CHAT_PATTERN = "\\[Server:.*\\]";
private static final int MESSAGE_SIZE = 60;
private static final int MAXIMUM_MESSAGE_SIZE = 119;
private final boolean isServerTunnel;
private final String streamType;
private final Player player;
private final Server server;
private final byte[] buffer;
private final Tunneler tunneler;
private DataInput in;
private DataOutput out;
private InputStream inputStream;
private OutputStream outputStream;
private StreamDumper inputDumper;
private StreamDumper outputDumper;
private boolean inGame = false;
private volatile long lastRead;
private volatile boolean run = true;
private Byte lastPacket;
private char commandPrefix;
public StreamTunnel(InputStream in, OutputStream out, boolean isServerTunnel,
Player player) {
this.isServerTunnel = isServerTunnel;
if (isServerTunnel) {
streamType = "ServerStream";
} else {
streamType = "PlayerStream";
}
this.player = player;
server = player.getServer();
commandPrefix = server.options.getBoolean("useSlashes") ? '/' : '!';
inputStream = in;
outputStream = out;
DataInputStream dIn = new DataInputStream(in);
DataOutputStream dOut = new DataOutputStream(out);
if (EXPENSIVE_DEBUG_LOGGING) {
try {
OutputStream dump = new FileOutputStream(streamType + "Input.debug");
InputStreamDumper dumper = new InputStreamDumper(dIn, dump);
inputDumper = dumper;
this.in = dumper;
} catch (FileNotFoundException e) {
System.out.println("Unable to open input debug dump!");
throw new RuntimeException(e);
}
try {
OutputStream dump = new FileOutputStream(streamType + "Output.debug");
OutputStreamDumper dumper = new OutputStreamDumper(dOut, dump);
outputDumper = dumper;
this.out = dumper;
} catch (FileNotFoundException e) {
System.out.println("Unable to open output debug dump!");
throw new RuntimeException(e);
}
} else {
this.in = dIn;
this.out = dOut;
}
buffer = new byte[BUFFER_SIZE];
tunneler = new Tunneler();
tunneler.start();
lastRead = System.currentTimeMillis();
}
public void stop() {
run = false;
}
public boolean isAlive() {
return tunneler.isAlive();
}
public boolean isActive() {
return System.currentTimeMillis() - lastRead < IDLE_TIME
|| player.isRobot();
}
private void handlePacket() throws IOException {
Byte packetId = in.readByte();
// System.out.println((isServerTunnel ? "server " : "client ") +
// String.format("%02x", packetId));
int x;
byte y;
int z;
byte dimension;
Coordinate coordinate;
switch (packetId) {
case 0x00: // Keep Alive
write(packetId);
write(in.readInt()); // random number that is returned from server
break;
case 0x01: // Login Request/Response
write(packetId);
if (!isServerTunnel) {
write(in.readInt());
write(readUTF16());
copyNBytes(5);
break;
}
player.setEntityId(write(in.readInt()));
write(readUTF16());
write(in.readByte());
dimension = in.readByte();
if (isServerTunnel) {
player.setDimension(Dimension.get(dimension));
}
write(dimension);
write(in.readByte());
write(in.readByte());
if (isServerTunnel) {
in.readByte();
write((byte) server.config.properties.getInt("maxPlayers"));
} else {
write(in.readByte());
}
break;
case 0x02: // Handshake
byte version = in.readByte();
String name = readUTF16();
boolean nameSet = false;
if (name.contains(";")) {
name = name.substring(0, name.indexOf(";"));
}
if (name.equals("Player") || !server.authenticator.isMinecraftUp) {
AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress());
if (req != null) {
name = req.playerName;
nameSet = server.authenticator.completeLogin(req, player);
}
if (req == null || !nameSet) {
if (!name.equals("Player")) {
player.addTMessage(Color.RED, "Login verification failed.");
player.addTMessage(Color.RED, "You were logged in as guest.");
}
name = server.authenticator.getFreeGuestName();
player.setGuest(true);
nameSet = player.setName(name);
}
} else {
nameSet = player.setName(name);
if (nameSet) {
player.updateRealName(name);
}
}
if (player.isGuest() && !server.authenticator.allowGuestJoin()) {
player.kick(t("Failed to login: User not authenticated"));
nameSet = false;
}
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
write(version);
write(player.getName());
write(readUTF16());
write(in.readInt());
break;
case 0x03: // Chat Message
String message = readUTF16();
Matcher joinMatcher = JOIN_PATTERN.matcher(message);
if (isServerTunnel && joinMatcher.find()) {
if (server.bots.ninja(joinMatcher.group(1))) {
break;
}
if (message.contains("join")) {
player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1));
} else {
player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1));
}
break;
}
if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) {
if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) {
break;
}
Matcher colorMatcher = COLOR_PATTERN.matcher(message);
String cleanMessage = colorMatcher.replaceAll("");
Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage);
if (messageMatcher.find()) {
} else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) {
break;
}
if (server.config.properties.getBoolean("msgWrap")) {
sendMessage(message);
} else {
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
} else if (!isServerTunnel) {
if (player.isMuted() && !message.startsWith("/")
&& !message.startsWith("!")) {
player.addTMessage(Color.RED, "You are muted! You may not send messages to all players.");
break;
}
if (message.charAt(0) == commandPrefix) {
message = player.parseCommand(message, false);
if (message == null) {
break;
}
write(packetId);
write(message);
return;
}
player.sendMessage(message);
}
break;
case 0x04: // Time Update
write(packetId);
write(in.readLong());
long time = in.readLong();
server.setTime(time);
write(time);
break;
case 0x05: // Player Inventory
write(packetId);
write(in.readInt());
write(in.readShort());
copyItem();
break;
case 0x06: // Spawn Position
write(packetId);
copyNBytes(12);
if (server.options.getBoolean("enableEvents")) {
server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null);
}
break;
case 0x07: // Use Entity
int user = in.readInt();
int target = in.readInt();
Player targetPlayer = server.playerList.findPlayer(target);
if (targetPlayer != null) {
if (targetPlayer.godModeEnabled()) {
in.readBoolean();
break;
}
}
write(packetId);
write(user);
write(target);
copyNBytes(1);
break;
case 0x08: // Update Health
write(packetId);
player.updateHealth(write(in.readShort()));
player.getHealth();
write(in.readShort());
write(in.readFloat());
break;
case 0x09: // Respawn
write(packetId);
if (!isServerTunnel) {
break;
}
player.setDimension(Dimension.get(write(in.readInt())));
write(in.readByte());
write(in.readByte());
write(in.readShort());
write(readUTF16()); // Added in 1.1 (level type)
if (server.options.getBoolean("enableEvents") && isServerTunnel) {
server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null);
}
break;
case 0x0a: // Player
write(packetId);
copyNBytes(1);
if (!inGame && !isServerTunnel) {
player.sendMOTD();
if (server.config.properties.getBoolean("showListOnConnect")) {
// display player list if enabled in config
player.execute(PlayerListCommand.class);
}
inGame = true;
}
break;
case 0x0b: // Player Position
write(packetId);
copyPlayerLocation();
copyNBytes(1);
break;
case 0x0c: // Player Look
write(packetId);
copyPlayerLook();
copyNBytes(1);
break;
case 0x0d: // Player Position & Look
write(packetId);
copyPlayerLocation();
copyPlayerLook();
copyNBytes(1);
break;
case 0x0e: // Player Digging
if (!isServerTunnel) {
byte status = in.readByte();
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte face = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (!player.getGroup().ignoreAreas) {
BlockPermission perm = server.config.blockPermission(player, coordinate);
if (!perm.use && status == 0) {
player.addTMessage(Color.RED, "You can not use this block here!");
break;
}
if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) {
player.addTMessage(Color.RED, "You can not destroy this block!");
break;
}
}
boolean locked = server.data.chests.isLocked(coordinate);
if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) {
if (locked && status == BLOCK_DESTROYED_STATUS) {
server.data.chests.releaseLock(coordinate);
server.data.save();
}
write(packetId);
write(status);
write(x);
write(y);
write(z);
write(face);
if (player.instantDestroyEnabled()) {
packetFinished();
write(packetId);
write(BLOCK_DESTROYED_STATUS);
write(x);
write(y);
write(z);
write(face);
}
if (status == BLOCK_DESTROYED_STATUS) {
player.destroyedBlock();
}
}
} else {
write(packetId);
copyNBytes(11);
}
break;
case 0x0f: // Player Block Placement
x = in.readInt();
y = in.readByte();
z = in.readInt();
coordinate = new Coordinate(x, y, z, player);
final byte direction = in.readByte();
final short dropItem = in.readShort();
byte itemCount = 0;
short uses = 0;
byte[] data = null;
if (dropItem != -1) {
itemCount = in.readByte();
uses = in.readShort();
short dataLength = in.readShort();
if (dataLength != -1) {
data = new byte[dataLength];
in.readFully(data);
}
}
byte blockX = in.readByte();
byte blockY = in.readByte();
byte blockZ = in.readByte();
boolean writePacket = true;
boolean drop = false;
BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem);
if (server.options.getBoolean("enableEvents")) {
player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0)));
}
if (isServerTunnel || server.data.chests.isChest(coordinate)) {
// continue
} else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) {
if (!perm.use) {
player.addTMessage(Color.RED, "You can not use this block here!");
} else {
player.addTMessage(Color.RED, "You can not place this block here!");
}
writePacket = false;
drop = true;
} else if (dropItem == 54) {
int xPosition = x;
byte yPosition = y;
int zPosition = z;
switch (direction) {
case 0:
--yPosition;
break;
case 1:
++yPosition;
break;
case 2:
--zPosition;
break;
case 3:
++zPosition;
break;
case 4:
--xPosition;
break;
case 5:
++xPosition;
break;
}
Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player);
Chest adjacentChest = server.data.chests.adjacentChest(targetBlock);
if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) {
player.addTMessage(Color.RED, "The adjacent chest is locked!");
writePacket = false;
drop = true;
} else {
player.placingChest(targetBlock);
}
}
if (writePacket) {
write(packetId);
write(x);
write(y);
write(z);
write(direction);
write(dropItem);
if (dropItem != -1) {
write(itemCount);
write(uses);
if (data != null) {
write((short) data.length);
out.write(data);
} else {
write((short) -1);
}
if (dropItem <= 94 && direction >= 0) {
player.placedBlock();
}
}
write(blockX);
write(blockY);
write(blockZ);
player.openingChest(coordinate);
} else if (drop) {
// Drop the item in hand. This keeps the client state in-sync with the
// server. This generally prevents empty-hand clicks by the client
// from placing blocks the server thinks the client has in hand.
write((byte) 0x0e);
write((byte) 0x04);
write(x);
write(y);
write(z);
write(direction);
}
break;
case 0x10: // Holding Change
write(packetId);
copyNBytes(2);
break;
case 0x11: // Use Bed
write(packetId);
copyNBytes(14);
break;
case 0x12: // Animation
write(packetId);
copyNBytes(5);
break;
case 0x13: // Entity Action
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x14: // Named Entity Spawn
int eid = in.readInt();
name = readUTF16();
if (!server.bots.ninja(name)) {
write(packetId);
write(eid);
write(name);
copyNBytes(16);
copyUnknownBlob();
} else {
skipNBytes(16);
skipUnknownBlob();
}
break;
case 0x15: // Pickup Spawn
write(packetId);
copyNBytes(4);
copyItem();
copyNBytes(15);
break;
case 0x16: // Collect Item
write(packetId);
copyNBytes(8);
break;
case 0x17: // Add Object/Vehicle
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
int flag = in.readInt();
write(flag);
if (flag > 0) {
write(in.readShort());
write(in.readShort());
write(in.readShort());
}
break;
case 0x18: // Mob Spawn
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readByte());
write(in.readByte());
write(in.readShort());
write(in.readShort());
write(in.readShort());
copyUnknownBlob();
break;
case 0x19: // Entity: Painting
write(packetId);
write(in.readInt());
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
break;
case 0x1a: // Experience Orb
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readShort());
break;
case 0x1c: // Entity Velocity
write(packetId);
copyNBytes(10);
break;
case 0x1d: // Destroy Entity
write(packetId);
byte destoryCount = write(in.readByte());
if (destoryCount > 0) {
copyNBytes(destoryCount * 4);
}
break;
case 0x1e: // Entity
write(packetId);
copyNBytes(4);
break;
case 0x1f: // Entity Relative Move
write(packetId);
copyNBytes(7);
break;
case 0x20: // Entity Look
write(packetId);
copyNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
write(packetId);
copyNBytes(9);
break;
case 0x22: // Entity Teleport
write(packetId);
copyNBytes(18);
break;
case 0x23: // Entitiy Look
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x26: // Entity Status
write(packetId);
copyNBytes(5);
break;
case 0x27: // Attach Entity
write(packetId);
copyNBytes(8);
break;
case 0x28: // Entity Metadata
write(packetId);
write(in.readInt());
copyUnknownBlob();
break;
case 0x29: // Entity Effect
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readByte());
write(in.readShort());
break;
case 0x2a: // Remove Entity Effect
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x2b: // Experience
write(packetId);
player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort()));
break;
case 0x33: // Map Chunk
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readBoolean());
write(in.readShort());
write(in.readShort());
copyNBytes(write(in.readInt()));
break;
case 0x34: // Multi Block Change
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readShort());
copyNBytes(write(in.readInt()));
break;
case 0x35: // Block Change
write(packetId);
x = in.readInt();
y = in.readByte();
z = in.readInt();
short blockType = in.readShort();
byte metadata = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (blockType == 54 && player.placedChest(coordinate)) {
lockChest(coordinate);
player.placingChest(null);
}
write(x);
write(y);
write(z);
write(blockType);
write(metadata);
break;
case 0x36: // Block Action
write(packetId);
copyNBytes(14);
break;
case 0x37: // Mining progress
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
break;
case 0x38: // Chunk Bulk
write(packetId);
copyNBytes(write(in.readShort()) * 12 + write(in.readInt()));
break;
case 0x3c: // Explosion
write(packetId);
copyNBytes(28);
int recordCount = in.readInt();
write(recordCount);
copyNBytes(recordCount * 3);
write(in.readFloat());
write(in.readFloat());
write(in.readFloat());
break;
case 0x3d: // Sound/Particle Effect
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readByte());
break;
case 0x3e: // Named Sound/Particle Effect
write(packetId);
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readFloat());
write(in.readByte());
break;
case 0x46: // New/Invalid State
write(packetId);
write(in.readByte());
write(in.readByte());
break;
case 0x47: // Thunderbolt
write(packetId);
copyNBytes(17);
break;
case 0x64: // Open Window
boolean allow = true;
byte id = in.readByte();
byte invtype = in.readByte();
String typeString = readUTF16();
byte unknownByte = in.readByte();
if (invtype == 0) {
Chest adjacent = server.data.chests.adjacentChest(player.openedChest());
if (!server.data.chests.isChest(player.openedChest())) {
if (adjacent == null) {
server.data.chests.addOpenChest(player.openedChest());
} else {
server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name);
}
server.data.save();
}
if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) {
player.addTMessage(Color.RED, "You can't use chests here");
allow = false;
} else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) {
if (server.data.chests.isLocked(player.openedChest())) {
if (player.isAttemptingUnlock()) {
server.data.chests.unlock(player.openedChest());
server.data.save();
player.setAttemptedAction(null);
player.addTMessage(Color.RED, "This chest is no longer locked!");
typeString = t("Open Chest");
} else {
typeString = server.data.chests.chestName(player.openedChest());
}
} else {
typeString = t("Open Chest");
if (player.isAttemptLock()) {
lockChest(player.openedChest());
typeString = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName();
}
}
} else {
player.addTMessage(Color.RED, "This chest is locked!");
allow = false;
}
}
if (!allow) {
write((byte) 0x65);
write(id);
} else {
write(packetId);
write(id);
write(invtype);
write(typeString);
write(unknownByte);
}
break;
case 0x65: // Close Window
write(packetId);
write(in.readByte());
break;
case 0x66: // Window Click
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
write(in.readShort());
write(in.readByte());
copyItem();
break;
case 0x67: // Set Slot
write(packetId);
write(in.readByte());
write(in.readShort());
copyItem();
break;
case 0x68: // Window Items
write(packetId);
write(in.readByte());
short count = write(in.readShort());
for (int c = 0; c < count; ++c) {
copyItem();
}
break;
case 0x69: // Update Window Property
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readShort());
break;
case 0x6a: // Transaction
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
break;
case 0x6b: // Creative Inventory Action
write(packetId);
write(in.readShort());
copyItem();
break;
case 0x6c: // Enchant Item
write(packetId);
write(in.readByte());
write(in.readByte());
break;
case (byte) 0x82: // Update Sign
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(readUTF16());
write(readUTF16());
write(readUTF16());
write(readUTF16());
break;
case (byte) 0x83: // Item Data
write(packetId);
write(in.readShort());
write(in.readShort());
short length = in.readShort();
write(length);
- copyNBytes(0xff & length);
+ copyNBytes(length);
break;
case (byte) 0x84: // added in 12w06a
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(in.readByte());
short nbtLength = write(in.readShort());
if (nbtLength > 0) {
copyNBytes(nbtLength);
}
break;
case (byte) 0xc3: // BukkitContrib
write(packetId);
write(in.readInt());
copyNBytes(write(in.readInt()));
break;
case (byte) 0xc8: // Increment Statistic
write(packetId);
copyNBytes(5);
break;
case (byte) 0xc9: // Player List Item
write(packetId);
write(readUTF16());
write(in.readByte());
write(in.readShort());
break;
case (byte) 0xca: // Player Abilities
write(packetId);
write(in.readByte());
write(in.readByte());
write(in.readByte());
break;
case (byte) 0xcb: // Tab-Completion
write(packetId);
write(readUTF16());
break;
case (byte) 0xcc: // Locale and View Distance
write(packetId);
write(readUTF16());
write(in.readByte());
write(in.readByte());
write(in.readByte());
write(in.readBoolean());
break;
case (byte) 0xcd: // Login & Respawn
write(packetId);
write(in.readByte());
break;
case (byte) 0xd3: // Red Power (mod by Eloraam)
write(packetId);
copyNBytes(1);
copyVLC();
copyVLC();
copyVLC();
copyNBytes((int) copyVLC());
break;
case (byte) 0xe6: // ModLoaderMP by SDK
write(packetId);
write(in.readInt()); // mod
write(in.readInt()); // packet id
copyNBytes(write(in.readInt()) * 4); // ints
copyNBytes(write(in.readInt()) * 4); // floats
copyNBytes(write(in.readInt()) * 8); // doubles
int sizeString = write(in.readInt()); // strings
for (int i = 0; i < sizeString; i++) {
copyNBytes(write(in.readInt()));
}
break;
case (byte) 0xfa: // Plugin Message
write(packetId);
write(readUTF16());
copyNBytes(write(in.readShort()));
break;
case (byte) 0xfc: // Encryption Key Response
byte[] sharedKey = new byte[in.readShort()];
in.readFully(sharedKey);
byte[] challengeTokenResponse = new byte[in.readShort()];
in.readFully(challengeTokenResponse);
if (!isServerTunnel) {
if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) {
player.kick("Invalid client response");
break;
}
player.clientEncryption.setEncryptedSharedKey(sharedKey);
sharedKey = player.serverEncryption.getEncryptedSharedKey();
}
if (!isServerTunnel && server.authenticator.useCustAuth(player)
&& !server.authenticator.onlineAuthenticate(player)) {
player.kick(t("%s Failed to login: User not premium", "[CustAuth]"));
break;
}
write(packetId);
write((short) sharedKey.length);
write(sharedKey);
challengeTokenResponse = player.serverEncryption.encryptChallengeToken();
write((short) challengeTokenResponse.length);
write(challengeTokenResponse);
if (isServerTunnel) {
in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream)));
out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream)));
} else {
in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream)));
out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream)));
}
break;
case (byte) 0xfd: // Encryption Key Request (server -> client)
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
String serverId = readUTF16();
if (!server.authenticator.useCustAuth(player)) {
serverId = "-";
} else {
serverId = player.getConnectionHash();
}
write(serverId);
byte[] keyBytes = new byte[in.readShort()];
in.readFully(keyBytes);
byte[] challengeToken = new byte[in.readShort()];
in.readFully(challengeToken);
player.serverEncryption.setPublicKey(keyBytes);
byte[] key = player.clientEncryption.getPublicKey();
write((short) key.length);
write(key);
write((short) challengeToken.length);
write(challengeToken);
player.serverEncryption.setChallengeToken(challengeToken);
player.clientEncryption.setChallengeToken(challengeToken);
break;
case (byte) 0xfe: // Server List Ping
write(packetId);
write(in.readByte());
break;
case (byte) 0xff: // Disconnect/Kick
write(packetId);
String reason = readUTF16();
if (reason.startsWith("\u00a71")) {
reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s",
Main.protocolVersion,
Main.minecraftVersion,
server.config.properties.get("serverDescription"),
server.playerList.size(),
server.config.properties.getInt("maxPlayers"));
}
write(reason);
if (reason.startsWith("Took too long")) {
server.addRobot(player);
}
player.close();
break;
default:
if (EXPENSIVE_DEBUG_LOGGING) {
while (true) {
skipNBytes(1);
flushAll();
}
} else {
if (lastPacket != null) {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName() + " (after 0x" + Integer.toHexString(lastPacket));
} else {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName());
}
}
}
packetFinished();
lastPacket = (packetId == 0x00) ? lastPacket : packetId;
}
private void copyItem() throws IOException {
if (write(in.readShort()) > 0) {
write(in.readByte());
write(in.readShort());
short length;
if ((length = write(in.readShort())) > 0) {
copyNBytes(length);
}
}
}
private long copyVLC() throws IOException {
long value = 0;
int shift = 0;
while (true) {
int i = write(in.readByte());
value |= (i & 0x7F) << shift;
if ((i & 0x80) == 0) {
break;
}
shift += 7;
}
return value;
}
private String readUTF16() throws IOException {
short length = in.readShort();
StringBuilder string = new StringBuilder();
for (int i = 0; i < length; i++) {
string.append(in.readChar());
}
return string.toString();
}
private void lockChest(Coordinate coordinate) {
Chest adjacentChest = server.data.chests.adjacentChest(coordinate);
if (player.isAttemptLock() || adjacentChest != null && !adjacentChest.isOpen()) {
if (adjacentChest != null && !adjacentChest.isOpen()) {
server.data.chests.giveLock(adjacentChest.owner, coordinate, adjacentChest.name);
} else {
if (adjacentChest != null) {
adjacentChest.lock(player);
adjacentChest.name = player.nextChestName();
}
server.data.chests.giveLock(player, coordinate, player.nextChestName());
}
player.setAttemptedAction(null);
player.addTMessage(Color.GRAY, "This chest is now locked.");
} else if (!server.data.chests.isChest(coordinate)) {
server.data.chests.addOpenChest(coordinate);
}
server.data.save();
}
private void copyPlayerLocation() throws IOException {
double x = in.readDouble();
double y = in.readDouble();
double stance = in.readDouble();
double z = in.readDouble();
player.position.updatePosition(x, y, z, stance);
if (server.options.getBoolean("enableEvents")) {
player.checkLocationEvents();
}
write(x);
write(y);
write(stance);
write(z);
}
private void copyPlayerLook() throws IOException {
float yaw = in.readFloat();
float pitch = in.readFloat();
player.position.updateLook(yaw, pitch);
write(yaw);
write(pitch);
}
private void copyUnknownBlob() throws IOException {
byte unknown = in.readByte();
write(unknown);
while (unknown != 0x7f) {
int type = (unknown & 0xE0) >> 5;
switch (type) {
case 0:
write(in.readByte());
break;
case 1:
write(in.readShort());
break;
case 2:
write(in.readInt());
break;
case 3:
write(in.readFloat());
break;
case 4:
write(readUTF16());
break;
case 5:
copyItem();
}
unknown = in.readByte();
write(unknown);
}
}
private void skipUnknownBlob() throws IOException {
byte unknown = in.readByte();
while (unknown != 0x7f) {
int type = (unknown & 0xE0) >> 5;
switch (type) {
case 0:
in.readByte();
break;
case 1:
in.readShort();
break;
case 2:
in.readInt();
break;
case 3:
in.readFloat();
break;
case 4:
readUTF16();
break;
}
unknown = in.readByte();
}
}
private byte write(byte b) throws IOException {
out.writeByte(b);
return b;
}
private byte[] write(byte[] b) throws IOException {
out.write(b);
return b;
}
private short write(short s) throws IOException {
out.writeShort(s);
return s;
}
private int write(int i) throws IOException {
out.writeInt(i);
return i;
}
private long write(long l) throws IOException {
out.writeLong(l);
return l;
}
private float write(float f) throws IOException {
out.writeFloat(f);
return f;
}
private double write(double d) throws IOException {
out.writeDouble(d);
return d;
}
private String write(String s) throws IOException {
write((short) s.length());
out.writeChars(s);
return s;
}
private boolean write(boolean b) throws IOException {
out.writeBoolean(b);
return b;
}
private void skipNBytes(int bytes) throws IOException {
int overflow = bytes / buffer.length;
for (int c = 0; c < overflow; ++c) {
in.readFully(buffer, 0, buffer.length);
}
in.readFully(buffer, 0, bytes % buffer.length);
}
private void copyNBytes(int bytes) throws IOException {
int overflow = bytes / buffer.length;
for (int c = 0; c < overflow; ++c) {
in.readFully(buffer, 0, buffer.length);
out.write(buffer, 0, buffer.length);
}
in.readFully(buffer, 0, bytes % buffer.length);
out.write(buffer, 0, bytes % buffer.length);
}
private void kick(String reason) throws IOException {
write((byte) 0xff);
write(reason);
packetFinished();
}
private String getLastColorCode(String message) {
String colorCode = "";
int lastIndex = message.lastIndexOf('\u00a7');
if (lastIndex != -1 && lastIndex + 1 < message.length()) {
colorCode = message.substring(lastIndex, lastIndex + 2);
}
return colorCode;
}
private void sendMessage(String message) throws IOException {
if (message.length() > 0) {
if (message.length() > MESSAGE_SIZE) {
int end = MESSAGE_SIZE - 1;
while (end > 0 && message.charAt(end) != ' ') {
end--;
}
if (end == 0) {
end = MESSAGE_SIZE;
} else {
end++;
}
if (end > 0 && message.charAt(end) == '\u00a7') {
end--;
}
String firstPart = message.substring(0, end);
sendMessagePacket(firstPart);
sendMessage(getLastColorCode(firstPart) + message.substring(end));
} else {
int end = message.length();
if (message.charAt(end - 1) == '\u00a7') {
end--;
}
sendMessagePacket(message.substring(0, end));
}
}
}
private void sendMessagePacket(String message) throws IOException {
if (message.length() > MESSAGE_SIZE) {
println("Invalid message size: " + message);
return;
}
if (message.length() > 0) {
write((byte) 0x03);
write(message);
packetFinished();
}
}
private void packetFinished() throws IOException {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.packetFinished();
outputDumper.packetFinished();
}
}
private void flushAll() throws IOException {
try {
((OutputStream) out).flush();
} finally {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.flush();
}
}
}
private final class Tunneler extends Thread {
@Override
public void run() {
try {
while (run) {
lastRead = System.currentTimeMillis();
try {
handlePacket();
if (isServerTunnel) {
while (player.hasMessages()) {
sendMessage(player.getMessage());
}
} else {
while (player.hasForwardMessages()) {
sendMessage(player.getForwardMessage());
}
}
flushAll();
} catch (IOException e) {
if (run && !player.isRobot()) {
println(e);
print(streamType
+ " error handling traffic for " + player.getIPAddress());
if (lastPacket != null) {
System.out.print(" (" + Integer.toHexString(lastPacket) + ")");
}
System.out.println();
}
break;
}
}
try {
if (player.isKicked()) {
kick(player.getKickMsg());
}
flushAll();
} catch (IOException e) {
}
} finally {
if (EXPENSIVE_DEBUG_LOGGING) {
inputDumper.cleanup();
outputDumper.cleanup();
}
}
}
}
}
| true | true | private void handlePacket() throws IOException {
Byte packetId = in.readByte();
// System.out.println((isServerTunnel ? "server " : "client ") +
// String.format("%02x", packetId));
int x;
byte y;
int z;
byte dimension;
Coordinate coordinate;
switch (packetId) {
case 0x00: // Keep Alive
write(packetId);
write(in.readInt()); // random number that is returned from server
break;
case 0x01: // Login Request/Response
write(packetId);
if (!isServerTunnel) {
write(in.readInt());
write(readUTF16());
copyNBytes(5);
break;
}
player.setEntityId(write(in.readInt()));
write(readUTF16());
write(in.readByte());
dimension = in.readByte();
if (isServerTunnel) {
player.setDimension(Dimension.get(dimension));
}
write(dimension);
write(in.readByte());
write(in.readByte());
if (isServerTunnel) {
in.readByte();
write((byte) server.config.properties.getInt("maxPlayers"));
} else {
write(in.readByte());
}
break;
case 0x02: // Handshake
byte version = in.readByte();
String name = readUTF16();
boolean nameSet = false;
if (name.contains(";")) {
name = name.substring(0, name.indexOf(";"));
}
if (name.equals("Player") || !server.authenticator.isMinecraftUp) {
AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress());
if (req != null) {
name = req.playerName;
nameSet = server.authenticator.completeLogin(req, player);
}
if (req == null || !nameSet) {
if (!name.equals("Player")) {
player.addTMessage(Color.RED, "Login verification failed.");
player.addTMessage(Color.RED, "You were logged in as guest.");
}
name = server.authenticator.getFreeGuestName();
player.setGuest(true);
nameSet = player.setName(name);
}
} else {
nameSet = player.setName(name);
if (nameSet) {
player.updateRealName(name);
}
}
if (player.isGuest() && !server.authenticator.allowGuestJoin()) {
player.kick(t("Failed to login: User not authenticated"));
nameSet = false;
}
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
write(version);
write(player.getName());
write(readUTF16());
write(in.readInt());
break;
case 0x03: // Chat Message
String message = readUTF16();
Matcher joinMatcher = JOIN_PATTERN.matcher(message);
if (isServerTunnel && joinMatcher.find()) {
if (server.bots.ninja(joinMatcher.group(1))) {
break;
}
if (message.contains("join")) {
player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1));
} else {
player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1));
}
break;
}
if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) {
if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) {
break;
}
Matcher colorMatcher = COLOR_PATTERN.matcher(message);
String cleanMessage = colorMatcher.replaceAll("");
Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage);
if (messageMatcher.find()) {
} else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) {
break;
}
if (server.config.properties.getBoolean("msgWrap")) {
sendMessage(message);
} else {
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
} else if (!isServerTunnel) {
if (player.isMuted() && !message.startsWith("/")
&& !message.startsWith("!")) {
player.addTMessage(Color.RED, "You are muted! You may not send messages to all players.");
break;
}
if (message.charAt(0) == commandPrefix) {
message = player.parseCommand(message, false);
if (message == null) {
break;
}
write(packetId);
write(message);
return;
}
player.sendMessage(message);
}
break;
case 0x04: // Time Update
write(packetId);
write(in.readLong());
long time = in.readLong();
server.setTime(time);
write(time);
break;
case 0x05: // Player Inventory
write(packetId);
write(in.readInt());
write(in.readShort());
copyItem();
break;
case 0x06: // Spawn Position
write(packetId);
copyNBytes(12);
if (server.options.getBoolean("enableEvents")) {
server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null);
}
break;
case 0x07: // Use Entity
int user = in.readInt();
int target = in.readInt();
Player targetPlayer = server.playerList.findPlayer(target);
if (targetPlayer != null) {
if (targetPlayer.godModeEnabled()) {
in.readBoolean();
break;
}
}
write(packetId);
write(user);
write(target);
copyNBytes(1);
break;
case 0x08: // Update Health
write(packetId);
player.updateHealth(write(in.readShort()));
player.getHealth();
write(in.readShort());
write(in.readFloat());
break;
case 0x09: // Respawn
write(packetId);
if (!isServerTunnel) {
break;
}
player.setDimension(Dimension.get(write(in.readInt())));
write(in.readByte());
write(in.readByte());
write(in.readShort());
write(readUTF16()); // Added in 1.1 (level type)
if (server.options.getBoolean("enableEvents") && isServerTunnel) {
server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null);
}
break;
case 0x0a: // Player
write(packetId);
copyNBytes(1);
if (!inGame && !isServerTunnel) {
player.sendMOTD();
if (server.config.properties.getBoolean("showListOnConnect")) {
// display player list if enabled in config
player.execute(PlayerListCommand.class);
}
inGame = true;
}
break;
case 0x0b: // Player Position
write(packetId);
copyPlayerLocation();
copyNBytes(1);
break;
case 0x0c: // Player Look
write(packetId);
copyPlayerLook();
copyNBytes(1);
break;
case 0x0d: // Player Position & Look
write(packetId);
copyPlayerLocation();
copyPlayerLook();
copyNBytes(1);
break;
case 0x0e: // Player Digging
if (!isServerTunnel) {
byte status = in.readByte();
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte face = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (!player.getGroup().ignoreAreas) {
BlockPermission perm = server.config.blockPermission(player, coordinate);
if (!perm.use && status == 0) {
player.addTMessage(Color.RED, "You can not use this block here!");
break;
}
if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) {
player.addTMessage(Color.RED, "You can not destroy this block!");
break;
}
}
boolean locked = server.data.chests.isLocked(coordinate);
if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) {
if (locked && status == BLOCK_DESTROYED_STATUS) {
server.data.chests.releaseLock(coordinate);
server.data.save();
}
write(packetId);
write(status);
write(x);
write(y);
write(z);
write(face);
if (player.instantDestroyEnabled()) {
packetFinished();
write(packetId);
write(BLOCK_DESTROYED_STATUS);
write(x);
write(y);
write(z);
write(face);
}
if (status == BLOCK_DESTROYED_STATUS) {
player.destroyedBlock();
}
}
} else {
write(packetId);
copyNBytes(11);
}
break;
case 0x0f: // Player Block Placement
x = in.readInt();
y = in.readByte();
z = in.readInt();
coordinate = new Coordinate(x, y, z, player);
final byte direction = in.readByte();
final short dropItem = in.readShort();
byte itemCount = 0;
short uses = 0;
byte[] data = null;
if (dropItem != -1) {
itemCount = in.readByte();
uses = in.readShort();
short dataLength = in.readShort();
if (dataLength != -1) {
data = new byte[dataLength];
in.readFully(data);
}
}
byte blockX = in.readByte();
byte blockY = in.readByte();
byte blockZ = in.readByte();
boolean writePacket = true;
boolean drop = false;
BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem);
if (server.options.getBoolean("enableEvents")) {
player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0)));
}
if (isServerTunnel || server.data.chests.isChest(coordinate)) {
// continue
} else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) {
if (!perm.use) {
player.addTMessage(Color.RED, "You can not use this block here!");
} else {
player.addTMessage(Color.RED, "You can not place this block here!");
}
writePacket = false;
drop = true;
} else if (dropItem == 54) {
int xPosition = x;
byte yPosition = y;
int zPosition = z;
switch (direction) {
case 0:
--yPosition;
break;
case 1:
++yPosition;
break;
case 2:
--zPosition;
break;
case 3:
++zPosition;
break;
case 4:
--xPosition;
break;
case 5:
++xPosition;
break;
}
Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player);
Chest adjacentChest = server.data.chests.adjacentChest(targetBlock);
if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) {
player.addTMessage(Color.RED, "The adjacent chest is locked!");
writePacket = false;
drop = true;
} else {
player.placingChest(targetBlock);
}
}
if (writePacket) {
write(packetId);
write(x);
write(y);
write(z);
write(direction);
write(dropItem);
if (dropItem != -1) {
write(itemCount);
write(uses);
if (data != null) {
write((short) data.length);
out.write(data);
} else {
write((short) -1);
}
if (dropItem <= 94 && direction >= 0) {
player.placedBlock();
}
}
write(blockX);
write(blockY);
write(blockZ);
player.openingChest(coordinate);
} else if (drop) {
// Drop the item in hand. This keeps the client state in-sync with the
// server. This generally prevents empty-hand clicks by the client
// from placing blocks the server thinks the client has in hand.
write((byte) 0x0e);
write((byte) 0x04);
write(x);
write(y);
write(z);
write(direction);
}
break;
case 0x10: // Holding Change
write(packetId);
copyNBytes(2);
break;
case 0x11: // Use Bed
write(packetId);
copyNBytes(14);
break;
case 0x12: // Animation
write(packetId);
copyNBytes(5);
break;
case 0x13: // Entity Action
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x14: // Named Entity Spawn
int eid = in.readInt();
name = readUTF16();
if (!server.bots.ninja(name)) {
write(packetId);
write(eid);
write(name);
copyNBytes(16);
copyUnknownBlob();
} else {
skipNBytes(16);
skipUnknownBlob();
}
break;
case 0x15: // Pickup Spawn
write(packetId);
copyNBytes(4);
copyItem();
copyNBytes(15);
break;
case 0x16: // Collect Item
write(packetId);
copyNBytes(8);
break;
case 0x17: // Add Object/Vehicle
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
int flag = in.readInt();
write(flag);
if (flag > 0) {
write(in.readShort());
write(in.readShort());
write(in.readShort());
}
break;
case 0x18: // Mob Spawn
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readByte());
write(in.readByte());
write(in.readShort());
write(in.readShort());
write(in.readShort());
copyUnknownBlob();
break;
case 0x19: // Entity: Painting
write(packetId);
write(in.readInt());
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
break;
case 0x1a: // Experience Orb
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readShort());
break;
case 0x1c: // Entity Velocity
write(packetId);
copyNBytes(10);
break;
case 0x1d: // Destroy Entity
write(packetId);
byte destoryCount = write(in.readByte());
if (destoryCount > 0) {
copyNBytes(destoryCount * 4);
}
break;
case 0x1e: // Entity
write(packetId);
copyNBytes(4);
break;
case 0x1f: // Entity Relative Move
write(packetId);
copyNBytes(7);
break;
case 0x20: // Entity Look
write(packetId);
copyNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
write(packetId);
copyNBytes(9);
break;
case 0x22: // Entity Teleport
write(packetId);
copyNBytes(18);
break;
case 0x23: // Entitiy Look
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x26: // Entity Status
write(packetId);
copyNBytes(5);
break;
case 0x27: // Attach Entity
write(packetId);
copyNBytes(8);
break;
case 0x28: // Entity Metadata
write(packetId);
write(in.readInt());
copyUnknownBlob();
break;
case 0x29: // Entity Effect
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readByte());
write(in.readShort());
break;
case 0x2a: // Remove Entity Effect
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x2b: // Experience
write(packetId);
player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort()));
break;
case 0x33: // Map Chunk
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readBoolean());
write(in.readShort());
write(in.readShort());
copyNBytes(write(in.readInt()));
break;
case 0x34: // Multi Block Change
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readShort());
copyNBytes(write(in.readInt()));
break;
case 0x35: // Block Change
write(packetId);
x = in.readInt();
y = in.readByte();
z = in.readInt();
short blockType = in.readShort();
byte metadata = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (blockType == 54 && player.placedChest(coordinate)) {
lockChest(coordinate);
player.placingChest(null);
}
write(x);
write(y);
write(z);
write(blockType);
write(metadata);
break;
case 0x36: // Block Action
write(packetId);
copyNBytes(14);
break;
case 0x37: // Mining progress
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
break;
case 0x38: // Chunk Bulk
write(packetId);
copyNBytes(write(in.readShort()) * 12 + write(in.readInt()));
break;
case 0x3c: // Explosion
write(packetId);
copyNBytes(28);
int recordCount = in.readInt();
write(recordCount);
copyNBytes(recordCount * 3);
write(in.readFloat());
write(in.readFloat());
write(in.readFloat());
break;
case 0x3d: // Sound/Particle Effect
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readByte());
break;
case 0x3e: // Named Sound/Particle Effect
write(packetId);
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readFloat());
write(in.readByte());
break;
case 0x46: // New/Invalid State
write(packetId);
write(in.readByte());
write(in.readByte());
break;
case 0x47: // Thunderbolt
write(packetId);
copyNBytes(17);
break;
case 0x64: // Open Window
boolean allow = true;
byte id = in.readByte();
byte invtype = in.readByte();
String typeString = readUTF16();
byte unknownByte = in.readByte();
if (invtype == 0) {
Chest adjacent = server.data.chests.adjacentChest(player.openedChest());
if (!server.data.chests.isChest(player.openedChest())) {
if (adjacent == null) {
server.data.chests.addOpenChest(player.openedChest());
} else {
server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name);
}
server.data.save();
}
if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) {
player.addTMessage(Color.RED, "You can't use chests here");
allow = false;
} else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) {
if (server.data.chests.isLocked(player.openedChest())) {
if (player.isAttemptingUnlock()) {
server.data.chests.unlock(player.openedChest());
server.data.save();
player.setAttemptedAction(null);
player.addTMessage(Color.RED, "This chest is no longer locked!");
typeString = t("Open Chest");
} else {
typeString = server.data.chests.chestName(player.openedChest());
}
} else {
typeString = t("Open Chest");
if (player.isAttemptLock()) {
lockChest(player.openedChest());
typeString = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName();
}
}
} else {
player.addTMessage(Color.RED, "This chest is locked!");
allow = false;
}
}
if (!allow) {
write((byte) 0x65);
write(id);
} else {
write(packetId);
write(id);
write(invtype);
write(typeString);
write(unknownByte);
}
break;
case 0x65: // Close Window
write(packetId);
write(in.readByte());
break;
case 0x66: // Window Click
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
write(in.readShort());
write(in.readByte());
copyItem();
break;
case 0x67: // Set Slot
write(packetId);
write(in.readByte());
write(in.readShort());
copyItem();
break;
case 0x68: // Window Items
write(packetId);
write(in.readByte());
short count = write(in.readShort());
for (int c = 0; c < count; ++c) {
copyItem();
}
break;
case 0x69: // Update Window Property
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readShort());
break;
case 0x6a: // Transaction
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
break;
case 0x6b: // Creative Inventory Action
write(packetId);
write(in.readShort());
copyItem();
break;
case 0x6c: // Enchant Item
write(packetId);
write(in.readByte());
write(in.readByte());
break;
case (byte) 0x82: // Update Sign
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(readUTF16());
write(readUTF16());
write(readUTF16());
write(readUTF16());
break;
case (byte) 0x83: // Item Data
write(packetId);
write(in.readShort());
write(in.readShort());
short length = in.readShort();
write(length);
copyNBytes(0xff & length);
break;
case (byte) 0x84: // added in 12w06a
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(in.readByte());
short nbtLength = write(in.readShort());
if (nbtLength > 0) {
copyNBytes(nbtLength);
}
break;
case (byte) 0xc3: // BukkitContrib
write(packetId);
write(in.readInt());
copyNBytes(write(in.readInt()));
break;
case (byte) 0xc8: // Increment Statistic
write(packetId);
copyNBytes(5);
break;
case (byte) 0xc9: // Player List Item
write(packetId);
write(readUTF16());
write(in.readByte());
write(in.readShort());
break;
case (byte) 0xca: // Player Abilities
write(packetId);
write(in.readByte());
write(in.readByte());
write(in.readByte());
break;
case (byte) 0xcb: // Tab-Completion
write(packetId);
write(readUTF16());
break;
case (byte) 0xcc: // Locale and View Distance
write(packetId);
write(readUTF16());
write(in.readByte());
write(in.readByte());
write(in.readByte());
write(in.readBoolean());
break;
case (byte) 0xcd: // Login & Respawn
write(packetId);
write(in.readByte());
break;
case (byte) 0xd3: // Red Power (mod by Eloraam)
write(packetId);
copyNBytes(1);
copyVLC();
copyVLC();
copyVLC();
copyNBytes((int) copyVLC());
break;
case (byte) 0xe6: // ModLoaderMP by SDK
write(packetId);
write(in.readInt()); // mod
write(in.readInt()); // packet id
copyNBytes(write(in.readInt()) * 4); // ints
copyNBytes(write(in.readInt()) * 4); // floats
copyNBytes(write(in.readInt()) * 8); // doubles
int sizeString = write(in.readInt()); // strings
for (int i = 0; i < sizeString; i++) {
copyNBytes(write(in.readInt()));
}
break;
case (byte) 0xfa: // Plugin Message
write(packetId);
write(readUTF16());
copyNBytes(write(in.readShort()));
break;
case (byte) 0xfc: // Encryption Key Response
byte[] sharedKey = new byte[in.readShort()];
in.readFully(sharedKey);
byte[] challengeTokenResponse = new byte[in.readShort()];
in.readFully(challengeTokenResponse);
if (!isServerTunnel) {
if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) {
player.kick("Invalid client response");
break;
}
player.clientEncryption.setEncryptedSharedKey(sharedKey);
sharedKey = player.serverEncryption.getEncryptedSharedKey();
}
if (!isServerTunnel && server.authenticator.useCustAuth(player)
&& !server.authenticator.onlineAuthenticate(player)) {
player.kick(t("%s Failed to login: User not premium", "[CustAuth]"));
break;
}
write(packetId);
write((short) sharedKey.length);
write(sharedKey);
challengeTokenResponse = player.serverEncryption.encryptChallengeToken();
write((short) challengeTokenResponse.length);
write(challengeTokenResponse);
if (isServerTunnel) {
in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream)));
out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream)));
} else {
in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream)));
out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream)));
}
break;
case (byte) 0xfd: // Encryption Key Request (server -> client)
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
String serverId = readUTF16();
if (!server.authenticator.useCustAuth(player)) {
serverId = "-";
} else {
serverId = player.getConnectionHash();
}
write(serverId);
byte[] keyBytes = new byte[in.readShort()];
in.readFully(keyBytes);
byte[] challengeToken = new byte[in.readShort()];
in.readFully(challengeToken);
player.serverEncryption.setPublicKey(keyBytes);
byte[] key = player.clientEncryption.getPublicKey();
write((short) key.length);
write(key);
write((short) challengeToken.length);
write(challengeToken);
player.serverEncryption.setChallengeToken(challengeToken);
player.clientEncryption.setChallengeToken(challengeToken);
break;
case (byte) 0xfe: // Server List Ping
write(packetId);
write(in.readByte());
break;
case (byte) 0xff: // Disconnect/Kick
write(packetId);
String reason = readUTF16();
if (reason.startsWith("\u00a71")) {
reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s",
Main.protocolVersion,
Main.minecraftVersion,
server.config.properties.get("serverDescription"),
server.playerList.size(),
server.config.properties.getInt("maxPlayers"));
}
write(reason);
if (reason.startsWith("Took too long")) {
server.addRobot(player);
}
player.close();
break;
default:
if (EXPENSIVE_DEBUG_LOGGING) {
while (true) {
skipNBytes(1);
flushAll();
}
} else {
if (lastPacket != null) {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName() + " (after 0x" + Integer.toHexString(lastPacket));
} else {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName());
}
}
}
packetFinished();
lastPacket = (packetId == 0x00) ? lastPacket : packetId;
}
| private void handlePacket() throws IOException {
Byte packetId = in.readByte();
// System.out.println((isServerTunnel ? "server " : "client ") +
// String.format("%02x", packetId));
int x;
byte y;
int z;
byte dimension;
Coordinate coordinate;
switch (packetId) {
case 0x00: // Keep Alive
write(packetId);
write(in.readInt()); // random number that is returned from server
break;
case 0x01: // Login Request/Response
write(packetId);
if (!isServerTunnel) {
write(in.readInt());
write(readUTF16());
copyNBytes(5);
break;
}
player.setEntityId(write(in.readInt()));
write(readUTF16());
write(in.readByte());
dimension = in.readByte();
if (isServerTunnel) {
player.setDimension(Dimension.get(dimension));
}
write(dimension);
write(in.readByte());
write(in.readByte());
if (isServerTunnel) {
in.readByte();
write((byte) server.config.properties.getInt("maxPlayers"));
} else {
write(in.readByte());
}
break;
case 0x02: // Handshake
byte version = in.readByte();
String name = readUTF16();
boolean nameSet = false;
if (name.contains(";")) {
name = name.substring(0, name.indexOf(";"));
}
if (name.equals("Player") || !server.authenticator.isMinecraftUp) {
AuthRequest req = server.authenticator.getAuthRequest(player.getIPAddress());
if (req != null) {
name = req.playerName;
nameSet = server.authenticator.completeLogin(req, player);
}
if (req == null || !nameSet) {
if (!name.equals("Player")) {
player.addTMessage(Color.RED, "Login verification failed.");
player.addTMessage(Color.RED, "You were logged in as guest.");
}
name = server.authenticator.getFreeGuestName();
player.setGuest(true);
nameSet = player.setName(name);
}
} else {
nameSet = player.setName(name);
if (nameSet) {
player.updateRealName(name);
}
}
if (player.isGuest() && !server.authenticator.allowGuestJoin()) {
player.kick(t("Failed to login: User not authenticated"));
nameSet = false;
}
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
write(version);
write(player.getName());
write(readUTF16());
write(in.readInt());
break;
case 0x03: // Chat Message
String message = readUTF16();
Matcher joinMatcher = JOIN_PATTERN.matcher(message);
if (isServerTunnel && joinMatcher.find()) {
if (server.bots.ninja(joinMatcher.group(1))) {
break;
}
if (message.contains("join")) {
player.addTMessage(Color.YELLOW, "%s joined the game.", joinMatcher.group(1));
} else {
player.addTMessage(Color.YELLOW, "%s left the game.", joinMatcher.group(1));
}
break;
}
if (isServerTunnel && server.config.properties.getBoolean("useMsgFormats")) {
if (server.config.properties.getBoolean("forwardChat") && server.getMessager().wasForwarded(message)) {
break;
}
Matcher colorMatcher = COLOR_PATTERN.matcher(message);
String cleanMessage = colorMatcher.replaceAll("");
Matcher messageMatcher = MESSAGE_PATTERN.matcher(cleanMessage);
if (messageMatcher.find()) {
} else if (cleanMessage.matches(CONSOLE_CHAT_PATTERN) && !server.config.properties.getBoolean("chatConsoleToOps")) {
break;
}
if (server.config.properties.getBoolean("msgWrap")) {
sendMessage(message);
} else {
if (message.length() > MAXIMUM_MESSAGE_SIZE) {
message = message.substring(0, MAXIMUM_MESSAGE_SIZE);
}
write(packetId);
write(message);
}
} else if (!isServerTunnel) {
if (player.isMuted() && !message.startsWith("/")
&& !message.startsWith("!")) {
player.addTMessage(Color.RED, "You are muted! You may not send messages to all players.");
break;
}
if (message.charAt(0) == commandPrefix) {
message = player.parseCommand(message, false);
if (message == null) {
break;
}
write(packetId);
write(message);
return;
}
player.sendMessage(message);
}
break;
case 0x04: // Time Update
write(packetId);
write(in.readLong());
long time = in.readLong();
server.setTime(time);
write(time);
break;
case 0x05: // Player Inventory
write(packetId);
write(in.readInt());
write(in.readShort());
copyItem();
break;
case 0x06: // Spawn Position
write(packetId);
copyNBytes(12);
if (server.options.getBoolean("enableEvents")) {
server.eventhost.execute(server.eventhost.findEvent("onPlayerConnect"), player, true, null);
}
break;
case 0x07: // Use Entity
int user = in.readInt();
int target = in.readInt();
Player targetPlayer = server.playerList.findPlayer(target);
if (targetPlayer != null) {
if (targetPlayer.godModeEnabled()) {
in.readBoolean();
break;
}
}
write(packetId);
write(user);
write(target);
copyNBytes(1);
break;
case 0x08: // Update Health
write(packetId);
player.updateHealth(write(in.readShort()));
player.getHealth();
write(in.readShort());
write(in.readFloat());
break;
case 0x09: // Respawn
write(packetId);
if (!isServerTunnel) {
break;
}
player.setDimension(Dimension.get(write(in.readInt())));
write(in.readByte());
write(in.readByte());
write(in.readShort());
write(readUTF16()); // Added in 1.1 (level type)
if (server.options.getBoolean("enableEvents") && isServerTunnel) {
server.eventhost.execute(server.eventhost.findEvent("onPlayerRespawn"), player, true, null);
}
break;
case 0x0a: // Player
write(packetId);
copyNBytes(1);
if (!inGame && !isServerTunnel) {
player.sendMOTD();
if (server.config.properties.getBoolean("showListOnConnect")) {
// display player list if enabled in config
player.execute(PlayerListCommand.class);
}
inGame = true;
}
break;
case 0x0b: // Player Position
write(packetId);
copyPlayerLocation();
copyNBytes(1);
break;
case 0x0c: // Player Look
write(packetId);
copyPlayerLook();
copyNBytes(1);
break;
case 0x0d: // Player Position & Look
write(packetId);
copyPlayerLocation();
copyPlayerLook();
copyNBytes(1);
break;
case 0x0e: // Player Digging
if (!isServerTunnel) {
byte status = in.readByte();
x = in.readInt();
y = in.readByte();
z = in.readInt();
byte face = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (!player.getGroup().ignoreAreas) {
BlockPermission perm = server.config.blockPermission(player, coordinate);
if (!perm.use && status == 0) {
player.addTMessage(Color.RED, "You can not use this block here!");
break;
}
if (!perm.destroy && status == BLOCK_DESTROYED_STATUS) {
player.addTMessage(Color.RED, "You can not destroy this block!");
break;
}
}
boolean locked = server.data.chests.isLocked(coordinate);
if (!locked || player.ignoresChestLocks() || server.data.chests.canOpen(player, coordinate)) {
if (locked && status == BLOCK_DESTROYED_STATUS) {
server.data.chests.releaseLock(coordinate);
server.data.save();
}
write(packetId);
write(status);
write(x);
write(y);
write(z);
write(face);
if (player.instantDestroyEnabled()) {
packetFinished();
write(packetId);
write(BLOCK_DESTROYED_STATUS);
write(x);
write(y);
write(z);
write(face);
}
if (status == BLOCK_DESTROYED_STATUS) {
player.destroyedBlock();
}
}
} else {
write(packetId);
copyNBytes(11);
}
break;
case 0x0f: // Player Block Placement
x = in.readInt();
y = in.readByte();
z = in.readInt();
coordinate = new Coordinate(x, y, z, player);
final byte direction = in.readByte();
final short dropItem = in.readShort();
byte itemCount = 0;
short uses = 0;
byte[] data = null;
if (dropItem != -1) {
itemCount = in.readByte();
uses = in.readShort();
short dataLength = in.readShort();
if (dataLength != -1) {
data = new byte[dataLength];
in.readFully(data);
}
}
byte blockX = in.readByte();
byte blockY = in.readByte();
byte blockZ = in.readByte();
boolean writePacket = true;
boolean drop = false;
BlockPermission perm = server.config.blockPermission(player, coordinate, dropItem);
if (server.options.getBoolean("enableEvents")) {
player.checkButtonEvents(new Coordinate(x + (x < 0 ? 1 : 0), y + 1, z + (z < 0 ? 1 : 0)));
}
if (isServerTunnel || server.data.chests.isChest(coordinate)) {
// continue
} else if (!player.getGroup().ignoreAreas && ((dropItem != -1 && !perm.place) || !perm.use)) {
if (!perm.use) {
player.addTMessage(Color.RED, "You can not use this block here!");
} else {
player.addTMessage(Color.RED, "You can not place this block here!");
}
writePacket = false;
drop = true;
} else if (dropItem == 54) {
int xPosition = x;
byte yPosition = y;
int zPosition = z;
switch (direction) {
case 0:
--yPosition;
break;
case 1:
++yPosition;
break;
case 2:
--zPosition;
break;
case 3:
++zPosition;
break;
case 4:
--xPosition;
break;
case 5:
++xPosition;
break;
}
Coordinate targetBlock = new Coordinate(xPosition, yPosition, zPosition, player);
Chest adjacentChest = server.data.chests.adjacentChest(targetBlock);
if (adjacentChest != null && !adjacentChest.isOpen() && !adjacentChest.ownedBy(player)) {
player.addTMessage(Color.RED, "The adjacent chest is locked!");
writePacket = false;
drop = true;
} else {
player.placingChest(targetBlock);
}
}
if (writePacket) {
write(packetId);
write(x);
write(y);
write(z);
write(direction);
write(dropItem);
if (dropItem != -1) {
write(itemCount);
write(uses);
if (data != null) {
write((short) data.length);
out.write(data);
} else {
write((short) -1);
}
if (dropItem <= 94 && direction >= 0) {
player.placedBlock();
}
}
write(blockX);
write(blockY);
write(blockZ);
player.openingChest(coordinate);
} else if (drop) {
// Drop the item in hand. This keeps the client state in-sync with the
// server. This generally prevents empty-hand clicks by the client
// from placing blocks the server thinks the client has in hand.
write((byte) 0x0e);
write((byte) 0x04);
write(x);
write(y);
write(z);
write(direction);
}
break;
case 0x10: // Holding Change
write(packetId);
copyNBytes(2);
break;
case 0x11: // Use Bed
write(packetId);
copyNBytes(14);
break;
case 0x12: // Animation
write(packetId);
copyNBytes(5);
break;
case 0x13: // Entity Action
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x14: // Named Entity Spawn
int eid = in.readInt();
name = readUTF16();
if (!server.bots.ninja(name)) {
write(packetId);
write(eid);
write(name);
copyNBytes(16);
copyUnknownBlob();
} else {
skipNBytes(16);
skipUnknownBlob();
}
break;
case 0x15: // Pickup Spawn
write(packetId);
copyNBytes(4);
copyItem();
copyNBytes(15);
break;
case 0x16: // Collect Item
write(packetId);
copyNBytes(8);
break;
case 0x17: // Add Object/Vehicle
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
int flag = in.readInt();
write(flag);
if (flag > 0) {
write(in.readShort());
write(in.readShort());
write(in.readShort());
}
break;
case 0x18: // Mob Spawn
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readByte());
write(in.readByte());
write(in.readShort());
write(in.readShort());
write(in.readShort());
copyUnknownBlob();
break;
case 0x19: // Entity: Painting
write(packetId);
write(in.readInt());
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
break;
case 0x1a: // Experience Orb
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readShort());
break;
case 0x1c: // Entity Velocity
write(packetId);
copyNBytes(10);
break;
case 0x1d: // Destroy Entity
write(packetId);
byte destoryCount = write(in.readByte());
if (destoryCount > 0) {
copyNBytes(destoryCount * 4);
}
break;
case 0x1e: // Entity
write(packetId);
copyNBytes(4);
break;
case 0x1f: // Entity Relative Move
write(packetId);
copyNBytes(7);
break;
case 0x20: // Entity Look
write(packetId);
copyNBytes(6);
break;
case 0x21: // Entity Look and Relative Move
write(packetId);
copyNBytes(9);
break;
case 0x22: // Entity Teleport
write(packetId);
copyNBytes(18);
break;
case 0x23: // Entitiy Look
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x26: // Entity Status
write(packetId);
copyNBytes(5);
break;
case 0x27: // Attach Entity
write(packetId);
copyNBytes(8);
break;
case 0x28: // Entity Metadata
write(packetId);
write(in.readInt());
copyUnknownBlob();
break;
case 0x29: // Entity Effect
write(packetId);
write(in.readInt());
write(in.readByte());
write(in.readByte());
write(in.readShort());
break;
case 0x2a: // Remove Entity Effect
write(packetId);
write(in.readInt());
write(in.readByte());
break;
case 0x2b: // Experience
write(packetId);
player.updateExperience(write(in.readFloat()), write(in.readShort()), write(in.readShort()));
break;
case 0x33: // Map Chunk
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readBoolean());
write(in.readShort());
write(in.readShort());
copyNBytes(write(in.readInt()));
break;
case 0x34: // Multi Block Change
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readShort());
copyNBytes(write(in.readInt()));
break;
case 0x35: // Block Change
write(packetId);
x = in.readInt();
y = in.readByte();
z = in.readInt();
short blockType = in.readShort();
byte metadata = in.readByte();
coordinate = new Coordinate(x, y, z, player);
if (blockType == 54 && player.placedChest(coordinate)) {
lockChest(coordinate);
player.placingChest(null);
}
write(x);
write(y);
write(z);
write(blockType);
write(metadata);
break;
case 0x36: // Block Action
write(packetId);
copyNBytes(14);
break;
case 0x37: // Mining progress
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readByte());
break;
case 0x38: // Chunk Bulk
write(packetId);
copyNBytes(write(in.readShort()) * 12 + write(in.readInt()));
break;
case 0x3c: // Explosion
write(packetId);
copyNBytes(28);
int recordCount = in.readInt();
write(recordCount);
copyNBytes(recordCount * 3);
write(in.readFloat());
write(in.readFloat());
write(in.readFloat());
break;
case 0x3d: // Sound/Particle Effect
write(packetId);
write(in.readInt());
write(in.readInt());
write(in.readByte());
write(in.readInt());
write(in.readInt());
write(in.readByte());
break;
case 0x3e: // Named Sound/Particle Effect
write(packetId);
write(readUTF16());
write(in.readInt());
write(in.readInt());
write(in.readInt());
write(in.readFloat());
write(in.readByte());
break;
case 0x46: // New/Invalid State
write(packetId);
write(in.readByte());
write(in.readByte());
break;
case 0x47: // Thunderbolt
write(packetId);
copyNBytes(17);
break;
case 0x64: // Open Window
boolean allow = true;
byte id = in.readByte();
byte invtype = in.readByte();
String typeString = readUTF16();
byte unknownByte = in.readByte();
if (invtype == 0) {
Chest adjacent = server.data.chests.adjacentChest(player.openedChest());
if (!server.data.chests.isChest(player.openedChest())) {
if (adjacent == null) {
server.data.chests.addOpenChest(player.openedChest());
} else {
server.data.chests.giveLock(adjacent.owner, player.openedChest(), adjacent.name);
}
server.data.save();
}
if (!player.getGroup().ignoreAreas && (!server.config.blockPermission(player, player.openedChest()).chest || (adjacent != null && !server.config.blockPermission(player, adjacent.coordinate).chest))) {
player.addTMessage(Color.RED, "You can't use chests here");
allow = false;
} else if (server.data.chests.canOpen(player, player.openedChest()) || player.ignoresChestLocks()) {
if (server.data.chests.isLocked(player.openedChest())) {
if (player.isAttemptingUnlock()) {
server.data.chests.unlock(player.openedChest());
server.data.save();
player.setAttemptedAction(null);
player.addTMessage(Color.RED, "This chest is no longer locked!");
typeString = t("Open Chest");
} else {
typeString = server.data.chests.chestName(player.openedChest());
}
} else {
typeString = t("Open Chest");
if (player.isAttemptLock()) {
lockChest(player.openedChest());
typeString = (player.nextChestName() == null) ? t("Locked Chest") : player.nextChestName();
}
}
} else {
player.addTMessage(Color.RED, "This chest is locked!");
allow = false;
}
}
if (!allow) {
write((byte) 0x65);
write(id);
} else {
write(packetId);
write(id);
write(invtype);
write(typeString);
write(unknownByte);
}
break;
case 0x65: // Close Window
write(packetId);
write(in.readByte());
break;
case 0x66: // Window Click
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
write(in.readShort());
write(in.readByte());
copyItem();
break;
case 0x67: // Set Slot
write(packetId);
write(in.readByte());
write(in.readShort());
copyItem();
break;
case 0x68: // Window Items
write(packetId);
write(in.readByte());
short count = write(in.readShort());
for (int c = 0; c < count; ++c) {
copyItem();
}
break;
case 0x69: // Update Window Property
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readShort());
break;
case 0x6a: // Transaction
write(packetId);
write(in.readByte());
write(in.readShort());
write(in.readByte());
break;
case 0x6b: // Creative Inventory Action
write(packetId);
write(in.readShort());
copyItem();
break;
case 0x6c: // Enchant Item
write(packetId);
write(in.readByte());
write(in.readByte());
break;
case (byte) 0x82: // Update Sign
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(readUTF16());
write(readUTF16());
write(readUTF16());
write(readUTF16());
break;
case (byte) 0x83: // Item Data
write(packetId);
write(in.readShort());
write(in.readShort());
short length = in.readShort();
write(length);
copyNBytes(length);
break;
case (byte) 0x84: // added in 12w06a
write(packetId);
write(in.readInt());
write(in.readShort());
write(in.readInt());
write(in.readByte());
short nbtLength = write(in.readShort());
if (nbtLength > 0) {
copyNBytes(nbtLength);
}
break;
case (byte) 0xc3: // BukkitContrib
write(packetId);
write(in.readInt());
copyNBytes(write(in.readInt()));
break;
case (byte) 0xc8: // Increment Statistic
write(packetId);
copyNBytes(5);
break;
case (byte) 0xc9: // Player List Item
write(packetId);
write(readUTF16());
write(in.readByte());
write(in.readShort());
break;
case (byte) 0xca: // Player Abilities
write(packetId);
write(in.readByte());
write(in.readByte());
write(in.readByte());
break;
case (byte) 0xcb: // Tab-Completion
write(packetId);
write(readUTF16());
break;
case (byte) 0xcc: // Locale and View Distance
write(packetId);
write(readUTF16());
write(in.readByte());
write(in.readByte());
write(in.readByte());
write(in.readBoolean());
break;
case (byte) 0xcd: // Login & Respawn
write(packetId);
write(in.readByte());
break;
case (byte) 0xd3: // Red Power (mod by Eloraam)
write(packetId);
copyNBytes(1);
copyVLC();
copyVLC();
copyVLC();
copyNBytes((int) copyVLC());
break;
case (byte) 0xe6: // ModLoaderMP by SDK
write(packetId);
write(in.readInt()); // mod
write(in.readInt()); // packet id
copyNBytes(write(in.readInt()) * 4); // ints
copyNBytes(write(in.readInt()) * 4); // floats
copyNBytes(write(in.readInt()) * 8); // doubles
int sizeString = write(in.readInt()); // strings
for (int i = 0; i < sizeString; i++) {
copyNBytes(write(in.readInt()));
}
break;
case (byte) 0xfa: // Plugin Message
write(packetId);
write(readUTF16());
copyNBytes(write(in.readShort()));
break;
case (byte) 0xfc: // Encryption Key Response
byte[] sharedKey = new byte[in.readShort()];
in.readFully(sharedKey);
byte[] challengeTokenResponse = new byte[in.readShort()];
in.readFully(challengeTokenResponse);
if (!isServerTunnel) {
if (!player.clientEncryption.checkChallengeToken(challengeTokenResponse)) {
player.kick("Invalid client response");
break;
}
player.clientEncryption.setEncryptedSharedKey(sharedKey);
sharedKey = player.serverEncryption.getEncryptedSharedKey();
}
if (!isServerTunnel && server.authenticator.useCustAuth(player)
&& !server.authenticator.onlineAuthenticate(player)) {
player.kick(t("%s Failed to login: User not premium", "[CustAuth]"));
break;
}
write(packetId);
write((short) sharedKey.length);
write(sharedKey);
challengeTokenResponse = player.serverEncryption.encryptChallengeToken();
write((short) challengeTokenResponse.length);
write(challengeTokenResponse);
if (isServerTunnel) {
in = new DataInputStream(new BufferedInputStream(player.serverEncryption.encryptedInputStream(inputStream)));
out = new DataOutputStream(new BufferedOutputStream(player.clientEncryption.encryptedOutputStream(outputStream)));
} else {
in = new DataInputStream(new BufferedInputStream(player.clientEncryption.encryptedInputStream(inputStream)));
out = new DataOutputStream(new BufferedOutputStream(player.serverEncryption.encryptedOutputStream(outputStream)));
}
break;
case (byte) 0xfd: // Encryption Key Request (server -> client)
tunneler.setName(streamType + "-" + player.getName());
write(packetId);
String serverId = readUTF16();
if (!server.authenticator.useCustAuth(player)) {
serverId = "-";
} else {
serverId = player.getConnectionHash();
}
write(serverId);
byte[] keyBytes = new byte[in.readShort()];
in.readFully(keyBytes);
byte[] challengeToken = new byte[in.readShort()];
in.readFully(challengeToken);
player.serverEncryption.setPublicKey(keyBytes);
byte[] key = player.clientEncryption.getPublicKey();
write((short) key.length);
write(key);
write((short) challengeToken.length);
write(challengeToken);
player.serverEncryption.setChallengeToken(challengeToken);
player.clientEncryption.setChallengeToken(challengeToken);
break;
case (byte) 0xfe: // Server List Ping
write(packetId);
write(in.readByte());
break;
case (byte) 0xff: // Disconnect/Kick
write(packetId);
String reason = readUTF16();
if (reason.startsWith("\u00a71")) {
reason = String.format("\u00a71\0%s\0%s\0%s\0%s\0%s",
Main.protocolVersion,
Main.minecraftVersion,
server.config.properties.get("serverDescription"),
server.playerList.size(),
server.config.properties.getInt("maxPlayers"));
}
write(reason);
if (reason.startsWith("Took too long")) {
server.addRobot(player);
}
player.close();
break;
default:
if (EXPENSIVE_DEBUG_LOGGING) {
while (true) {
skipNBytes(1);
flushAll();
}
} else {
if (lastPacket != null) {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName() + " (after 0x" + Integer.toHexString(lastPacket));
} else {
throw new IOException("Unable to parse unknown " + streamType
+ " packet 0x" + Integer.toHexString(packetId) + " for player "
+ player.getName());
}
}
}
packetFinished();
lastPacket = (packetId == 0x00) ? lastPacket : packetId;
}
|
diff --git a/svnkit-cli/src/org/tmatesoft/svn/cli/svn/SVNPropSetCommand.java b/svnkit-cli/src/org/tmatesoft/svn/cli/svn/SVNPropSetCommand.java
index 023111228..36963e7e7 100644
--- a/svnkit-cli/src/org/tmatesoft/svn/cli/svn/SVNPropSetCommand.java
+++ b/svnkit-cli/src/org/tmatesoft/svn/cli/svn/SVNPropSetCommand.java
@@ -1,191 +1,201 @@
/*
* ====================================================================
* Copyright (c) 2004-2009 TMate Software Ltd. All rights reserved.
*
* This software is licensed as described in the file COPYING, which
* you should have received as part of this distribution. The terms
* are also available at http://svnkit.com/license.html.
* If newer versions of this license are posted there, you may use a
* newer version instead, at your option.
* ====================================================================
*/
package org.tmatesoft.svn.cli.svn;
import java.io.UnsupportedEncodingException;
import java.text.MessageFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Iterator;
import java.util.LinkedList;
import org.tmatesoft.svn.cli.SVNCommandUtil;
import org.tmatesoft.svn.core.SVNDepth;
import org.tmatesoft.svn.core.SVNErrorCode;
import org.tmatesoft.svn.core.SVNErrorMessage;
import org.tmatesoft.svn.core.SVNException;
import org.tmatesoft.svn.core.SVNPropertyValue;
import org.tmatesoft.svn.core.SVNURL;
import org.tmatesoft.svn.core.internal.wc.SVNErrorManager;
import org.tmatesoft.svn.core.internal.wc.SVNPath;
import org.tmatesoft.svn.core.internal.wc.SVNPropertiesManager;
import org.tmatesoft.svn.core.wc.SVNPropertyData;
import org.tmatesoft.svn.core.wc.SVNRevision;
import org.tmatesoft.svn.core.wc.SVNWCClient;
import org.tmatesoft.svn.util.SVNLogType;
/**
* @author TMate Software Ltd.
* @version 1.3
*/
public class SVNPropSetCommand extends SVNPropertiesCommand {
public SVNPropSetCommand() {
super("propset", new String[]{"pset", "ps"});
}
protected Collection createSupportedOptions() {
Collection options = new LinkedList();
options.add(SVNOption.FILE);
options.add(SVNOption.ENCODING);
options.add(SVNOption.QUIET);
options.add(SVNOption.REVISION);
options.add(SVNOption.TARGETS);
options.add(SVNOption.RECURSIVE);
options.add(SVNOption.DEPTH);
options.add(SVNOption.REVPROP);
options.add(SVNOption.FORCE);
options.add(SVNOption.CHANGELIST);
return options;
}
public void run() throws SVNException {
String propertyName = getSVNEnvironment().popArgument();
if (propertyName == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS);
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (!SVNPropertiesManager.isValidPropertyName(propertyName)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME,
"''{0}'' is not a valid Subversion property name", propertyName);
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
String encoding = null;
if (SVNPropertiesManager.propNeedsTranslation(propertyName)) {
encoding = getSVNEnvironment().getEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
} else {
if (getSVNEnvironment().getEncoding() != null) {
SVNErrorMessage errorMessage = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE,
"Bad encoding option: prop value not stored as UTF8");
SVNErrorManager.error(errorMessage, SVNLogType.CLIENT);
}
}
SVNPropertyValue propertyValue = null;
if (encoding != null) {
if (getSVNEnvironment().getFileData() != null) {
String stringValue = null;
try {
stringValue = new String(getSVNEnvironment().getFileData(), encoding);
} catch (UnsupportedEncodingException e) {
stringValue = new String(getSVNEnvironment().getFileData());
}
propertyValue = SVNPropertyValue.create(stringValue);
} else {
- propertyValue = SVNPropertyValue.create(getSVNEnvironment().popArgument());
+ String argument = getSVNEnvironment().popArgument();
+ if (argument == null) {
+ SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS);
+ SVNErrorManager.error(err, SVNLogType.CLIENT);
+ }
+ propertyValue = SVNPropertyValue.create(argument);
}
} else {
if (getSVNEnvironment().getFileData() != null) {
propertyValue = SVNPropertyValue.create(propertyName, getSVNEnvironment().getFileData());
} else {
- propertyValue = SVNPropertyValue.create(propertyName, getSVNEnvironment().popArgument().getBytes());
+ String argument = getSVNEnvironment().popArgument();
+ if (argument == null) {
+ SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS);
+ SVNErrorManager.error(err, SVNLogType.CLIENT);
+ }
+ propertyValue = SVNPropertyValue.create(propertyName, argument.getBytes());
}
}
Collection targets = new ArrayList();
if (getSVNEnvironment().getTargets() != null) {
targets.addAll(getSVNEnvironment().getTargets());
}
targets = getSVNEnvironment().combineTargets(targets, true);
if (getSVNEnvironment().isRevprop()) {
if (targets.isEmpty()) {
targets.add("");
}
SVNURL revPropURL = getRevpropURL(getSVNEnvironment().getStartRevision(), targets);
getSVNEnvironment().getClientManager().getWCClient().doSetRevisionProperty(revPropURL, getSVNEnvironment().getStartRevision(),
propertyName, propertyValue, getSVNEnvironment().isForce(), this);
} else if (getSVNEnvironment().getStartRevision() != SVNRevision.UNDEFINED) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Cannot specify revision for setting versioned property ''{0}''", propertyName);
SVNErrorManager.error(err, SVNLogType.CLIENT);
} else {
SVNDepth depth = getSVNEnvironment().getDepth();
if (depth == SVNDepth.UNKNOWN) {
depth = SVNDepth.EMPTY;
}
if (targets.isEmpty()) {
if (getSVNEnvironment().getFileData() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS,
"Explicit target required (''{0}'' interpreted as prop value)", propertyValue);
SVNErrorManager.error(err, SVNLogType.CLIENT);
} else {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Explicit target argument required");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
Collection changeLists = getSVNEnvironment().getChangelistsCollection();
SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient();
for (Iterator ts = targets.iterator(); ts.hasNext();) {
String targetName = (String) ts.next();
SVNPath target = new SVNPath(targetName);
if (target.isFile()) {
boolean success = true;
try {
if (target.isFile()) {
client.doSetProperty(target.getFile(), propertyName, propertyValue,
getSVNEnvironment().isForce(), depth, this, changeLists);
} else {
client.setCommitHandler(getSVNEnvironment());
client.doSetProperty(target.getURL(), propertyName, propertyValue, SVNRevision.HEAD, getSVNEnvironment().getMessage(),
getSVNEnvironment().getRevisionProperties(), getSVNEnvironment().isForce(), this);
}
} catch (SVNException e) {
success = getSVNEnvironment().handleWarning(e.getErrorMessage(),
new SVNErrorCode[]{SVNErrorCode.UNVERSIONED_RESOURCE, SVNErrorCode.ENTRY_NOT_FOUND},
getSVNEnvironment().isQuiet());
}
clearCollectedProperties();
if (!getSVNEnvironment().isQuiet()) {
checkBooleanProperty(propertyName, propertyValue);
if (success) {
String path = SVNCommandUtil.getLocalPath(targetName);
String message = depth.isRecursive() ?
"property ''{0}'' set (recursively) on ''{1}''" :
"property ''{0}'' set on ''{1}''";
message = MessageFormat.format(message, new Object[]{propertyName, path});
getSVNEnvironment().getOut().println(message);
}
}
}
}
}
}
public void handleProperty(long revision, SVNPropertyData property) throws SVNException {
super.handleProperty(revision, property);
if (!getSVNEnvironment().isQuiet()) {
String message = "property ''{0}'' set on repository revision {1}";
message = MessageFormat.format(message, new Object[]{property.getName(), new Long(revision)});
getSVNEnvironment().getOut().println(message);
}
}
}
| false | true | public void run() throws SVNException {
String propertyName = getSVNEnvironment().popArgument();
if (propertyName == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS);
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (!SVNPropertiesManager.isValidPropertyName(propertyName)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME,
"''{0}'' is not a valid Subversion property name", propertyName);
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
String encoding = null;
if (SVNPropertiesManager.propNeedsTranslation(propertyName)) {
encoding = getSVNEnvironment().getEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
} else {
if (getSVNEnvironment().getEncoding() != null) {
SVNErrorMessage errorMessage = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE,
"Bad encoding option: prop value not stored as UTF8");
SVNErrorManager.error(errorMessage, SVNLogType.CLIENT);
}
}
SVNPropertyValue propertyValue = null;
if (encoding != null) {
if (getSVNEnvironment().getFileData() != null) {
String stringValue = null;
try {
stringValue = new String(getSVNEnvironment().getFileData(), encoding);
} catch (UnsupportedEncodingException e) {
stringValue = new String(getSVNEnvironment().getFileData());
}
propertyValue = SVNPropertyValue.create(stringValue);
} else {
propertyValue = SVNPropertyValue.create(getSVNEnvironment().popArgument());
}
} else {
if (getSVNEnvironment().getFileData() != null) {
propertyValue = SVNPropertyValue.create(propertyName, getSVNEnvironment().getFileData());
} else {
propertyValue = SVNPropertyValue.create(propertyName, getSVNEnvironment().popArgument().getBytes());
}
}
Collection targets = new ArrayList();
if (getSVNEnvironment().getTargets() != null) {
targets.addAll(getSVNEnvironment().getTargets());
}
targets = getSVNEnvironment().combineTargets(targets, true);
if (getSVNEnvironment().isRevprop()) {
if (targets.isEmpty()) {
targets.add("");
}
SVNURL revPropURL = getRevpropURL(getSVNEnvironment().getStartRevision(), targets);
getSVNEnvironment().getClientManager().getWCClient().doSetRevisionProperty(revPropURL, getSVNEnvironment().getStartRevision(),
propertyName, propertyValue, getSVNEnvironment().isForce(), this);
} else if (getSVNEnvironment().getStartRevision() != SVNRevision.UNDEFINED) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Cannot specify revision for setting versioned property ''{0}''", propertyName);
SVNErrorManager.error(err, SVNLogType.CLIENT);
} else {
SVNDepth depth = getSVNEnvironment().getDepth();
if (depth == SVNDepth.UNKNOWN) {
depth = SVNDepth.EMPTY;
}
if (targets.isEmpty()) {
if (getSVNEnvironment().getFileData() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS,
"Explicit target required (''{0}'' interpreted as prop value)", propertyValue);
SVNErrorManager.error(err, SVNLogType.CLIENT);
} else {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Explicit target argument required");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
Collection changeLists = getSVNEnvironment().getChangelistsCollection();
SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient();
for (Iterator ts = targets.iterator(); ts.hasNext();) {
String targetName = (String) ts.next();
SVNPath target = new SVNPath(targetName);
if (target.isFile()) {
boolean success = true;
try {
if (target.isFile()) {
client.doSetProperty(target.getFile(), propertyName, propertyValue,
getSVNEnvironment().isForce(), depth, this, changeLists);
} else {
client.setCommitHandler(getSVNEnvironment());
client.doSetProperty(target.getURL(), propertyName, propertyValue, SVNRevision.HEAD, getSVNEnvironment().getMessage(),
getSVNEnvironment().getRevisionProperties(), getSVNEnvironment().isForce(), this);
}
} catch (SVNException e) {
success = getSVNEnvironment().handleWarning(e.getErrorMessage(),
new SVNErrorCode[]{SVNErrorCode.UNVERSIONED_RESOURCE, SVNErrorCode.ENTRY_NOT_FOUND},
getSVNEnvironment().isQuiet());
}
clearCollectedProperties();
if (!getSVNEnvironment().isQuiet()) {
checkBooleanProperty(propertyName, propertyValue);
if (success) {
String path = SVNCommandUtil.getLocalPath(targetName);
String message = depth.isRecursive() ?
"property ''{0}'' set (recursively) on ''{1}''" :
"property ''{0}'' set on ''{1}''";
message = MessageFormat.format(message, new Object[]{propertyName, path});
getSVNEnvironment().getOut().println(message);
}
}
}
}
}
}
| public void run() throws SVNException {
String propertyName = getSVNEnvironment().popArgument();
if (propertyName == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS);
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
if (!SVNPropertiesManager.isValidPropertyName(propertyName)) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CLIENT_PROPERTY_NAME,
"''{0}'' is not a valid Subversion property name", propertyName);
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
String encoding = null;
if (SVNPropertiesManager.propNeedsTranslation(propertyName)) {
encoding = getSVNEnvironment().getEncoding();
if (encoding == null) {
encoding = "UTF-8";
}
} else {
if (getSVNEnvironment().getEncoding() != null) {
SVNErrorMessage errorMessage = SVNErrorMessage.create(SVNErrorCode.UNSUPPORTED_FEATURE,
"Bad encoding option: prop value not stored as UTF8");
SVNErrorManager.error(errorMessage, SVNLogType.CLIENT);
}
}
SVNPropertyValue propertyValue = null;
if (encoding != null) {
if (getSVNEnvironment().getFileData() != null) {
String stringValue = null;
try {
stringValue = new String(getSVNEnvironment().getFileData(), encoding);
} catch (UnsupportedEncodingException e) {
stringValue = new String(getSVNEnvironment().getFileData());
}
propertyValue = SVNPropertyValue.create(stringValue);
} else {
String argument = getSVNEnvironment().popArgument();
if (argument == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS);
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
propertyValue = SVNPropertyValue.create(argument);
}
} else {
if (getSVNEnvironment().getFileData() != null) {
propertyValue = SVNPropertyValue.create(propertyName, getSVNEnvironment().getFileData());
} else {
String argument = getSVNEnvironment().popArgument();
if (argument == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS);
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
propertyValue = SVNPropertyValue.create(propertyName, argument.getBytes());
}
}
Collection targets = new ArrayList();
if (getSVNEnvironment().getTargets() != null) {
targets.addAll(getSVNEnvironment().getTargets());
}
targets = getSVNEnvironment().combineTargets(targets, true);
if (getSVNEnvironment().isRevprop()) {
if (targets.isEmpty()) {
targets.add("");
}
SVNURL revPropURL = getRevpropURL(getSVNEnvironment().getStartRevision(), targets);
getSVNEnvironment().getClientManager().getWCClient().doSetRevisionProperty(revPropURL, getSVNEnvironment().getStartRevision(),
propertyName, propertyValue, getSVNEnvironment().isForce(), this);
} else if (getSVNEnvironment().getStartRevision() != SVNRevision.UNDEFINED) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_ARG_PARSING_ERROR,
"Cannot specify revision for setting versioned property ''{0}''", propertyName);
SVNErrorManager.error(err, SVNLogType.CLIENT);
} else {
SVNDepth depth = getSVNEnvironment().getDepth();
if (depth == SVNDepth.UNKNOWN) {
depth = SVNDepth.EMPTY;
}
if (targets.isEmpty()) {
if (getSVNEnvironment().getFileData() == null) {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS,
"Explicit target required (''{0}'' interpreted as prop value)", propertyValue);
SVNErrorManager.error(err, SVNLogType.CLIENT);
} else {
SVNErrorMessage err = SVNErrorMessage.create(SVNErrorCode.CL_INSUFFICIENT_ARGS, "Explicit target argument required");
SVNErrorManager.error(err, SVNLogType.CLIENT);
}
}
Collection changeLists = getSVNEnvironment().getChangelistsCollection();
SVNWCClient client = getSVNEnvironment().getClientManager().getWCClient();
for (Iterator ts = targets.iterator(); ts.hasNext();) {
String targetName = (String) ts.next();
SVNPath target = new SVNPath(targetName);
if (target.isFile()) {
boolean success = true;
try {
if (target.isFile()) {
client.doSetProperty(target.getFile(), propertyName, propertyValue,
getSVNEnvironment().isForce(), depth, this, changeLists);
} else {
client.setCommitHandler(getSVNEnvironment());
client.doSetProperty(target.getURL(), propertyName, propertyValue, SVNRevision.HEAD, getSVNEnvironment().getMessage(),
getSVNEnvironment().getRevisionProperties(), getSVNEnvironment().isForce(), this);
}
} catch (SVNException e) {
success = getSVNEnvironment().handleWarning(e.getErrorMessage(),
new SVNErrorCode[]{SVNErrorCode.UNVERSIONED_RESOURCE, SVNErrorCode.ENTRY_NOT_FOUND},
getSVNEnvironment().isQuiet());
}
clearCollectedProperties();
if (!getSVNEnvironment().isQuiet()) {
checkBooleanProperty(propertyName, propertyValue);
if (success) {
String path = SVNCommandUtil.getLocalPath(targetName);
String message = depth.isRecursive() ?
"property ''{0}'' set (recursively) on ''{1}''" :
"property ''{0}'' set on ''{1}''";
message = MessageFormat.format(message, new Object[]{propertyName, path});
getSVNEnvironment().getOut().println(message);
}
}
}
}
}
}
|
diff --git a/JamJam/src/com/touchlabs/jamjam/GameModel.java b/JamJam/src/com/touchlabs/jamjam/GameModel.java
index 796a85b..574bf32 100644
--- a/JamJam/src/com/touchlabs/jamjam/GameModel.java
+++ b/JamJam/src/com/touchlabs/jamjam/GameModel.java
@@ -1,277 +1,277 @@
package com.touchlabs.jamjam;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import android.content.Context;
import android.content.SharedPreferences;
public class GameModel implements java.io.Serializable {
private static final long serialVersionUID = 1L;
private GroundTop groundTop;
private GroundMid groundMid;
private GroundBot groundBot;
//private EnemyWall enemyWall;
private Dront mDront;
private PowerUp mPowerUp;
private List<EnemyWall> listEnemyWall = new ArrayList<EnemyWall>();
private Background mBg;
private boolean lost = false;
private float incSpeedTimer = 5; //each 10 sec increase the globalGameSpeed
private double globalGameSpeed = 100;
private int distance = 0;
private double distanceMeter = 1;
private double timeTick = 0;
private Context context;
private SoundManager mSoundManager;
/**
* Constructor
*/
public GameModel(SoundManager sm) {
mSoundManager = sm;
groundTop = new GroundTop();
groundMid = new GroundMid();
groundBot = new GroundBot();
mDront = new Dront();
mPowerUp = new PowerUp();
mBg = new Background();
Random generator = new Random();
for(int i = 0; i < 6; i++){
if (i == 0 || i == 1)
listEnemyWall.add(new EnemyWall((generator.nextInt(9) + 1), 1));
if (i == 2 || i == 3)
listEnemyWall.add(new EnemyWall((generator.nextInt(9) + 1), 2));
if (i == 4 || i == 5)
listEnemyWall.add(new EnemyWall((generator.nextInt(9) + 1), 3));
}
}
/**
* Initializes all variables of the GameModel.
*/
public void initialize(Context context) {
this.context = context;
}
/**
* This class is called from the GameThread.
* @param timeDelta
*/
public void updateModel(float timeDelta) {
if(!lost){
groundTop.setXPos(timeDelta);
groundMid.setXPos(timeDelta);
groundBot.setXPos(timeDelta);
mDront.updateDront(timeDelta);
mPowerUp.updatePowerUp(timeDelta);
mBg.setXPos(timeDelta);
int count = listEnemyWall.size();
if(mDront.getX() + 80 > mPowerUp.getX() && mDront.getX() < mPowerUp.getX()){
if(mDront.getY() + 80 > mPowerUp.getY() && mDront.getY() < mPowerUp.getY() +80){
if (mPowerUp.getType() == 0){
mDront.drontPowerUp();
distance += 1;
mSoundManager.playSound(2);
}
else if (mPowerUp.getType() == 1) {
globalGameSpeed *= 0.5;
mDront.setAnimationWalk(1.5f);
//Update speed for all
//Update speed for walls
for(int i = 0; i < count; i++){
listEnemyWall.get(i).setSpeed(globalGameSpeed);
}
groundTop.setSpeed(globalGameSpeed);
groundMid.setSpeed(globalGameSpeed);
groundBot.setSpeed(globalGameSpeed);
mPowerUp.setSpeed(globalGameSpeed);
mSoundManager.playSound(4);
}
else if (mPowerUp.getType() == 2) {
mDront.frontFreeze();
mSoundManager.playSound(3);
}
mPowerUp.updatePowerUp(600);
}
}
timeTick -= timeDelta;
boolean showWall = false;
if (timeTick <= 0) {
- timeTick = 1;
+ timeTick = 1.5;
showWall = true;
}
int y1 = 0;
int y2 = 0;
int y3 = 0;
for(int i = 0; i < count; i++){
if (i == 0) {
boolean temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y1 = 1;
}
if (i == 1) {
boolean temp = false;
if (y1 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y1 = 1;
}
}
if (i == 2) {
boolean temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y2 = 1;
}
if (i == 3) {
boolean temp = false;
if (y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y2 = 1;
}
}
if (i == 4) {
boolean temp = false;
if (y1 == 1 && y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y3 = 1;
}
if (i == 5) {
boolean temp = false;
if (y3 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
if (y1 == 1 && y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y3 = 1;
}
}
}
showWall = false;
incSpeedTimer -= timeDelta;
if(incSpeedTimer < 0){
globalGameSpeed *= 1.1;
mDront.setAnimationWalk(0.9f);
//Update speed for all
//Update speed for walls
for(int i = 0; i < count; i++){
listEnemyWall.get(i).setSpeed(globalGameSpeed);
}
groundTop.setSpeed(globalGameSpeed);
groundMid.setSpeed(globalGameSpeed);
groundBot.setSpeed(globalGameSpeed);
mPowerUp.setSpeed(globalGameSpeed);
incSpeedTimer = 5;
}
//Score in distance
distanceMeter += timeDelta * globalGameSpeed * 0.01;
if(distanceMeter > 2){
distance += 1;
distanceMeter = 1;
}
for(int i = 0; i < count; i++){
if(mDront.getX() + 80 > listEnemyWall.get(i).getX1() && mDront.getX() < listEnemyWall.get(i).getX1()){
if(mDront.getY() + 80 > listEnemyWall.get(i).getY() && mDront.getY() < listEnemyWall.get(i).getY() +80){
mDront.hitDront();
mSoundManager.playSound(1);
distance -= 1;
listEnemyWall.get(i).setNewRandomTime();
}
}
}
//Lost?
if(mDront.getX() == 0){
lost = true;
}
}
}
public Background getBackgroun(){
return mBg;
}
public int getDistance(){
return distance;
}
public boolean getLost(){
return lost;
}
//Return the dront
public Dront getDront() {
return mDront;
}
//Return the powerup
public PowerUp getPowerUp() {
return mPowerUp;
}
public GroundTop getGroundTop(){
return groundTop;
}
public GroundMid getGroundMid(){
return groundMid;
}
public GroundBot getGroundBot(){
return groundBot;
}
public List<EnemyWall> getListEnemyWall(){
return listEnemyWall;
}
public void release() {
// TODO Auto-generated method stub
}
}
| true | true | public void updateModel(float timeDelta) {
if(!lost){
groundTop.setXPos(timeDelta);
groundMid.setXPos(timeDelta);
groundBot.setXPos(timeDelta);
mDront.updateDront(timeDelta);
mPowerUp.updatePowerUp(timeDelta);
mBg.setXPos(timeDelta);
int count = listEnemyWall.size();
if(mDront.getX() + 80 > mPowerUp.getX() && mDront.getX() < mPowerUp.getX()){
if(mDront.getY() + 80 > mPowerUp.getY() && mDront.getY() < mPowerUp.getY() +80){
if (mPowerUp.getType() == 0){
mDront.drontPowerUp();
distance += 1;
mSoundManager.playSound(2);
}
else if (mPowerUp.getType() == 1) {
globalGameSpeed *= 0.5;
mDront.setAnimationWalk(1.5f);
//Update speed for all
//Update speed for walls
for(int i = 0; i < count; i++){
listEnemyWall.get(i).setSpeed(globalGameSpeed);
}
groundTop.setSpeed(globalGameSpeed);
groundMid.setSpeed(globalGameSpeed);
groundBot.setSpeed(globalGameSpeed);
mPowerUp.setSpeed(globalGameSpeed);
mSoundManager.playSound(4);
}
else if (mPowerUp.getType() == 2) {
mDront.frontFreeze();
mSoundManager.playSound(3);
}
mPowerUp.updatePowerUp(600);
}
}
timeTick -= timeDelta;
boolean showWall = false;
if (timeTick <= 0) {
timeTick = 1;
showWall = true;
}
int y1 = 0;
int y2 = 0;
int y3 = 0;
for(int i = 0; i < count; i++){
if (i == 0) {
boolean temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y1 = 1;
}
if (i == 1) {
boolean temp = false;
if (y1 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y1 = 1;
}
}
if (i == 2) {
boolean temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y2 = 1;
}
if (i == 3) {
boolean temp = false;
if (y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y2 = 1;
}
}
if (i == 4) {
boolean temp = false;
if (y1 == 1 && y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y3 = 1;
}
if (i == 5) {
boolean temp = false;
if (y3 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
if (y1 == 1 && y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y3 = 1;
}
}
}
showWall = false;
incSpeedTimer -= timeDelta;
if(incSpeedTimer < 0){
globalGameSpeed *= 1.1;
mDront.setAnimationWalk(0.9f);
//Update speed for all
//Update speed for walls
for(int i = 0; i < count; i++){
listEnemyWall.get(i).setSpeed(globalGameSpeed);
}
groundTop.setSpeed(globalGameSpeed);
groundMid.setSpeed(globalGameSpeed);
groundBot.setSpeed(globalGameSpeed);
mPowerUp.setSpeed(globalGameSpeed);
incSpeedTimer = 5;
}
//Score in distance
distanceMeter += timeDelta * globalGameSpeed * 0.01;
if(distanceMeter > 2){
distance += 1;
distanceMeter = 1;
}
for(int i = 0; i < count; i++){
if(mDront.getX() + 80 > listEnemyWall.get(i).getX1() && mDront.getX() < listEnemyWall.get(i).getX1()){
if(mDront.getY() + 80 > listEnemyWall.get(i).getY() && mDront.getY() < listEnemyWall.get(i).getY() +80){
mDront.hitDront();
mSoundManager.playSound(1);
distance -= 1;
listEnemyWall.get(i).setNewRandomTime();
}
}
}
//Lost?
if(mDront.getX() == 0){
lost = true;
}
}
}
| public void updateModel(float timeDelta) {
if(!lost){
groundTop.setXPos(timeDelta);
groundMid.setXPos(timeDelta);
groundBot.setXPos(timeDelta);
mDront.updateDront(timeDelta);
mPowerUp.updatePowerUp(timeDelta);
mBg.setXPos(timeDelta);
int count = listEnemyWall.size();
if(mDront.getX() + 80 > mPowerUp.getX() && mDront.getX() < mPowerUp.getX()){
if(mDront.getY() + 80 > mPowerUp.getY() && mDront.getY() < mPowerUp.getY() +80){
if (mPowerUp.getType() == 0){
mDront.drontPowerUp();
distance += 1;
mSoundManager.playSound(2);
}
else if (mPowerUp.getType() == 1) {
globalGameSpeed *= 0.5;
mDront.setAnimationWalk(1.5f);
//Update speed for all
//Update speed for walls
for(int i = 0; i < count; i++){
listEnemyWall.get(i).setSpeed(globalGameSpeed);
}
groundTop.setSpeed(globalGameSpeed);
groundMid.setSpeed(globalGameSpeed);
groundBot.setSpeed(globalGameSpeed);
mPowerUp.setSpeed(globalGameSpeed);
mSoundManager.playSound(4);
}
else if (mPowerUp.getType() == 2) {
mDront.frontFreeze();
mSoundManager.playSound(3);
}
mPowerUp.updatePowerUp(600);
}
}
timeTick -= timeDelta;
boolean showWall = false;
if (timeTick <= 0) {
timeTick = 1.5;
showWall = true;
}
int y1 = 0;
int y2 = 0;
int y3 = 0;
for(int i = 0; i < count; i++){
if (i == 0) {
boolean temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y1 = 1;
}
if (i == 1) {
boolean temp = false;
if (y1 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y1 = 1;
}
}
if (i == 2) {
boolean temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y2 = 1;
}
if (i == 3) {
boolean temp = false;
if (y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y2 = 1;
}
}
if (i == 4) {
boolean temp = false;
if (y1 == 1 && y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y3 = 1;
}
if (i == 5) {
boolean temp = false;
if (y3 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else {
if (y1 == 1 && y2 == 1)
temp = listEnemyWall.get(i).updateWall(timeDelta,false);
else
temp = listEnemyWall.get(i).updateWall(timeDelta,showWall);
if (temp)
y3 = 1;
}
}
}
showWall = false;
incSpeedTimer -= timeDelta;
if(incSpeedTimer < 0){
globalGameSpeed *= 1.1;
mDront.setAnimationWalk(0.9f);
//Update speed for all
//Update speed for walls
for(int i = 0; i < count; i++){
listEnemyWall.get(i).setSpeed(globalGameSpeed);
}
groundTop.setSpeed(globalGameSpeed);
groundMid.setSpeed(globalGameSpeed);
groundBot.setSpeed(globalGameSpeed);
mPowerUp.setSpeed(globalGameSpeed);
incSpeedTimer = 5;
}
//Score in distance
distanceMeter += timeDelta * globalGameSpeed * 0.01;
if(distanceMeter > 2){
distance += 1;
distanceMeter = 1;
}
for(int i = 0; i < count; i++){
if(mDront.getX() + 80 > listEnemyWall.get(i).getX1() && mDront.getX() < listEnemyWall.get(i).getX1()){
if(mDront.getY() + 80 > listEnemyWall.get(i).getY() && mDront.getY() < listEnemyWall.get(i).getY() +80){
mDront.hitDront();
mSoundManager.playSound(1);
distance -= 1;
listEnemyWall.get(i).setNewRandomTime();
}
}
}
//Lost?
if(mDront.getX() == 0){
lost = true;
}
}
}
|
diff --git a/core/src/main/java/dagger/internal/FailoverLoader.java b/core/src/main/java/dagger/internal/FailoverLoader.java
index 52f923ee..4b14af25 100644
--- a/core/src/main/java/dagger/internal/FailoverLoader.java
+++ b/core/src/main/java/dagger/internal/FailoverLoader.java
@@ -1,72 +1,72 @@
/*
* Copyright (C) 2013 Square, Inc.
* Copyright (C) 2013 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 dagger.internal;
import dagger.internal.loaders.GeneratedAdapters;
import dagger.internal.loaders.ReflectiveAtInjectBinding;
import dagger.internal.loaders.ReflectiveStaticInjection;
/**
* Handles loading/finding of modules, injection bindings, and static injections by use of a
* strategy of "load the appropriate generated code" or, if no such code is found, create a
* reflective equivalent.
*/
public final class FailoverLoader implements Loader {
/**
* Obtains a module adapter for {@code module} from the first responding resolver.
*/
@Override public <T> ModuleAdapter<T> getModuleAdapter(Class<? extends T> type, T instance) {
ModuleAdapter<T> result = null;
try {
result = GeneratedAdapters.initModuleAdapter(type);
} catch (ClassNotFoundException e) {
throw new TypeNotPresentException(type + GeneratedAdapters.MODULE_ADAPTER_SUFFIX, e);
}
result.module = (instance != null) ? instance : result.newModule();
return result;
}
@Override public Binding<?> getAtInjectBinding(String key, String className,
ClassLoader classLoader, boolean mustHaveInjections) {
try {
return GeneratedAdapters.initInjectAdapter(className, classLoader);
} catch (ClassNotFoundException ignored /* failover case */) {
try {
// A null classloader is the system classloader.
classLoader = (classLoader != null) ? classLoader : ClassLoader.getSystemClassLoader();
Class<?> type = classLoader.loadClass(className);
- if (!type.isInterface()) {
+ if (type.isInterface()) {
return null; // Short-circuit since we can't build reflective bindings for interfaces.
}
return ReflectiveAtInjectBinding.create(type, mustHaveInjections);
} catch (ClassNotFoundException e) {
throw new TypeNotPresentException(
String.format("Could not find %s needed for binding %s", className, key), e);
}
}
}
@Override public StaticInjection getStaticInjection(Class<?> injectedClass) {
try {
return GeneratedAdapters.initStaticInjection(injectedClass);
} catch (ClassNotFoundException ignored) {
return ReflectiveStaticInjection.create(injectedClass);
}
}
}
| true | true | @Override public Binding<?> getAtInjectBinding(String key, String className,
ClassLoader classLoader, boolean mustHaveInjections) {
try {
return GeneratedAdapters.initInjectAdapter(className, classLoader);
} catch (ClassNotFoundException ignored /* failover case */) {
try {
// A null classloader is the system classloader.
classLoader = (classLoader != null) ? classLoader : ClassLoader.getSystemClassLoader();
Class<?> type = classLoader.loadClass(className);
if (!type.isInterface()) {
return null; // Short-circuit since we can't build reflective bindings for interfaces.
}
return ReflectiveAtInjectBinding.create(type, mustHaveInjections);
} catch (ClassNotFoundException e) {
throw new TypeNotPresentException(
String.format("Could not find %s needed for binding %s", className, key), e);
}
}
}
| @Override public Binding<?> getAtInjectBinding(String key, String className,
ClassLoader classLoader, boolean mustHaveInjections) {
try {
return GeneratedAdapters.initInjectAdapter(className, classLoader);
} catch (ClassNotFoundException ignored /* failover case */) {
try {
// A null classloader is the system classloader.
classLoader = (classLoader != null) ? classLoader : ClassLoader.getSystemClassLoader();
Class<?> type = classLoader.loadClass(className);
if (type.isInterface()) {
return null; // Short-circuit since we can't build reflective bindings for interfaces.
}
return ReflectiveAtInjectBinding.create(type, mustHaveInjections);
} catch (ClassNotFoundException e) {
throw new TypeNotPresentException(
String.format("Could not find %s needed for binding %s", className, key), e);
}
}
}
|
diff --git a/examples/org.eclipse.gmf.examples.eclipsecon.diagram.custom/src/org/eclipse/gmf/examples/eclipsecon/diagram/custom/editparts/BetterLookingPresenterEditPart.java b/examples/org.eclipse.gmf.examples.eclipsecon.diagram.custom/src/org/eclipse/gmf/examples/eclipsecon/diagram/custom/editparts/BetterLookingPresenterEditPart.java
index 66fc49d83..01c5d2afb 100644
--- a/examples/org.eclipse.gmf.examples.eclipsecon.diagram.custom/src/org/eclipse/gmf/examples/eclipsecon/diagram/custom/editparts/BetterLookingPresenterEditPart.java
+++ b/examples/org.eclipse.gmf.examples.eclipsecon.diagram.custom/src/org/eclipse/gmf/examples/eclipsecon/diagram/custom/editparts/BetterLookingPresenterEditPart.java
@@ -1,115 +1,115 @@
package org.eclipse.gmf.examples.eclipsecon.diagram.custom.editparts;
import java.net.MalformedURLException;
import java.net.URL;
import org.eclipse.core.runtime.FileLocator;
import org.eclipse.core.runtime.IPath;
import org.eclipse.core.runtime.Path;
import org.eclipse.draw2d.BorderLayout;
import org.eclipse.draw2d.ConnectionAnchor;
import org.eclipse.draw2d.Figure;
import org.eclipse.draw2d.IFigure;
import org.eclipse.draw2d.geometry.PrecisionPoint;
import org.eclipse.emf.common.notify.Notification;
import org.eclipse.gmf.examples.eclipsecon.diagram.custom.Activator;
import org.eclipse.gmf.examples.eclipsecon.diagram.custom.styles.PresenterStyle;
import org.eclipse.gmf.examples.eclipsecon.diagram.custom.styles.StylesPackage;
import org.eclipse.gmf.examples.eclipsecon.diagram.edit.parts.PresenterEditPart;
import org.eclipse.gmf.runtime.draw2d.ui.figures.ConstrainedToolbarLayout;
import org.eclipse.gmf.runtime.draw2d.ui.render.RenderedImage;
import org.eclipse.gmf.runtime.draw2d.ui.render.factory.RenderedImageFactory;
import org.eclipse.gmf.runtime.draw2d.ui.render.figures.ScalableImageFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure;
import org.eclipse.gmf.runtime.gef.ui.figures.SlidableImageAnchor;
import org.eclipse.gmf.runtime.gef.ui.figures.WrapperNodeFigure;
import org.eclipse.gmf.runtime.notation.View;
public class BetterLookingPresenterEditPart extends PresenterEditPart {
public BetterLookingPresenterEditPart(View view) {
super(view);
// TODO Auto-generated constructor stub
}
private static final String TRANSLATE_PATH_ARGUMENT = "$nl$"; //$NON-NLS-1$
/*
* (non-Javadoc)
* @see org.eclipse.gmf.examples.eclipsecon.diagram.edit.parts.PresenterEditPart#createNodeFigure()
*/
protected NodeFigure createNodeFigure() {
// determine which figure to create - first check for default display
PresenterStyle presenterStyle = (PresenterStyle)getNotationView().getStyle(StylesPackage.eINSTANCE.getPresenterStyle());
if (presenterStyle == null || presenterStyle.getDisplayAsDefault().booleanValue())
return super.createNodeFigure();
// check for URL string
URL presenterURL = null;
try {
URL imageURL = new URL(presenterStyle.getImageURL());
presenterURL = imageURL;
} catch (MalformedURLException e) {
// assume default;
IPath path =
new Path(TRANSLATE_PATH_ARGUMENT).append(
"images" + IPath.SEPARATOR + "presenter.svg"); //$NON-NLS-1$ //$NON-NLS-2$
presenterURL = FileLocator.find(Activator.getDefault().getBundle(), path, null);
}
RenderedImage rndImg = RenderedImageFactory.getInstance(presenterURL);
final ScalableImageFigure sif = new ScalableImageFigure(rndImg, false, true, true);
NodeFigure nf = new WrapperNodeFigure(sif) {
/* (non-Javadoc)
* @see org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure#createDefaultAnchor()
*/
protected ConnectionAnchor createDefaultAnchor() {
return new SlidableImageAnchor(this, sif);
}
/* (non-Javadoc)
* @see org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure#createAnchor(org.eclipse.draw2d.geometry.PrecisionPoint)
*/
protected ConnectionAnchor createAnchor(PrecisionPoint p) {
if (p==null)
// If the old terminal for the connection anchor cannot be resolved (by SlidableAnchor) a null
// PrecisionPoint will passed in - this is handled here
return createDefaultAnchor();
return new SlidableImageAnchor(this, sif, p);
}
};
ConstrainedToolbarLayout myGenLayoutManager = new ConstrainedToolbarLayout();
myGenLayoutManager.setStretchMinorAxis(false);
myGenLayoutManager
.setMinorAlignment(org.eclipse.draw2d.ToolbarLayout.ALIGN_TOPLEFT);
myGenLayoutManager.setSpacing(5);
myGenLayoutManager.setVertical(true);
nf.setLayoutManager(myGenLayoutManager);
IFigure pane = new Figure();
pane.setOpaque(false);
pane.setLayoutManager(new BorderLayout());
nf.add(pane);
- addContentPane(pane);
+ setupContentPane(pane);
return nf;
}
/**
* @see org.eclipse.gmf.runtime.diagram.ui.editparts.GraphicalEditPart#handlePropertyChangeEvent(java.beans.PropertyChangeEvent)
*/
protected void handleNotificationEvent(Notification notification) {
Object feature = notification.getFeature();
if (StylesPackage.eINSTANCE.getPresenterStyle_DisplayAsDefault().equals(feature) ||
StylesPackage.eINSTANCE.getPresenterStyle_ImageURL().equals(feature))
handleMajorSemanticChange();
else
super.handleNotificationEvent(notification);
}
}
| true | true | protected NodeFigure createNodeFigure() {
// determine which figure to create - first check for default display
PresenterStyle presenterStyle = (PresenterStyle)getNotationView().getStyle(StylesPackage.eINSTANCE.getPresenterStyle());
if (presenterStyle == null || presenterStyle.getDisplayAsDefault().booleanValue())
return super.createNodeFigure();
// check for URL string
URL presenterURL = null;
try {
URL imageURL = new URL(presenterStyle.getImageURL());
presenterURL = imageURL;
} catch (MalformedURLException e) {
// assume default;
IPath path =
new Path(TRANSLATE_PATH_ARGUMENT).append(
"images" + IPath.SEPARATOR + "presenter.svg"); //$NON-NLS-1$ //$NON-NLS-2$
presenterURL = FileLocator.find(Activator.getDefault().getBundle(), path, null);
}
RenderedImage rndImg = RenderedImageFactory.getInstance(presenterURL);
final ScalableImageFigure sif = new ScalableImageFigure(rndImg, false, true, true);
NodeFigure nf = new WrapperNodeFigure(sif) {
/* (non-Javadoc)
* @see org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure#createDefaultAnchor()
*/
protected ConnectionAnchor createDefaultAnchor() {
return new SlidableImageAnchor(this, sif);
}
/* (non-Javadoc)
* @see org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure#createAnchor(org.eclipse.draw2d.geometry.PrecisionPoint)
*/
protected ConnectionAnchor createAnchor(PrecisionPoint p) {
if (p==null)
// If the old terminal for the connection anchor cannot be resolved (by SlidableAnchor) a null
// PrecisionPoint will passed in - this is handled here
return createDefaultAnchor();
return new SlidableImageAnchor(this, sif, p);
}
};
ConstrainedToolbarLayout myGenLayoutManager = new ConstrainedToolbarLayout();
myGenLayoutManager.setStretchMinorAxis(false);
myGenLayoutManager
.setMinorAlignment(org.eclipse.draw2d.ToolbarLayout.ALIGN_TOPLEFT);
myGenLayoutManager.setSpacing(5);
myGenLayoutManager.setVertical(true);
nf.setLayoutManager(myGenLayoutManager);
IFigure pane = new Figure();
pane.setOpaque(false);
pane.setLayoutManager(new BorderLayout());
nf.add(pane);
addContentPane(pane);
return nf;
}
| protected NodeFigure createNodeFigure() {
// determine which figure to create - first check for default display
PresenterStyle presenterStyle = (PresenterStyle)getNotationView().getStyle(StylesPackage.eINSTANCE.getPresenterStyle());
if (presenterStyle == null || presenterStyle.getDisplayAsDefault().booleanValue())
return super.createNodeFigure();
// check for URL string
URL presenterURL = null;
try {
URL imageURL = new URL(presenterStyle.getImageURL());
presenterURL = imageURL;
} catch (MalformedURLException e) {
// assume default;
IPath path =
new Path(TRANSLATE_PATH_ARGUMENT).append(
"images" + IPath.SEPARATOR + "presenter.svg"); //$NON-NLS-1$ //$NON-NLS-2$
presenterURL = FileLocator.find(Activator.getDefault().getBundle(), path, null);
}
RenderedImage rndImg = RenderedImageFactory.getInstance(presenterURL);
final ScalableImageFigure sif = new ScalableImageFigure(rndImg, false, true, true);
NodeFigure nf = new WrapperNodeFigure(sif) {
/* (non-Javadoc)
* @see org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure#createDefaultAnchor()
*/
protected ConnectionAnchor createDefaultAnchor() {
return new SlidableImageAnchor(this, sif);
}
/* (non-Javadoc)
* @see org.eclipse.gmf.runtime.gef.ui.figures.NodeFigure#createAnchor(org.eclipse.draw2d.geometry.PrecisionPoint)
*/
protected ConnectionAnchor createAnchor(PrecisionPoint p) {
if (p==null)
// If the old terminal for the connection anchor cannot be resolved (by SlidableAnchor) a null
// PrecisionPoint will passed in - this is handled here
return createDefaultAnchor();
return new SlidableImageAnchor(this, sif, p);
}
};
ConstrainedToolbarLayout myGenLayoutManager = new ConstrainedToolbarLayout();
myGenLayoutManager.setStretchMinorAxis(false);
myGenLayoutManager
.setMinorAlignment(org.eclipse.draw2d.ToolbarLayout.ALIGN_TOPLEFT);
myGenLayoutManager.setSpacing(5);
myGenLayoutManager.setVertical(true);
nf.setLayoutManager(myGenLayoutManager);
IFigure pane = new Figure();
pane.setOpaque(false);
pane.setLayoutManager(new BorderLayout());
nf.add(pane);
setupContentPane(pane);
return nf;
}
|
diff --git a/src/org/dita/dost/reader/MergeMapParser.java b/src/org/dita/dost/reader/MergeMapParser.java
index ff4fdb4af..d51caa323 100644
--- a/src/org/dita/dost/reader/MergeMapParser.java
+++ b/src/org/dita/dost/reader/MergeMapParser.java
@@ -1,179 +1,180 @@
/*
* 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. 2004, 2005 All Rights Reserved.
*/
package org.dita.dost.reader;
import java.io.File;
import org.dita.dost.exception.DITAOTXMLErrorHandler;
import org.dita.dost.log.DITAOTJavaLogger;
import org.dita.dost.module.Content;
import org.dita.dost.module.ContentImpl;
import org.dita.dost.util.Constants;
import org.dita.dost.util.MergeUtils;
import org.dita.dost.util.StringUtils;
import org.xml.sax.Attributes;
import org.xml.sax.SAXException;
import org.xml.sax.XMLReader;
import org.xml.sax.helpers.XMLReaderFactory;
/**
* MergeMapParser reads the ditamap file after preprocessing and merges
* different files into one intermediate result. It calls MergeTopicParser
* to process the topic file.
*
* @author Zhang, Yuan Peng
*/
public class MergeMapParser extends AbstractXMLReader {
private XMLReader reader = null;
private StringBuffer mapInfo = null;
private MergeTopicParser topicParser = null;
private DITAOTJavaLogger logger = null;
private MergeUtils util;
private ContentImpl content;
private String dirPath = null;
/**
* Default Constructor
*/
public MergeMapParser() {
logger = new DITAOTJavaLogger();
try{
if (System.getProperty(Constants.SAX_DRIVER_PROPERTY) == null){
//The default sax driver is set to xerces's sax driver
StringUtils.initSaxDriver();
}
if(reader == null){
reader = XMLReaderFactory.createXMLReader();
reader.setContentHandler(this);
// reader.setProperty(Constants.LEXICAL_HANDLER_PROPERTY,this);
reader.setFeature(Constants.FEATURE_NAMESPACE_PREFIX, true);
// reader.setFeature(Constants.FEATURE_VALIDATION, true);
// reader.setFeature(Constants.FEATURE_VALIDATION_SCHEMA, true);
}
if(mapInfo == null){
mapInfo = new StringBuffer(Constants.INT_1024);
}
topicParser = new MergeTopicParser();
content = new ContentImpl();
util = MergeUtils.getInstance();
}catch (Exception e){
logger.logException(e);
}
}
/**
* @see org.dita.dost.reader.AbstractReader#getContent()
*/
public Content getContent() {
content.setValue(mapInfo.append((StringBuffer)topicParser.getContent().getValue()));
return content;
}
/**
* @see org.dita.dost.reader.AbstractReader#read(java.lang.String)
*/
public void read(String filename) {
try{
File input = new File(filename);
dirPath = input.getParent();
reader.setErrorHandler(new DITAOTXMLErrorHandler(filename));
reader.parse(filename);
}catch(Exception e){
logger.logException(e);
}
}
/**
* @see org.xml.sax.ContentHandler#endElement(java.lang.String, java.lang.String, java.lang.String)
*/
public void endElement(String uri, String localName, String qName) throws SAXException {
mapInfo.append(Constants.LESS_THAN)
.append(Constants.SLASH)
.append(qName)
.append(Constants.GREATER_THAN);
}
/**
* @see org.xml.sax.ContentHandler#characters(char[], int, int)
*/
public void characters(char[] ch, int start, int length) throws SAXException {
mapInfo.append(StringUtils.escapeXML(ch, start, length));
}
/**
* @see org.xml.sax.ContentHandler#startElement(java.lang.String, java.lang.String, java.lang.String, org.xml.sax.Attributes)
*/
public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
String scopeValue = null;
String formatValue = null;
String classValue = null;
String fileId = null;
int attsLen = atts.getLength();
mapInfo.append(Constants.LESS_THAN).append(qName);
+ classValue = atts.getValue(Constants.ATTRIBUTE_NAME_CLASS);
for (int i = 0; i < attsLen; i++) {
String attQName = atts.getQName(i);
String attValue = atts.getValue(i);
if(Constants.ATTRIBUTE_NAME_HREF.equals(attQName)
&& !StringUtils.isEmptyString(attValue)
&& classValue != null
&& classValue.indexOf(Constants.ATTR_CLASS_VALUE_TOPICREF)!=-1){
scopeValue = atts.getValue(Constants.ATTRIBUTE_NAME_SCOPE);
formatValue = atts.getValue(Constants.ATTRIBUTE_NAME_FORMAT);
// if (attValue.indexOf(Constants.SHARP) != -1){
// attValue = attValue.substring(0, attValue.indexOf(Constants.SHARP));
// }
if((scopeValue == null
|| Constants.ATTR_SCOPE_VALUE_LOCAL.equalsIgnoreCase(scopeValue))
&& (formatValue == null
|| Constants.ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(formatValue))){
if (util.isVisited(attValue)){
mapInfo.append(Constants.STRING_BLANK)
.append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
// random = RandomUtils.getRandomNum();
// filename = attValue + "(" + Long.toString(random) + ")";
attValue = new StringBuffer(Constants.SHARP).append(util.getIdValue(attValue)).toString();
//parse the file but give it another file name
// topicParser.read(filename);
}else{
mapInfo.append(Constants.STRING_BLANK)
.append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
//parse the topic
fileId = topicParser.parse(attValue,dirPath);
util.visit(attValue);
attValue = new StringBuffer(Constants.SHARP).append(fileId).toString();
}
}
}
//output all attributes
mapInfo.append(Constants.STRING_BLANK)
.append(attQName).append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
}
mapInfo.append(Constants.GREATER_THAN);
}
}
| true | true | public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
String scopeValue = null;
String formatValue = null;
String classValue = null;
String fileId = null;
int attsLen = atts.getLength();
mapInfo.append(Constants.LESS_THAN).append(qName);
for (int i = 0; i < attsLen; i++) {
String attQName = atts.getQName(i);
String attValue = atts.getValue(i);
if(Constants.ATTRIBUTE_NAME_HREF.equals(attQName)
&& !StringUtils.isEmptyString(attValue)
&& classValue != null
&& classValue.indexOf(Constants.ATTR_CLASS_VALUE_TOPICREF)!=-1){
scopeValue = atts.getValue(Constants.ATTRIBUTE_NAME_SCOPE);
formatValue = atts.getValue(Constants.ATTRIBUTE_NAME_FORMAT);
// if (attValue.indexOf(Constants.SHARP) != -1){
// attValue = attValue.substring(0, attValue.indexOf(Constants.SHARP));
// }
if((scopeValue == null
|| Constants.ATTR_SCOPE_VALUE_LOCAL.equalsIgnoreCase(scopeValue))
&& (formatValue == null
|| Constants.ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(formatValue))){
if (util.isVisited(attValue)){
mapInfo.append(Constants.STRING_BLANK)
.append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
// random = RandomUtils.getRandomNum();
// filename = attValue + "(" + Long.toString(random) + ")";
attValue = new StringBuffer(Constants.SHARP).append(util.getIdValue(attValue)).toString();
//parse the file but give it another file name
// topicParser.read(filename);
}else{
mapInfo.append(Constants.STRING_BLANK)
.append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
//parse the topic
fileId = topicParser.parse(attValue,dirPath);
util.visit(attValue);
attValue = new StringBuffer(Constants.SHARP).append(fileId).toString();
}
}
}
//output all attributes
mapInfo.append(Constants.STRING_BLANK)
.append(attQName).append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
}
mapInfo.append(Constants.GREATER_THAN);
}
| public void startElement(String uri, String localName, String qName, Attributes atts) throws SAXException {
String scopeValue = null;
String formatValue = null;
String classValue = null;
String fileId = null;
int attsLen = atts.getLength();
mapInfo.append(Constants.LESS_THAN).append(qName);
classValue = atts.getValue(Constants.ATTRIBUTE_NAME_CLASS);
for (int i = 0; i < attsLen; i++) {
String attQName = atts.getQName(i);
String attValue = atts.getValue(i);
if(Constants.ATTRIBUTE_NAME_HREF.equals(attQName)
&& !StringUtils.isEmptyString(attValue)
&& classValue != null
&& classValue.indexOf(Constants.ATTR_CLASS_VALUE_TOPICREF)!=-1){
scopeValue = atts.getValue(Constants.ATTRIBUTE_NAME_SCOPE);
formatValue = atts.getValue(Constants.ATTRIBUTE_NAME_FORMAT);
// if (attValue.indexOf(Constants.SHARP) != -1){
// attValue = attValue.substring(0, attValue.indexOf(Constants.SHARP));
// }
if((scopeValue == null
|| Constants.ATTR_SCOPE_VALUE_LOCAL.equalsIgnoreCase(scopeValue))
&& (formatValue == null
|| Constants.ATTR_FORMAT_VALUE_DITA.equalsIgnoreCase(formatValue))){
if (util.isVisited(attValue)){
mapInfo.append(Constants.STRING_BLANK)
.append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
// random = RandomUtils.getRandomNum();
// filename = attValue + "(" + Long.toString(random) + ")";
attValue = new StringBuffer(Constants.SHARP).append(util.getIdValue(attValue)).toString();
//parse the file but give it another file name
// topicParser.read(filename);
}else{
mapInfo.append(Constants.STRING_BLANK)
.append("ohref").append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
//parse the topic
fileId = topicParser.parse(attValue,dirPath);
util.visit(attValue);
attValue = new StringBuffer(Constants.SHARP).append(fileId).toString();
}
}
}
//output all attributes
mapInfo.append(Constants.STRING_BLANK)
.append(attQName).append(Constants.EQUAL).append(Constants.QUOTATION)
.append(StringUtils.escapeXML(attValue)).append(Constants.QUOTATION);
}
mapInfo.append(Constants.GREATER_THAN);
}
|
diff --git a/src/player/millitta/Millitta.java b/src/player/millitta/Millitta.java
index 0f0af67..aeeb57e 100644
--- a/src/player/millitta/Millitta.java
+++ b/src/player/millitta/Millitta.java
@@ -1,131 +1,132 @@
package player.millitta;
import algds.Player;
import player.millitta.Evaluate.Evaluator;
public class Millitta extends Player implements Constants {
private long board;
/*
0 ----------- 1 ----------- 2
| | |
| 8 ------- 9 ------ 10 |
| | | | |
| | 16 - 17 - 18 | |
| | | | | |
7 - 15 - 23 19- 11 - 3
| | | | | |
| | 22 - 21 - 20 | |
| | | | |
| 14 ------ 13 ----- 12 |
| | |
6 ----------- 5 ----------- 4
*/
protected Millitta() {
super();
}
public void play() {
board = getBoardLong();
Evaluator eval = new Evaluator(board);
long nextBoard = eval.getNextBoard();
setMessage("Board: " + String.valueOf(board));
setMessage("Next board: " + nextBoard);
// Make the move!
long bitDiff = (board ^ nextBoard) & BITS_MENS;
if ((board & ((1L << BIT_ACTION))) != 0L) {
int pos = (int) (Math.log(bitDiff) / LOG2);
setMessage("Set Man to: "+pos);
pos = pos >= 24 ? pos - 24 : pos;
if ((board & (1L << (BIT_ACTION + 1))) != 0L) { // Remove man
this.removeMan(pos);
} else { // Set man
this.setMan(pos);
}
} else { // move man
int pos1 = (int) (Math.log(bitDiff) / LOG2); // highest set bit
int pos2 = (int) (Math.log(bitDiff & ~(1L << pos1)) / LOG2); // second set bit
// TODO lesbar machen
if ((board & (1L << pos1)) == 0L) {
moveMan(pos2 >= 24 ? pos2 - 24 : pos2, pos1 >= 24 ? pos1 - 24 : pos1);
} else {
moveMan(pos1 >= 24 ? pos1 - 24 : pos1, pos2 >= 24 ? pos2 - 24 : pos2);
}
}
}
public String getAuthor() {
return "Jens Dieskau";
}
private long getBoardLong() {
// Reset board
long board = 0L;
int[] boardArray = getBoard();
// Speichere aktiven Spieler
if (getMyColor() == BLACK) {
board = 1L << BIT_PLAYER;
}
// Positionen der Spielfiguren
for (int i = 0; i < 24; ++i) {
switch (boardArray[i]) {
case BLACK:
board |= 1L << (24 + i);
break;
case WHITE:
board |= 1L << i;
break;
default:
break;
}
}
// Aktion und Spielphase
switch (getAction()) {
case SET_MAN:
board |= 1L << BIT_PHASE; // Setzphase
board |= 1L << BIT_ACTION;
break;
case MOVE_MAN:
board |= 1L << BIT_ACTION + 1;
break;
case REMOVE_MAN:
board |= (1L << BIT_ACTION) | (1L << (BIT_ACTION + 1));
break;
default:
break;
}
if (getAction() != SET_MAN) {
if (Helper.getMyMenOnBoard(board) <= 3 && countMyRest() <= 0) { // Flugphase
board |= (1L << BIT_PHASE) | (1L << (BIT_PHASE + 1));
} else if (countMyRest() > 0) { // Setzphase
board |= 1L << BIT_PHASE;
} else { // Zugphase
// BIT_PHASE => 0
}
}
// Anzahl noch zu setzender Spieler
if( (board & (1L << BIT_PLAYER)) != 0L) { // Ich bin Spieler 2
- board |= (countMyRest() << BIT_REST2);
- board |= (countOppRest() << BIT_REST1);
+ board |= ((long)(countMyRest()) << BIT_REST2);
+ board |= ((long)(countOppRest()) << BIT_REST1);
} else {
- board |= (countMyRest() << BIT_REST1);
- board |= (countOppRest() << BIT_REST2);
+ board |= ((long)(countMyRest()) << BIT_REST1);
+ board |= ((long)(countOppRest()) << BIT_REST2);
}
+ setMessage("First board: " + board);
return board;
}
}
| false | true | private long getBoardLong() {
// Reset board
long board = 0L;
int[] boardArray = getBoard();
// Speichere aktiven Spieler
if (getMyColor() == BLACK) {
board = 1L << BIT_PLAYER;
}
// Positionen der Spielfiguren
for (int i = 0; i < 24; ++i) {
switch (boardArray[i]) {
case BLACK:
board |= 1L << (24 + i);
break;
case WHITE:
board |= 1L << i;
break;
default:
break;
}
}
// Aktion und Spielphase
switch (getAction()) {
case SET_MAN:
board |= 1L << BIT_PHASE; // Setzphase
board |= 1L << BIT_ACTION;
break;
case MOVE_MAN:
board |= 1L << BIT_ACTION + 1;
break;
case REMOVE_MAN:
board |= (1L << BIT_ACTION) | (1L << (BIT_ACTION + 1));
break;
default:
break;
}
if (getAction() != SET_MAN) {
if (Helper.getMyMenOnBoard(board) <= 3 && countMyRest() <= 0) { // Flugphase
board |= (1L << BIT_PHASE) | (1L << (BIT_PHASE + 1));
} else if (countMyRest() > 0) { // Setzphase
board |= 1L << BIT_PHASE;
} else { // Zugphase
// BIT_PHASE => 0
}
}
// Anzahl noch zu setzender Spieler
if( (board & (1L << BIT_PLAYER)) != 0L) { // Ich bin Spieler 2
board |= (countMyRest() << BIT_REST2);
board |= (countOppRest() << BIT_REST1);
} else {
board |= (countMyRest() << BIT_REST1);
board |= (countOppRest() << BIT_REST2);
}
return board;
}
| private long getBoardLong() {
// Reset board
long board = 0L;
int[] boardArray = getBoard();
// Speichere aktiven Spieler
if (getMyColor() == BLACK) {
board = 1L << BIT_PLAYER;
}
// Positionen der Spielfiguren
for (int i = 0; i < 24; ++i) {
switch (boardArray[i]) {
case BLACK:
board |= 1L << (24 + i);
break;
case WHITE:
board |= 1L << i;
break;
default:
break;
}
}
// Aktion und Spielphase
switch (getAction()) {
case SET_MAN:
board |= 1L << BIT_PHASE; // Setzphase
board |= 1L << BIT_ACTION;
break;
case MOVE_MAN:
board |= 1L << BIT_ACTION + 1;
break;
case REMOVE_MAN:
board |= (1L << BIT_ACTION) | (1L << (BIT_ACTION + 1));
break;
default:
break;
}
if (getAction() != SET_MAN) {
if (Helper.getMyMenOnBoard(board) <= 3 && countMyRest() <= 0) { // Flugphase
board |= (1L << BIT_PHASE) | (1L << (BIT_PHASE + 1));
} else if (countMyRest() > 0) { // Setzphase
board |= 1L << BIT_PHASE;
} else { // Zugphase
// BIT_PHASE => 0
}
}
// Anzahl noch zu setzender Spieler
if( (board & (1L << BIT_PLAYER)) != 0L) { // Ich bin Spieler 2
board |= ((long)(countMyRest()) << BIT_REST2);
board |= ((long)(countOppRest()) << BIT_REST1);
} else {
board |= ((long)(countMyRest()) << BIT_REST1);
board |= ((long)(countOppRest()) << BIT_REST2);
}
setMessage("First board: " + board);
return board;
}
|
diff --git a/src/java/sulfur/factories/SPageFactory.java b/src/java/sulfur/factories/SPageFactory.java
index 18447b5..63123a8 100644
--- a/src/java/sulfur/factories/SPageFactory.java
+++ b/src/java/sulfur/factories/SPageFactory.java
@@ -1,194 +1,194 @@
/*
This file is part of the Sulfur project by Ivan De Marino (http://ivandemarino.me).
Copyright (c) 2013, Ivan De Marino (http://ivandemarino.me)
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.
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 HOLDER 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 sulfur.factories;
import sulfur.SPage;
import sulfur.factories.exceptions.*;
import com.google.gson.Gson;
import com.google.gson.JsonSyntaxException;
import org.apache.log4j.Logger;
import org.openqa.selenium.WebDriver;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Map;
import java.util.Set;
/**
* @author Ivan De Marino
*
* #factory
* #singleton
*
* TODO
*/
public class SPageFactory {
/** Logger */
private static final Logger LOG = Logger.getLogger(SPageFactory.class);
/** MANDATORY System Property to instruct Sulfur where to look for the Config file */
public static final String SYSPROP_CONFIG_FILE_PATH = "sulfur.config";
private final SConfig mConfig;
private final SPageConfigFactory mPageConfigFactory;
private static SPageFactory singleton = null;
private SPageFactory() {
// Read configuration file location
String configFilePath = System.getProperty(SYSPROP_CONFIG_FILE_PATH);
if (null == configFilePath) {
throw new SConfigNotProvidedException();
}
// Parse configuration file
Gson gson = new Gson();
try {
FileReader configFileReader = new FileReader(configFilePath);
mConfig = gson.fromJson(configFileReader, SConfig.class);
// Logging
LOG.debug("FOUND Sulfur Config file: " + configFilePath);
mConfig.logDebug(LOG);
} catch (FileNotFoundException fnfe) {
LOG.error("INVALID Config (not found)");
throw new SInvalidConfigException(configFilePath);
} catch (JsonSyntaxException jse) {
LOG.error("INVALID Config (malformed)");
throw new SInvalidConfigException(configFilePath, jse);
}
// Fetch a SPageConfigFactory
mPageConfigFactory = SPageConfigFactory.getInstance();
LOG.debug("Available Pages: " + getAvailablePageConfigs());
}
/**
* Factory Method
*
* @return The SPageFactory
*/
public synchronized static SPageFactory getInstance() {
if (null == singleton) {
singleton = new SPageFactory();
}
return singleton;
}
/**
* Utility method to get rid of the SPageFactory Singleton Instance.
* NOTE: Make sure you know what you are doing when using this.
*/
public synchronized static void clearInstance() {
singleton = null;
}
/**
* Creates a SPage.
* It validates the input parameters, checking if the requested driver exists, if the page exists and the
* mandatory path and query parameters are all provided.
*
* NOTE: The returned SPage hasn't loaded yet, so the User can still operate on it before the initial HTTP GET.
*
* @param driverName Possible values are listed in @see SWebDriverFactory
* @param pageName Name of the SPage we want to open. It must be part of the given SPageConfig(s)
* @param pathParams Map of parameters that will be set in the SPage URL Path (@see SPageConfig)
* @param queryParams Map of parameters that will be set in the SPage URL Query (@see SPageConfig)
* @return A "ready to open" SPage object
*/
public SPage createPage(String driverName,
String pageName,
Map<String, String> pathParams,
Map<String, String> queryParams) {
// Validate Driver Name
if (!getConfig().getDrivers().contains(driverName)) {
throw new SUnavailableDriverException(driverName);
}
// Validate SPage Name
if (!getAvailablePageConfigs().contains(pageName)) {
throw new SUnavailablePageException(pageName);
}
// Fetch required SPageConfig
SPageConfig pageConfig = mPageConfigFactory.getPageConfig(pageName);
// Compose URL Path & Query to the SPage
String urlPath = pageConfig.composeUrlPath(pathParams);
String urlQuery = pageConfig.composeUrlQuery(queryParams);
// Create the requested driver
WebDriver driver = SWebDriverFactory.createDriver(driverName);
// Create the destination URL
String initialUrl;
try {
initialUrl = new URL(mConfig.getProtocol(), mConfig.getHost(), mConfig.getPort(), urlPath + "?" + urlQuery).toString();
} catch (MalformedURLException mue) {
LOG.fatal(String.format("FAILED to compose the URL to the Page '%s'", pageName), mue);
throw new SFailedToCreatePageException(mue);
}
// Create and return the new SPage
try {
return new SPage(driver, initialUrl, pageConfig.getComponentClassnames());
} catch (Exception e) {
// In case something goes wrong when creating the SPage, it's important we "quit()" the driver.
// We don't want Browser instances hanging around
- LOG.fatal(String.format("EXCEPTION thrown while trying to create Page '%s'"), e);
+ LOG.fatal(String.format("EXCEPTION thrown while trying to create Page '%s'", pageName), e);
driver.quit();
throw e;
}
}
public SPage createClonePage(SPage pageToClone) {
return new SPage(pageToClone);
}
public SPage createNextPage(SPage currentPage, String pageName) {
// Fetch required SPageConfig
SPageConfig pageConfig = mPageConfigFactory.getPageConfig(pageName);
// Build a new page using the same driver as "currentPage"
return new SPage(currentPage.getDriver(), pageConfig.getComponentClassnames());
}
public Set<String> getAvailablePageConfigs() {
return mPageConfigFactory.getPageConfigs().keySet();
}
/**
* @return The Sulfur Configuration currently used by the SPageFactory
*/
public SConfig getConfig() {
return mConfig;
}
}
| true | true | public SPage createPage(String driverName,
String pageName,
Map<String, String> pathParams,
Map<String, String> queryParams) {
// Validate Driver Name
if (!getConfig().getDrivers().contains(driverName)) {
throw new SUnavailableDriverException(driverName);
}
// Validate SPage Name
if (!getAvailablePageConfigs().contains(pageName)) {
throw new SUnavailablePageException(pageName);
}
// Fetch required SPageConfig
SPageConfig pageConfig = mPageConfigFactory.getPageConfig(pageName);
// Compose URL Path & Query to the SPage
String urlPath = pageConfig.composeUrlPath(pathParams);
String urlQuery = pageConfig.composeUrlQuery(queryParams);
// Create the requested driver
WebDriver driver = SWebDriverFactory.createDriver(driverName);
// Create the destination URL
String initialUrl;
try {
initialUrl = new URL(mConfig.getProtocol(), mConfig.getHost(), mConfig.getPort(), urlPath + "?" + urlQuery).toString();
} catch (MalformedURLException mue) {
LOG.fatal(String.format("FAILED to compose the URL to the Page '%s'", pageName), mue);
throw new SFailedToCreatePageException(mue);
}
// Create and return the new SPage
try {
return new SPage(driver, initialUrl, pageConfig.getComponentClassnames());
} catch (Exception e) {
// In case something goes wrong when creating the SPage, it's important we "quit()" the driver.
// We don't want Browser instances hanging around
LOG.fatal(String.format("EXCEPTION thrown while trying to create Page '%s'"), e);
driver.quit();
throw e;
}
}
| public SPage createPage(String driverName,
String pageName,
Map<String, String> pathParams,
Map<String, String> queryParams) {
// Validate Driver Name
if (!getConfig().getDrivers().contains(driverName)) {
throw new SUnavailableDriverException(driverName);
}
// Validate SPage Name
if (!getAvailablePageConfigs().contains(pageName)) {
throw new SUnavailablePageException(pageName);
}
// Fetch required SPageConfig
SPageConfig pageConfig = mPageConfigFactory.getPageConfig(pageName);
// Compose URL Path & Query to the SPage
String urlPath = pageConfig.composeUrlPath(pathParams);
String urlQuery = pageConfig.composeUrlQuery(queryParams);
// Create the requested driver
WebDriver driver = SWebDriverFactory.createDriver(driverName);
// Create the destination URL
String initialUrl;
try {
initialUrl = new URL(mConfig.getProtocol(), mConfig.getHost(), mConfig.getPort(), urlPath + "?" + urlQuery).toString();
} catch (MalformedURLException mue) {
LOG.fatal(String.format("FAILED to compose the URL to the Page '%s'", pageName), mue);
throw new SFailedToCreatePageException(mue);
}
// Create and return the new SPage
try {
return new SPage(driver, initialUrl, pageConfig.getComponentClassnames());
} catch (Exception e) {
// In case something goes wrong when creating the SPage, it's important we "quit()" the driver.
// We don't want Browser instances hanging around
LOG.fatal(String.format("EXCEPTION thrown while trying to create Page '%s'", pageName), e);
driver.quit();
throw e;
}
}
|
diff --git a/src/ox/stackgame/stackmachine/StringStackValue.java b/src/ox/stackgame/stackmachine/StringStackValue.java
index b97f90a..433e503 100644
--- a/src/ox/stackgame/stackmachine/StringStackValue.java
+++ b/src/ox/stackgame/stackmachine/StringStackValue.java
@@ -1,58 +1,58 @@
package ox.stackgame.stackmachine;
import ox.stackgame.stackmachine.exceptions.TypeException;
public class StringStackValue extends StackValue<String> {
private String value;
public StringStackValue() {
}
public StringStackValue(String value) {
this.value = value;
}
public boolean init( String str ) {
this.value = str;
return true;
}
@Override
public String getValue() {
return value;
}
@Override
public StackValue<?> add(StackValue<?> y) throws TypeException {
throw new TypeException(0, this.getClass());
}
@Override
public StackValue<?> sub(StackValue<?> y) throws TypeException {
throw new TypeException(0, this.getClass());
}
@Override
public StackValue<?> mul(StackValue<?> y) throws TypeException {
throw new TypeException(0, this.getClass());
}
@Override
public StackValue<?> div(StackValue<?> y) throws TypeException {
throw new TypeException(0, this.getClass());
}
@Override
public boolean equals(Object other) {
if (other instanceof StackValue<?>) {
StackValue<?> otherStackValue = (StackValue<?>) other;
- return value.equals(otherStackValue); // TODO is this self referential?
+ return value.equals(otherStackValue.toString());
} else
return false;
}
public int hashCode() {
return value.hashCode();
}
}
| true | true | public boolean equals(Object other) {
if (other instanceof StackValue<?>) {
StackValue<?> otherStackValue = (StackValue<?>) other;
return value.equals(otherStackValue); // TODO is this self referential?
} else
return false;
}
| public boolean equals(Object other) {
if (other instanceof StackValue<?>) {
StackValue<?> otherStackValue = (StackValue<?>) other;
return value.equals(otherStackValue.toString());
} else
return false;
}
|
diff --git a/core/src/test/java/com/google/bitcoin/core/FakeChannelSink.java b/core/src/test/java/com/google/bitcoin/core/FakeChannelSink.java
index ff3bd57..9e23a61 100644
--- a/core/src/test/java/com/google/bitcoin/core/FakeChannelSink.java
+++ b/core/src/test/java/com/google/bitcoin/core/FakeChannelSink.java
@@ -1,53 +1,54 @@
package com.google.bitcoin.core;
import org.jboss.netty.channel.*;
import static org.jboss.netty.channel.Channels.fireChannelConnected;
public class FakeChannelSink extends AbstractChannelSink {
public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
if (e instanceof ChannelStateEvent) {
ChannelStateEvent event = (ChannelStateEvent) e;
FakeChannel channel = (FakeChannel) event.getChannel();
boolean offered = channel.events.offer(event);
assert offered;
ChannelFuture future = event.getFuture();
ChannelState state = event.getState();
Object value = event.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
channel.setClosed();
}
break;
case BOUND:
if (value != null) {
// Bind
} else {
// Close
}
break;
case CONNECTED:
if (value != null) {
future.setSuccess();
fireChannelConnected(channel, channel.getRemoteAddress());
} else {
// Close
}
break;
case INTEREST_OPS:
// Unsupported - discard silently.
future.setSuccess();
break;
}
} else if (e instanceof MessageEvent) {
MessageEvent event = (MessageEvent) e;
FakeChannel channel = (FakeChannel) event.getChannel();
boolean offered = channel.events.offer(event);
assert offered;
+ event.getFuture().setSuccess();
}
}
}
| true | true | public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
if (e instanceof ChannelStateEvent) {
ChannelStateEvent event = (ChannelStateEvent) e;
FakeChannel channel = (FakeChannel) event.getChannel();
boolean offered = channel.events.offer(event);
assert offered;
ChannelFuture future = event.getFuture();
ChannelState state = event.getState();
Object value = event.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
channel.setClosed();
}
break;
case BOUND:
if (value != null) {
// Bind
} else {
// Close
}
break;
case CONNECTED:
if (value != null) {
future.setSuccess();
fireChannelConnected(channel, channel.getRemoteAddress());
} else {
// Close
}
break;
case INTEREST_OPS:
// Unsupported - discard silently.
future.setSuccess();
break;
}
} else if (e instanceof MessageEvent) {
MessageEvent event = (MessageEvent) e;
FakeChannel channel = (FakeChannel) event.getChannel();
boolean offered = channel.events.offer(event);
assert offered;
}
}
| public void eventSunk(ChannelPipeline pipeline, ChannelEvent e) throws Exception {
if (e instanceof ChannelStateEvent) {
ChannelStateEvent event = (ChannelStateEvent) e;
FakeChannel channel = (FakeChannel) event.getChannel();
boolean offered = channel.events.offer(event);
assert offered;
ChannelFuture future = event.getFuture();
ChannelState state = event.getState();
Object value = event.getValue();
switch (state) {
case OPEN:
if (Boolean.FALSE.equals(value)) {
channel.setClosed();
}
break;
case BOUND:
if (value != null) {
// Bind
} else {
// Close
}
break;
case CONNECTED:
if (value != null) {
future.setSuccess();
fireChannelConnected(channel, channel.getRemoteAddress());
} else {
// Close
}
break;
case INTEREST_OPS:
// Unsupported - discard silently.
future.setSuccess();
break;
}
} else if (e instanceof MessageEvent) {
MessageEvent event = (MessageEvent) e;
FakeChannel channel = (FakeChannel) event.getChannel();
boolean offered = channel.events.offer(event);
assert offered;
event.getFuture().setSuccess();
}
}
|
diff --git a/src/java/fedora/server/storage/replication/DefaultDOReplicator.java b/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
index b72248630..93c2bac95 100755
--- a/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
+++ b/src/java/fedora/server/storage/replication/DefaultDOReplicator.java
@@ -1,2890 +1,2890 @@
package fedora.server.storage.replication;
import java.util.*;
import java.sql.*;
import java.net.InetAddress;
import java.net.UnknownHostException;
import java.util.regex.Pattern;
import fedora.server.errors.*;
import fedora.server.storage.*;
import fedora.server.storage.lowlevel.FileSystemLowlevelStorage;
import fedora.server.storage.types.*;
import fedora.server.utilities.SQLUtility;
import fedora.server.Module;
import fedora.server.Server;
import fedora.server.storage.ConnectionPoolManager;
import fedora.server.errors.ModuleInitializationException;
/**
*
* <p><b>Title:</b> DefaultDOReplicator.java</p>
* <p><b>Description:</b> A Module that replicates digital object information
* to the dissemination database.</p>
*
* <p>Converts data read from the object reader interfaces and creates or
* updates the corresponding database rows in the dissemination database.</p>
*
* -----------------------------------------------------------------------------
*
* <p><b>License and Copyright: </b>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 <a href="http://www.mozilla.org/MPL">http://www.mozilla.org/MPL/.</a></p>
*
* <p>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.</p>
*
* <p>The entire file consists of original code. Copyright © 2002-2005 by The
* Rector and Visitors of the University of Virginia and Cornell University.
* All rights reserved.</p>
*
* -----------------------------------------------------------------------------
*
* @author Paul Charlton, [email protected]
* @version $Id$
*/
public class DefaultDOReplicator
extends Module
implements DOReplicator {
private ConnectionPool m_pool;
private RowInsertion m_ri;
// sdp - local.fedora.server conversion
private Pattern hostPattern = null;
private Pattern hostPortPattern = null;
private Pattern serializedLocalURLPattern = null;
/**
* Server instance to work with in this module.
*/
private Server server;
/** Port number on which the Fedora server is running; determined from
* fedora.fcfg config file.
*/
private static String fedoraServerPort = null;
/** Hostname of the Fedora server determined from
* fedora.fcfg config file, or (fallback) by hostIP.getHostName()
*/
private static String fedoraServerHost = null;
/** The IP address of the local host; determined dynamically. */
private static InetAddress hostIP = null;
public DefaultDOReplicator(Map moduleParameters, Server server, String role)
throws ModuleInitializationException {
super(moduleParameters, server, role);
}
public void initModule() {
}
public void postInitModule()
throws ModuleInitializationException {
try {
ConnectionPoolManager mgr=(ConnectionPoolManager)
getServer().getModule(
"fedora.server.storage.ConnectionPoolManager");
m_pool=mgr.getPool();
// sdp: insert new
hostIP = null;
fedoraServerPort = getServer().getParameter("fedoraServerPort");
getServer().logFinest("fedoraServerPort: " + fedoraServerPort);
hostIP = InetAddress.getLocalHost();
fedoraServerHost = getServer().getParameter("fedoraServerHost");
if (fedoraServerHost==null || fedoraServerHost.equals("")) {
fedoraServerHost=hostIP.getHostName();
}
hostPattern = Pattern.compile("http://"+fedoraServerHost+"/");
hostPortPattern = Pattern.compile("http://"+fedoraServerHost+":"+fedoraServerPort+"/");
serializedLocalURLPattern = Pattern.compile("http://local.fedora.server/");
//System.out.println("Replicator: hostPattern is " + hostPattern.pattern());
//System.out.println("Replicator: hostPortPattern is " + hostPortPattern.pattern());
//
} catch (ServerException se) {
throw new ModuleInitializationException(
"Error getting default pool: " + se.getMessage(),
getRole());
} catch (UnknownHostException se) {
throw new ModuleInitializationException(
"Error determining hostIP address: " + se.getMessage(),
getRole());
}
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* @ids=select doDbID from do where doPID='demo:5'
* if @ids.size=0, return false
* else:
* foreach $id in @ids
* ds=reader.getDatastream(id, null)
* update dsBind set dsLabel='mylabel', dsLocation='' where dsID='$id'
*
* // currentVersionId?
*
* @param reader a digital object reader.
* @return true is successful update; false oterhwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
logFinest("DefaultDOReplicator.updateComponents: Entering ------");
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// Get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID,doState,doLabel FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
String doState=results.getString("doState");
String doLabel=results.getString("doLabel");
results.close();
results=null;
ArrayList updates=new ArrayList();
// Check if state has changed for the digital object.
String objState = reader.GetObjectState();
if (!doState.equalsIgnoreCase(objState)) {
updates.add("UPDATE do SET doState='" + objState + "' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET objectState='" + objState + "' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// Check if label has changed for the digital object.
String objLabel = reader.GetObjectLabel();
if (!doLabel.equalsIgnoreCase(objLabel)) {
updates.add("UPDATE do SET doLabel='" + objLabel + "' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET label='" + objLabel + "' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
results=null;
// Do any required updates via a transaction.
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("DefaultDOReplication.updateComponents: "
+ "No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID);
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
if (dissDbIDs.size()==0 || reader.GetDisseminators(null, null).length!=dissDbIDs.size()) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "either has no disseminators or a new disseminator"
+ "has been added; components dont need updating.");
return false;
}
results.close();
results=null;
// Iterate over disseminators to check if any have been modified
Iterator dissIter = dissDbIDs.iterator();
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
// Get disseminator info for this disseminator.
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
results=null;
// Compare the latest version of the disseminator with what's in the db...
// Replace what's in db if they are different.
Disseminator diss=reader.GetDisseminator(dissID, null);
if (diss == null) {
// XML object has no disseminators
// so this must be a purgeComponents or a new object.
logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators");
return false;
}
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
if (!diss.dissLabel.equals(dissLabel))
logFinest("DefaultDOReplicator.updateComponents: dissLabel changed from '" + dissLabel + "' to '"
+ diss.dissLabel + "'");
if (!diss.dissState.equals(dissState))
logFinest("DefaultDOReplicator.updateComponents: dissState changed from '" + dissState + "' to '"
+ diss.dissState + "'");
// We might need to set the bMechDbID to the id for the new one,
// if the mechanism changed.
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
logFinest("DefaultDOReplicator.updateComponents: bMechPID changed from '" + bMechPID + "' to '"
+ diss.bMechID + "'");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
results=null;
}
// Update the diss table with all new, correct values.
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
+ "dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID
+ " AND bMechDbID=" + bMechDbID);
}
// Compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different.
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID);
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
results=null;
String newDSBindMapID=diss.dsBindMapID;
logFinest("DefaultDOReplicator.updateComponents: newDSBindMapID: "
+ newDSBindMapID + " origDSBindMapID: " + origDSBindMapID);
// Is this a new bindingMap?
if (!newDSBindMapID.equals(origDSBindMapID)) {
// Yes, dsBindingMap was modified so remove original bindingMap and datastreams.
// BindingMaps can be shared by other objects so first check to see if
// the orignial bindingMap is bound to datastreams of any other objects.
Statement st2 = connection.createStatement();
- results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbId,dsBindMapDbId FROM dsBind WHERE dsBindMapDbId="+origDSBindMapDbID);
+ results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbID,dsBindMapDbID FROM dsBind WHERE dsBindMapDbID="+origDSBindMapDbID);
int numRows = 0;
while (results.next()) {
numRows++;
}
st2.close();
st2=null;
results.close();
results=null;
// Remove all datastreams for this binding map.
// If anything has changed, they will all be added back
// shortly from the current binding info the xml object.
String dsBindMapDBID = null;
dsBindMapDBID = lookupDataStreamBindingMapDBID(connection, (new Integer(bMechDbID)).toString(), origDSBindMapID);
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID
+ " AND dsBindMapDbID="+dsBindMapDBID);
logFinest("DefaultDOReplicator.updateComponents: deleted "
+ rowCount + " rows from dsBind");
// Is bindingMap shared?
if(numRows == 1) {
// No, the bindingMap is NOT shared by any other objects and can be removed.
rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID="
+ origDSBindMapDbID);
logFinest("DefaultDOReplicator.updateComponents: deleted "
+ rowCount + " rows from dsBindMapDbID");
} else {
//Yes, the bindingMap IS shared by other objects so leave bindingMap untouched.
logFinest("DefaultDOReplicator.updateComponents: dsBindMapID: "
+ origDSBindMapID + " is shared by other objects; it will NOT be deleted");
}
// Now add back new datastreams and dsBindMap associated with this disseminator
// using current info in xml object.
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
//String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
logFinest("DefaultDOReplicator.updateComponents: Bindings found: "+allBindingMaps.length);
for (int i=0; i<allBindingMaps.length; ++i) {
// Only update bindingMap that was modified.
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
logFinest("DefaultDOReplicator.updateComponents: "
+ "Adding back datastreams and ds binding map. New dsBindMapID: "
+ newDSBindMapID);
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Now insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
logFinest("DefaultDOReplicator.updateComponents: ADDing dsBindMap row");
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
// Now add back datastream bindings removed earlier.
logFinest("DefaultDOReplicator.updateComponents: Bindings found: "
+ allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length; ++j) {
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i + " j=" + j);
}
// Insert DataStreamBinding row
logFinest("DefaultDOReplicator.updateComponents: Adding back dsBind row for: "
+allBindingMaps[i].dsBindingsAugmented[j].datastreamID);
Datastream ds = reader.getDatastream(allBindingMaps[i].dsBindingsAugmented[j].datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID);
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
ds.DSState);
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
if (connection!=null) m_pool.free(connection);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
results=null;
st=null;
}
}
}
}
logFinest("DefaultDOReplicator.updateComponents: Exiting ------");
return true;
}
private boolean addNewComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean failed=false;
logFinest("DefaultDOReplicator.addNewComponents: Entering ------");
try {
String doPID = reader.GetObjectPID();
connection=m_pool.getConnection();
connection.setAutoCommit(false);
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE "
+ "doPID='" + doPID + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.addNewComponents: Object is "
+ "new; components will be added as part of new object replication.");
return false;
}
int doDbID=results.getInt("doDbID");
results.close();
results=null;
Disseminator[] dissArray = reader.GetDisseminators(null, null);
HashSet newDisseminators = new HashSet();
int dissDBID = 0;
logFinest("DefaultDOReplicator.addNewComponents: Disseminators found: "
+ dissArray.length);
for (int j=0; j< dissArray.length; j++)
{
// Find disseminators that are NEW within an existing object
// (disseminator does not already exist in the database)
results=logAndExecuteQuery(st, "SELECT diss.dissDbID"
+ " FROM doDissAssoc, diss"
+ " WHERE doDissAssoc.doDbID=" + doDbID + " AND diss.dissID='" + dissArray[j].dissID + "'"
+ " AND doDissAssoc.dissDbID=diss.dissDbID");
dissDBID = 0;
while (results.next()) {
dissDBID = results.getInt("dissDbID");
}
if (dissDBID==0) {
// the disseminator does NOT exist in the database; it is NEW.
newDisseminators.add(dissArray[j]);
logFinest("DefaultDOReplicator.addNewComponents: Added new disseminator dissID: "+dissArray[j].dissID);
}
}
addDisseminators(doPID, (Disseminator[])newDisseminators.toArray(new Disseminator[0]), reader, connection);
connection.commit();
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
// TODO: make sure this makes sense here
if (connection!=null) {
try {
if (failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
if (connection!=null) m_pool.free(connection);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
results=null;
st=null;
}
}
}
}
logFinest("DefaultDOReplicator.addNewComponents: Exiting ------");
return true;
}
/**
* <p> Removes components of a digital object from the database.</p>
*
* @param reader an instance a DOReader.
* @return True if the removal was successfult; false otherwise.
* @throws ReplicationException If any type of error occurs during the removal.
*/
private boolean purgeComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean failed=false;
logFinest("DefaultDOReplication.purgeComponents: Entering -----");
try {
String doPID = reader.GetObjectPID();
connection=m_pool.getConnection();
connection.setAutoCommit(false);
st=connection.createStatement();
// get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID FROM do WHERE "
+ "doPID='" + doPID + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.purgeComponents: Object is "
+ "new; components will be added as part of new object replication.");
return false;
}
int doDbID=results.getInt("doDbID");
results.close();
results=null;
// FIXME: this is a quick hack to fix the problem of versioned datastreams
// not being properly removed from LLStore at time of purge.
// Check for any Managed Content Datastreams that have been purged
HashMap versions = new HashMap();
Datastream[] ds = reader.GetDatastreams(null, null);
for (int i=0; i<ds.length; i++) {
if(ds[i].DSControlGrp.equalsIgnoreCase("M"))
{
java.util.Date[] dates = reader.getDatastreamVersions(ds[i].DatastreamID);
for (int j=0; j<dates.length; j++)
{
Datastream d = reader.GetDatastream(ds[i].DatastreamID, dates[j]);
versions.put(d.DSVersionID, d.DSLocation);
}
}
}
HashMap dsPaths = new HashMap();
results=logAndExecuteQuery(st,"SELECT token FROM "
+ "datastreamPaths WHERE token LIKE '"
+ doPID + "+%'");
boolean isDeleted = false;
while (results.next())
{
String token = results.getString("token");
if(!versions.containsValue(token))
{
logInfo("Deleting ManagedContent datastream. " + "id: " + token);
isDeleted = true;
try {
FileSystemLowlevelStorage.getDatastreamStore().remove(token);
} catch (LowlevelStorageException llse) {
logWarning("While attempting removal of managed content datastream: " + llse.getClass().getName() + ": " + llse.getMessage());
}
}
}
results.close();
results=null;
if(isDeleted)
return true;
// Get all disseminators that are in db for this object
HashSet dissDbIds = new HashSet();
results=logAndExecuteQuery(st, "SELECT dissDbID"
+ " FROM doDissAssoc"
+ " WHERE doDbID=" + doDbID);
while (results.next()) {
Integer id = new Integer(results.getInt("dissDbID"));
dissDbIds.add(id);
}
results.close();
results=null;
logFinest("DefaultDOReplicator.purgeComponents: Found "
+ dissDbIds.size() + "dissDbId(s). ");
// Get all binding maps that are in db for this object
HashSet dsBindMapIds = new HashSet();
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMapDbID "
+ " FROM dsBind WHERE doDbID=" + doDbID);
while (results.next()) {
Integer id = new Integer(results.getInt("dsBindMapDbID"));
dsBindMapIds.add(id);
}
results.close();
results=null;
logFinest("DefaultDOReplicator.purgeComponents: Found "
+ dsBindMapIds.size() + "dsBindMapDbId(s). ");
// Now get all existing disseminators that are in xml object for this object
Disseminator[] dissArray = reader.GetDisseminators(null, null);
HashSet existingDisseminators = new HashSet();
HashSet purgedDisseminators = new HashSet();
for (int j=0; j< dissArray.length; j++)
{
// Find disseminators that have been removed within an existing object
// (disseminator(s) still exist in the database)
results=logAndExecuteQuery(st, "SELECT diss.dissDbID"
+ " FROM doDissAssoc, diss"
+ " WHERE doDissAssoc.doDbID=" + doDbID + " AND diss.dissID='" + dissArray[j].dissID + "'"
+ " AND doDissAssoc.dissDbID=diss.dissDbID");
if (!results.next()) {
// No disseminator was found in db so it must be new one
// indicating an instance of AddNewComponents rather than purgeComponents
logFinest("DefaultDOReplicator.purgeComponents: Disseminator not found in db; Assuming this is case of AddNewComponents");
return false;
} else {
Integer id = new Integer(results.getInt("dissDbID"));
existingDisseminators.add(id);
logFinest("DefaultDOReplicator.purgeComponents: Adding "
+ " dissDbId: " + id + " to list of Existing dissDbId(s). ");
}
results.close();
results=null;
}
logFinest("DefaultDOReplicator.purgeComponents: Found "
+ existingDisseminators.size() + " existing dissDbId(s). ");
// Now get all existing dsbindmapids that are in xml object for this object
HashSet existingDsBindMapIds = new HashSet();
HashSet purgedDsBindMapIds = new HashSet();
for (int j=0; j< dissArray.length; j++)
{
// Find disseminators that have been removed within an existing object
// (disseminator(s) still exist in the database)
results=logAndExecuteQuery(st, "SELECT dsBindMapDbID, dsBindMapID"
+ " FROM dsBindMap,bMech,diss"
+ " WHERE dsBindMap.bMechDbID=bMech.bMechDbID AND bMech.bMechPID='" + dissArray[j].bMechID + "' "
+ " AND diss.dissID='" + dissArray[j].dissID + "' AND dsBindMapID='" + dissArray[j].dsBindMapID + "'");
if (!results.next()) {
// No disseminator was found in db so it must be new one
// indicating an instance of AddNewComponents rather than purgeComponents
logFinest("DefaultDOReplicator.purgeComponents: Disseminator not found in db; Assuming this is case of AddNewComponents");
return false;
} else {
Integer dsBindMapDbId = new Integer(results.getInt("dsBindMapDbID"));
String dsBindMapID = results.getString("dsBindMapID");
existingDsBindMapIds.add(dsBindMapDbId);
logFinest("DefaultDOReplicator.purgeComponents: Adding "
+ " dsBindMapDbId: " + dsBindMapDbId + " to list of Existing dsBindMapDbId(s). ");
}
results.close();
results=null;
}
logFinest("DefaultDOReplicator.purgeComponents: Found "
+ existingDsBindMapIds.size() + " existing dsBindMapDbId(s). ");
// Compare what's in db with what's in xml object
Iterator dissDbIdIter = dissDbIds.iterator();
Iterator existingDissIter = existingDisseminators.iterator();
while (dissDbIdIter.hasNext()) {
Integer dissDbId = (Integer) dissDbIdIter.next();
if (existingDisseminators.contains(dissDbId)) {
// database disseminator exists in xml object
// so ignore
} else {
// database disseminator does not exist in xml object
// so remove it from database
purgedDisseminators.add(dissDbId);
logFinest("DefaultDOReplicator.purgeComponents: Adding "
+ " dissDbId: " + dissDbId + " to list of Purged dissDbId(s). ");
}
}
if (purgedDisseminators.isEmpty()) {
// no disseminators were removed so this must be an
// an instance of addComponent or updateComponent
logFinest("DefaultDOReplicator.purgeComponents: "
+ "No disseminators have been removed from object;"
+ " Assuming this a case of UpdateComponents");
return false;
}
// Compare what's in db with what's in xml object
Iterator dsBindMapIdIter = dsBindMapIds.iterator();
Iterator existingDsBindMapIdIter = existingDsBindMapIds.iterator();
while (dsBindMapIdIter.hasNext()) {
Integer dsBindMapDbId = (Integer) dsBindMapIdIter.next();
if (existingDsBindMapIds.contains(dsBindMapDbId)) {
// database disseminator exists in xml object
// so ignore
} else {
// database disseminator does not exist in xml object
// so remove it from database
purgedDsBindMapIds.add(dsBindMapDbId);
logFinest("DefaultDOReplicator.purgeComponents: Adding "
+ " dsBindMapDbId: " + dsBindMapDbId + " to list of Purged dsBindMapDbId(s). ");
}
}
if (purgedDsBindMapIds.isEmpty()) {
// no disseminators were removed so this must be an
// an instance of addComponent or updateComponent
logFinest("DefaultDOReplicator.purgeComponents: "
+ "No disseminators have been removed from object;"
+ " Assuming this a case of UpdateComponents");
return false;
}
purgeDisseminators(doPID, purgedDisseminators, purgedDsBindMapIds, reader, connection);
connection.commit();
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
// TODO: make sure this makes sense here
if (connection!=null) {
try {
if (failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
if (connection!=null) m_pool.free(connection);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
results=null;
st=null;
}
}
}
}
logFinest("DefaultDOReplicator.purgeComponents: Exiting ------");
return true;
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* Currently bdef components cannot be updated, so this will
* simply return true if the bDef has already been replicated.
*
* @param reader a behavior definitionobject reader.
* @return true if bdef update successful; false otherwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(BDefReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
logFinest("DefaultDOReplication.updateComponents: Entering -----");
try {
connection=m_pool.getConnection();
st=connection.createStatement();
results=logAndExecuteQuery(st, "SELECT bDefDbID,bDefState FROM bDef WHERE "
+ "bDefPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int bDefDbID=results.getInt("bDefDbID");
String bDefState=results.getString("bDefState");
results.close();
results=null;
ArrayList updates=new ArrayList();
// check if state has changed for the bdef object
String objState = reader.GetObjectState();
if (!bDefState.equalsIgnoreCase(objState)) {
updates.add("UPDATE bDef SET bDefState='"+objState+"' WHERE bDefDbID=" + bDefDbID);
updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("No datastream labels or locations changed.");
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
if (connection!=null) m_pool.free(connection);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
results=null;
st=null;
}
}
}
}
logFinest("DefaultDOReplication.updateComponents: Exiting -----");
return true;
}
/**
* If the object has already been replicated, update the components
* and return true. Otherwise, return false.
*
* Currently bmech components cannot be updated, so this will
* simply return true if the bMech has already been replicated.
*
* @param reader a behavior mechanism object reader.
* @return true if bmech update successful; false otherwise.
* @throws ReplicationException if replication fails for any reason.
*/
private boolean updateComponents(BMechReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
try {
connection=m_pool.getConnection();
st=connection.createStatement();
results=logAndExecuteQuery(st, "SELECT bMechDbID,bMechState FROM bMech WHERE "
+ "bMechPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int bMechDbID=results.getInt("bMechDbID");
String bMechState=results.getString("bMechState");
results.close();
results=null;
ArrayList updates=new ArrayList();
// check if state has changed for the bdef object
String objState = reader.GetObjectState();
if (!bMechState.equalsIgnoreCase(objState)) {
updates.add("UPDATE bMech SET bMechState='"+objState+"' WHERE bMechDbID=" + bMechDbID);
updates.add("UPDATE doRegistry SET objectState='"+objState+"' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// do any required updates via a transaction
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("DefaultDOReplicator.updateComponents(bMech): No datastream labels or locations changed.");
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
if (connection!=null) m_pool.free(connection);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
results=null;
st=null;
}
}
}
}
return true;
}
/**
* Replicates a Fedora behavior definition object.
*
* @param bDefReader behavior definition reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(BDefReader bDefReader)
throws ReplicationException, SQLException {
if (!updateComponents(bDefReader)) {
Connection connection=null;
try {
MethodDef behaviorDefs[];
String bDefDBID;
String bDefPID;
String bDefLabel;
String methDBID;
String methodName;
String parmRequired;
String[] parmDomainValues;
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Behavior Definition row
bDefPID = bDefReader.GetObjectPID();
bDefLabel = bDefReader.GetObjectLabel();
insertBehaviorDefinitionRow(connection, bDefPID, bDefLabel, bDefReader.GetObjectState());
// Insert method rows
bDefDBID = lookupBehaviorDefinitionDBID(connection, bDefPID);
if (bDefDBID == null) {
throw new ReplicationException(
"BehaviorDefinition row doesn't exist for PID: "
+ bDefPID);
}
behaviorDefs = bDefReader.getAbstractMethods(null);
for (int i=0; i<behaviorDefs.length; ++i) {
insertMethodRow(connection, bDefDBID,
behaviorDefs[i].methodName,
behaviorDefs[i].methodLabel);
// Insert method parm rows
methDBID = lookupMethodDBID(connection, bDefDBID,
behaviorDefs[i].methodName);
for (int j=0; j<behaviorDefs[i].methodParms.length; j++)
{
MethodParmDef[] methodParmDefs =
new MethodParmDef[behaviorDefs[i].methodParms.length];
methodParmDefs = behaviorDefs[i].methodParms;
parmRequired =
methodParmDefs[j].parmRequired ? "true" : "false";
parmDomainValues = methodParmDefs[j].parmDomainValues;
StringBuffer sb = new StringBuffer();
if (parmDomainValues != null && parmDomainValues.length > 0)
{
for (int k=0; k<parmDomainValues.length; k++)
{
if (k < parmDomainValues.length-1)
{
sb.append(parmDomainValues[k]+",");
} else
{
sb.append(parmDomainValues[k]);
}
}
} else
{
sb.append("null");
}
insertMethodParmRow(connection, methDBID, bDefDBID,
methodParmDefs[j].parmName,
methodParmDefs[j].parmDefaultValue,
sb.toString(),
parmRequired,
methodParmDefs[j].parmLabel,
methodParmDefs[j].parmType);
}
}
connection.commit();
} catch (ReplicationException re) {
throw re;
} catch (ServerException se) {
throw new ReplicationException("Replication exception caused by "
+ "ServerException - " + se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
/**
* Replicates a Fedora behavior mechanism object.
*
* @param bMechReader behavior mechanism reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(BMechReader bMechReader)
throws ReplicationException, SQLException {
if (!updateComponents(bMechReader)) {
Connection connection=null;
try {
BMechDSBindSpec dsBindSpec;
MethodDefOperationBind behaviorBindings[];
MethodDefOperationBind behaviorBindingsEntry;
String bDefDBID;
String bDefPID;
String bMechDBID;
String bMechPID;
String bMechLabel;
String dsBindingKeyDBID;
String methodDBID;
String ordinality_flag;
String cardinality;
String[] parmDomainValues;
String parmRequired;
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Behavior Mechanism row
dsBindSpec = bMechReader.getServiceDSInputSpec(null);
bDefPID = dsBindSpec.bDefPID;
bDefDBID = lookupBehaviorDefinitionDBID(connection, bDefPID);
if (bDefDBID == null) {
throw new ReplicationException("BehaviorDefinition row doesn't "
+ "exist for PID: " + bDefPID);
}
bMechPID = bMechReader.GetObjectPID();
bMechLabel = bMechReader.GetObjectLabel();
insertBehaviorMechanismRow(connection, bDefDBID, bMechPID,
bMechLabel, bMechReader.GetObjectState());
// Insert dsBindSpec rows
bMechDBID = lookupBehaviorMechanismDBID(connection, bMechPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row doesn't "
+ "exist for PID: " + bDefPID);
}
for (int i=0; i<dsBindSpec.dsBindRules.length; ++i) {
// Convert from type boolean to type String
ordinality_flag =
dsBindSpec.dsBindRules[i].ordinality ? "true" : "false";
// Convert from type int to type String
cardinality = Integer.toString(
dsBindSpec.dsBindRules[i].maxNumBindings);
insertDataStreamBindingSpecRow(connection,
bMechDBID, dsBindSpec.dsBindRules[i].bindingKeyName,
ordinality_flag, cardinality,
dsBindSpec.dsBindRules[i].bindingLabel);
// Insert dsMIME rows
dsBindingKeyDBID =
lookupDataStreamBindingSpecDBID(connection,
bMechDBID, dsBindSpec.dsBindRules[i].bindingKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"dsBindSpec row doesn't exist for "
+ "bMechDBID: " + bMechDBID
+ ", binding key name: "
+ dsBindSpec.dsBindRules[i].bindingKeyName);
}
for (int j=0; j<dsBindSpec.dsBindRules[i].bindingMIMETypes.length; ++j) {
insertDataStreamMIMERow(connection,
dsBindingKeyDBID,
dsBindSpec.dsBindRules[i].bindingMIMETypes[j]);
}
}
// Insert mechImpl rows
behaviorBindings = bMechReader.getServiceMethodBindings(null);
for (int i=0; i<behaviorBindings.length; ++i) {
behaviorBindingsEntry =
(MethodDefOperationBind)behaviorBindings[i];
if (!behaviorBindingsEntry.protocolType.equals("HTTP")) {
// For the time being, ignore bindings other than HTTP.
continue;
}
// Insert mechDefParm rows
methodDBID = lookupMethodDBID(connection, bDefDBID,
behaviorBindingsEntry.methodName);
if (methodDBID == null) {
throw new ReplicationException("Method row doesn't "
+ "exist for method name: "
+ behaviorBindingsEntry.methodName);
}
for (int j=0; j<behaviorBindings[i].methodParms.length; j++)
{
MethodParmDef[] methodParmDefs =
new MethodParmDef[behaviorBindings[i].methodParms.length];
methodParmDefs = behaviorBindings[i].methodParms;
//if (methodParmDefs[j].parmType.equalsIgnoreCase("fedora:defaultInputType"))
if (methodParmDefs[j].parmType.equalsIgnoreCase(MethodParmDef.DEFAULT_INPUT))
{
parmRequired =
methodParmDefs[j].parmRequired ? "true" : "false";
parmDomainValues = methodParmDefs[j].parmDomainValues;
StringBuffer sb = new StringBuffer();
if (parmDomainValues != null && parmDomainValues.length > 0)
{
for (int k=0; k<parmDomainValues.length; k++)
{
if (k < parmDomainValues.length-1)
{
sb.append(parmDomainValues[k]+",");
} else
{
sb.append(parmDomainValues[k]);
}
}
} else
{
if (sb.length() == 0) sb.append("null");
}
insertMechDefaultMethodParmRow(connection, methodDBID, bMechDBID,
methodParmDefs[j].parmName,
methodParmDefs[j].parmDefaultValue,
sb.toString(),
parmRequired,
methodParmDefs[j].parmLabel,
methodParmDefs[j].parmType);
}
}
for (int j=0; j<dsBindSpec.dsBindRules.length; ++j) {
dsBindingKeyDBID =
lookupDataStreamBindingSpecDBID(connection,
bMechDBID,
dsBindSpec.dsBindRules[j].bindingKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"dsBindSpec "
+ "row doesn't exist for bMechDBID: "
+ bMechDBID + ", binding key name: "
+ dsBindSpec.dsBindRules[j].bindingKeyName);
}
for (int k=0; k<behaviorBindingsEntry.dsBindingKeys.length;
k++)
{
// A row is added to the mechImpl table for each
// method with a different BindingKeyName. In cases where
// a single method may have multiple binding keys,
// multiple rows are added for each different
// BindingKeyName for that method.
if (behaviorBindingsEntry.dsBindingKeys[k].
equalsIgnoreCase(
dsBindSpec.dsBindRules[j].bindingKeyName))
{
insertMechanismImplRow(connection, bMechDBID,
bDefDBID, methodDBID, dsBindingKeyDBID,
"http", "text/html",
// sdp - local.fedora.server conversion
encodeLocalURL(behaviorBindingsEntry.serviceBindingAddress),
encodeLocalURL(behaviorBindingsEntry.operationLocation), "1");
}
}
}
}
connection.commit();
} catch (ReplicationException re) {
re.printStackTrace();
throw re;
} catch (ServerException se) {
se.printStackTrace();
throw new ReplicationException(
"Replication exception caused by ServerException - "
+ se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
/**
* Replicates a Fedora data object.
*
* @param doReader data object reader
* @exception ReplicationException replication processing error
* @exception SQLException JDBC, SQL error
*/
public void replicate(DOReader doReader)
throws ReplicationException, SQLException {
// Do updates only if the object already existed.
boolean componentsUpdated=false;
boolean componentsAdded=false;
boolean componentsPurged=purgeComponents(doReader);
logFinest("DefaultDOReplicator.replicate: ----- componentsPurged: "+componentsPurged);
// Update operations are mutually exclusive
if (!componentsPurged) {
componentsUpdated=updateComponents(doReader);
logFinest("DefaultDOReplicator.replicate: ----- componentsUpdated: "+componentsUpdated);
if (!componentsUpdated) {
// and do adds if the object already existed
componentsAdded=addNewComponents(doReader);
logFinest("DefaultDOReplicator.replicate: ----- newComponentsAdded: "+componentsAdded);
}
}
if ( !componentsUpdated && !componentsAdded && !componentsPurged ) {
// Object is New
Connection connection=null;
logFinest("DefaultDOReplicator.replicate: ----- New Object");
try
{
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
String doLabel;
String dsBindingKeyDBID;
int rc;
doPID = doReader.GetObjectPID();
connection = m_pool.getConnection();
connection.setAutoCommit(false);
// Insert Digital Object row
doPID = doReader.GetObjectPID();
doLabel = doReader.GetObjectLabel();
insertDigitalObjectRow(connection, doPID, doLabel, doReader.GetObjectState());
doDBID = lookupDigitalObjectDBID(connection, doPID);
if (doDBID == null) {
throw new ReplicationException("do row doesn't "
+ "exist for PID: " + doPID);
}
// add disseminator components (which include associated datastream components)
disseminators = doReader.GetDisseminators(null, null);
addDisseminators(doPID, disseminators, doReader, connection);
connection.commit();
} catch (ReplicationException re) {
re.printStackTrace();
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + re.getClass().getName()
+ " \". The cause was \" " + re.getMessage() + " \"");
} catch (ServerException se) {
se.printStackTrace();
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName() + ": " + th.getMessage());
} finally {
connection.setAutoCommit(true);
m_pool.free(connection);
}
}
}
}
}
private ResultSet logAndExecuteQuery(Statement statement, String sql)
throws SQLException {
logFinest("Executing query: " + sql);
return statement.executeQuery(sql);
}
private int logAndExecuteUpdate(Statement statement, String sql)
throws SQLException {
logFinest("Executing update: " + sql);
return statement.executeUpdate(sql);
}
/**
* Gets a string suitable for a SQL WHERE clause, of the form
* <b>x=y1 or x=y2 or x=y3</b>...etc, where x is the value from the
* column, and y1 is composed of the integer values from the given set.
* <p></p>
* If the set doesn't contain any items, returns a condition that
* always evaluates to false, <b>1=2</b>.
*
* @param column value of the column.
* @param integers set of integers.
* @return string suitable for SQL WHERE clause.
*/
private String inIntegerSetWhereConditionString(String column,
Set integers) {
StringBuffer out=new StringBuffer();
Iterator iter=integers.iterator();
int n=0;
while (iter.hasNext()) {
if (n>0) {
out.append(" OR ");
}
out.append(column);
out.append('=');
int i=((Integer) iter.next()).intValue();
out.append(i);
n++;
}
if (n>0) {
return out.toString();
} else {
return "1=2";
}
}
/**
* Deletes all rows pertinent to the given behavior definition object,
* if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $bDefDbID=SELECT bDefDbID FROM bDef WHERE bDefPID=$PID
* DELETE FROM bDef,method,parm
* WHERE bDefDbID=$bDefDbID
* </pre></ul>
*
* @param connection a database connection.
* @param pid the idenitifer of a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteBehaviorDefinition(Connection connection, String pid)
throws SQLException {
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Entering -----");
Statement st=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Checking BehaviorDefinition table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT bDefDbID FROM "
+ "bDef WHERE bDefPID='" + pid + "'");
if (!results.next()) {
// must not be a bdef...exit early
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: " + pid + " wasn't found in BehaviorDefinition table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("bDefDbID");
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: " + pid + " was found in BehaviorDefinition table (DBID="
+ dbid + ")");
//
// WRITE
//
int rowCount;
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Attempting row deletion from BehaviorDefinition "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM bDef "
+ "WHERE bDefDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Attempting row deletion from method table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM method WHERE "
+ "bDefDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Attempting row deletion from parm table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM parm WHERE "
+ "bDefDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Deleted " + rowCount + " row(s).");
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
} catch (SQLException sqle) {
} finally {
results=null;
st=null;
logFinest("DefaultDOReplicator.deleteBehaviorDefinition: Exiting -----");
}
}
}
/**
* Deletes all rows pertinent to the given behavior mechanism object,
* if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $bMechDbID=SELECT bMechDbID
* FROM bMech WHERE bMechPID=$PID
* bMech
* @BKEYIDS=SELECT dsBindKeyDbID
* FROM dsBindSpec
* WHERE bMechDbID=$bMechDbID
* dsMIME WHERE dsBindKeyDbID in @BKEYIDS
* mechImpl
* </pre></ul>
*
* @param connection a database connection.
* @param pid the identifier of a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteBehaviorMechanism(Connection connection, String pid)
throws SQLException {
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Entering -----");
Statement st=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Checking bMech table for " + pid + "...");
//results=logAndExecuteQuery(st, "SELECT bMechDbID, SMType_DBID "
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech WHERE bMechPID='" + pid + "'");
if (!results.next()) {
// must not be a bmech...exit early
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: " + pid + " wasn't found in bMech table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("bMechDbID");
//int smtype_dbid=results.getInt("bMechDbID");
results.close();
results=null;
logFinest("DefaultDOReplicator.deleteBehaviorMechanism:" + pid + " was found in bMech table (DBID="
// + dbid + ", SMTYPE_DBID=" + smtype_dbid + ")");
+ dbid);
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Getting dsBindKeyDbID(s) from dsBindSpec "
+ "table...");
HashSet dsBindingKeyIds=new HashSet();
results=logAndExecuteQuery(st, "SELECT dsBindKeyDbID from "
+ "dsBindSpec WHERE bMechDbID=" + dbid);
while (results.next()) {
dsBindingKeyIds.add(new Integer(
results.getInt("dsBindKeyDbID")));
}
results.close();
results=null;
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Found " + dsBindingKeyIds.size()
+ " dsBindKeyDbID(s).");
//
// WRITE
//
int rowCount;
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from bMech table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM bMech "
+ "WHERE bMechDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from dsBindSpec "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "dsBindSpec WHERE bMechDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from dsMIME table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsMIME WHERE "
+ inIntegerSetWhereConditionString("dsBindKeyDbID",
dsBindingKeyIds));
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s).");
//logFinest("Attempting row deletion from StructMapType table...");
//rowCount=logAndExecuteUpdate(st, "DELETE FROM StructMapType WHERE "
// + "SMType_DBID=" + smtype_dbid);
//logFinest("Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from dsBindMap table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE "
+ "bMechDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from mechImpl table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM mechImpl WHERE "
+ "bMechDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Attempting row deletion from mechDefParm table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM mechDefParm "
+ "WHERE bMechDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Deleted " + rowCount + " row(s).");
} finally {
try {
if (results != null) results.close();
if (st!=null)st.close();
} catch (SQLException sqle) {
} finally {
results=null;
st=null;
logFinest("DefaultDOReplicator.deleteBehaviorMechanism: Exiting -----");
}
}
}
/**
* Deletes all rows pertinent to the given digital object (treated as a
* data object) if they exist.
* <p></p>
* Pseudocode:
* <ul><pre>
* $doDbID=SELECT doDbID FROM do where doPID=$PID
* @DISSIDS=SELECT dissDbID
* FROM doDissAssoc WHERE doDbID=$doDbID
* @BMAPIDS=SELECT dsBindMapDbID
* FROM dsBind WHERE doDbID=$doDbID
* do
* doDissAssoc where $doDbID=doDbID
* dsBind WHERE $doDbID=doDbID
* diss WHERE dissDbID in @DISSIDS
* dsBindMap WHERE dsBindMapDbID in @BMAPIDS
* </pre></ul>
*
* @param connection a databae connection.
* @param pid the identifier for a digital object.
* @throws SQLException If something totally unexpected happened.
*/
private void deleteDigitalObject(Connection connection, String pid)
throws SQLException {
logFinest("DefaultDOReplicator.deleteDigitalObject: Entering -----");
Statement st=null;
Statement st2=null;
Statement st3=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("DefaultDOReplicator.deleteDigitalObject: Checking do table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT doDbID FROM "
+ "do WHERE doPID='" + pid + "'");
if (!results.next()) {
// must not be a digitalobject...exit early
logFinest("DefaultDOReplicator.deleteDigitalObject: " + pid + " wasn't found in do table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("doDbID");
results.close();
results=null;
logFinest("DefaultDOReplicator.deleteDigitalObject: " + pid + " was found in do table (DBID="
+ dbid + ")");
logFinest("DefaultDOReplicator.deleteDigitalObject: Getting dissDbID(s) from doDissAssoc "
+ "table...");
HashSet dissIds=new HashSet();
HashSet dissIdsNotShared = new HashSet();
// Get all dissIds in db for this object
results=logAndExecuteQuery(st, "SELECT dissDbID from "
+ "doDissAssoc WHERE doDbID=" + dbid);
while (results.next()) {
dissIds.add(new Integer(results.getInt("dissDbID")));
}
results.close();
results=null;
logFinest("DefaultDOReplicator.deleteDigitalObject: Found " + dissIds.size() + " dissDbID(s).");
logFinest("DefaultDOReplicator.deleteDigitalObject: Getting dissDbID(s) from doDissAssoc "
+ "table unique to this object...");
Iterator iterator = dissIds.iterator();
// Iterate over dissIds and separate those that are unique
// (i.e., not shared by other objects)
while (iterator.hasNext())
{
Integer id = (Integer)iterator.next();
logFinest("DefaultDOReplicator.deleteDigitalObject: Getting occurrences of dissDbID(s) in "
+ "doDissAssoc table...");
results=logAndExecuteQuery(st, "SELECT COUNT(*) from "
+ "doDissAssoc WHERE dissDbID=" + id);
while (results.next())
{
Integer i1 = new Integer(results.getInt("COUNT(*)"));
if ( i1.intValue() == 1 )
{
// A dissDbID that occurs only once indicates that the
// disseminator is not used by other objects. In this case, we
// want to keep track of this dissDbID.
dissIdsNotShared.add(id);
logFinest("DefaultDOReplicator.deleteDigitalObject: added "
+ "dissDbId that was not shared: " + id);
}
}
results.close();
results=null;
}
// Get all binding map Ids in db for this object.
HashSet bmapIds=new HashSet();
results=logAndExecuteQuery(st, "SELECT dsBindMapDbID FROM "
+ "dsBind WHERE doDbID=" + dbid);
while (results.next()) {
bmapIds.add(new Integer(results.getInt("dsBindMapDbID")));
}
results.close();
results=null;
logFinest("DefaultDOReplicator.deleteDigitalObject: Found " + bmapIds.size() + " dsBindMapDbID(s).");
// Iterate over bmapIds and separate those that are unique
// (i.e., not shared by other objects)
iterator = bmapIds.iterator();
HashSet bmapIdsNotShared = new HashSet();
while (iterator.hasNext() )
{
Integer id = (Integer)iterator.next();
ResultSet rs = null;
logFinest("DefaultDOReplicator.deleteDigitalObject: Getting associated bmapId(s) that are unique "
+ "for this object in diss table...");
st2 = connection.createStatement();
rs=logAndExecuteQuery(st2, "SELECT DISTINCT doDbID FROM "
+ "dsBind WHERE dsBindMapDbID=" + id);
int rowCount = 0;
while (rs.next())
{
rowCount++;
}
if ( rowCount == 1 )
{
// A bmapId that occurs only once indicates that
// a bmapId is not used by other objects. In this case, we
// want to keep track of this bpamId.
bmapIdsNotShared.add(id);
logFinest("DefaultDOReplicator.deleteDigitalObject: added "
+ "dsBindMapDbId that was not shared: " + id);
}
rs.close();
rs=null;
st2.close();
st2=null;
}
//
// WRITE
//
int rowCount;
logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from do table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM do "
+ "WHERE doDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from doDissAssoc "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "doDissAssoc WHERE doDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from dsBind table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind "
+ "WHERE doDbID=" + dbid);
logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s).");
// Since dissIds can be shared by other objects in db, only remove
// those Ids that are not shared.
logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from diss table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE "
+ inIntegerSetWhereConditionString("dissDbID", dissIdsNotShared));
logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s).");
logFinest("DefaultDOReplicator.deleteDigitalObject: Attempting row deletion from dsBindMap "
+ "table...");
// Since bmapIds can be shared by other objects in db, only remove
// thos Ids that are not shared.
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap "
+ "WHERE " + inIntegerSetWhereConditionString(
"dsBindMapDbID", bmapIdsNotShared));
logFinest("DefaultDOReplicator.deleteDigitalObject: Deleted " + rowCount + " row(s).");
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
if (st2!=null) st2.close();
} catch (SQLException sqle) {
} finally {
results=null;
st=null;
st2=null;
logFinest("DefaultDOReplicator.deleteDigitalObject: Exiting -----");
}
}
}
/**
* Removes a digital object from the dissemination database.
* <p></p>
* If the object is a behavior definition or mechanism, it's deleted
* as such, and then an attempt is made to delete it as a data object
* as well.
* <p></p>
* Note that this does not do cascading check object dependencies at
* all. It is expected at this point that when this is called, any
* referencial integrity issues have been ironed out or checked as
* appropriate.
* <p></p>
* All deletions happen in a transaction. If any database errors occur,
* the change is rolled back.
*
* @param pid The pid of the object to delete.
* @throws ReplicationException If the request couldn't be fulfilled for
* any reason.
*/
public void delete(String pid)
throws ReplicationException {
logFinest("DefaultDOReplicator.delete: Entering -----");
Connection connection=null;
try {
connection = m_pool.getConnection();
connection.setAutoCommit(false);
deleteBehaviorDefinition(connection, pid);
deleteBehaviorMechanism(connection, pid);
deleteDigitalObject(connection, pid);
connection.commit();
} catch (SQLException sqle) {
throw new ReplicationException("Error while replicator was trying "
+ "to delete " + pid + ". " + sqle.getMessage());
} finally {
if (connection!=null) {
try {
connection.rollback();
connection.setAutoCommit(true);
m_pool.free(connection);
} catch (SQLException sqle) {}
}
logFinest("DefaultDOReplicator.delete: Exiting -----");
}
}
/**
*
* Inserts a Behavior Definition row.
*
* @param connection JDBC DBMS connection
* @param bDefPID Behavior definition PID
* @param bDefLabel Behavior definition label
* @param bDefState State of behavior definition object.
*
* @exception SQLException JDBC, SQL error
*/
public void insertBehaviorDefinitionRow(Connection connection, String bDefPID, String bDefLabel, String bDefState) throws SQLException {
String insertionStatement = "INSERT INTO bDef (bDefPID, bDefLabel, bDefState) VALUES ('" + bDefPID + "', '" + SQLUtility.aposEscape(bDefLabel) + "', '" + bDefState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a Behavior Mechanism row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param bMechPID Behavior mechanism DBID
* @param bMechLabel Behavior mechanism label
* @param bMechState Statye of behavior mechanism object.
*
* @throws SQLException JDBC, SQL error
*/
public void insertBehaviorMechanismRow(Connection connection, String bDefDbID, String bMechPID, String bMechLabel, String bMechState) throws SQLException {
String insertionStatement = "INSERT INTO bMech (bDefDbID, bMechPID, bMechLabel, bMechState) VALUES ('" + bDefDbID + "', '" + bMechPID + "', '" + SQLUtility.aposEscape(bMechLabel) + "', '" + bMechState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a DataStreamBindingRow row.
*
* @param connection JDBC DBMS connection
* @param doDbID Digital object DBID
* @param dsBindKeyDbID Datastream binding key DBID
* @param dsBindMapDbID Binding map DBID
* @param dsBindKeySeq Datastream binding key sequence number
* @param dsID Datastream ID
* @param dsLabel Datastream label
* @param dsMIME Datastream mime type
* @param dsLocation Datastream location
* @param dsControlGroupType Datastream type
* @param dsCurrentVersionID Datastream current version ID
* @param policyDbID Policy DBID
* @param dsState State of datastream.
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingRow(Connection connection, String doDbID, String dsBindKeyDbID, String dsBindMapDbID, String dsBindKeySeq, String dsID, String dsLabel, String dsMIME, String dsLocation, String dsControlGroupType, String dsCurrentVersionID, String policyDbID, String dsState) throws SQLException {
if (dsBindKeySeq == null || dsBindKeySeq.equals("")) dsBindKeySeq = "0";
String insertionStatement = "INSERT INTO dsBind (doDbID, dsBindKeyDbID, dsBindMapDbID, dsBindKeySeq, dsID, dsLabel, dsMIME, dsLocation, dsControlGroupType, dsCurrentVersionID, policyDbID, dsState) VALUES ('" + doDbID + "', '" + dsBindKeyDbID + "', '" + dsBindMapDbID + "', '" + dsBindKeySeq + "', '" + dsID + "', '" + SQLUtility.aposEscape(dsLabel) + "', '" + dsMIME + "', '" + SQLUtility.aposEscape(dsLocation) + "', '" + dsControlGroupType + "', '" + dsCurrentVersionID + "', '" + policyDbID + "', '" + dsState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsBindMap row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param dsBindMapID Datastream binding map ID
* @param dsBindMapLabel Datastream binding map label
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingMapRow(Connection connection, String bMechDbID, String dsBindMapID, String dsBindMapLabel) throws SQLException {
String insertionStatement = "INSERT INTO dsBindMap (bMechDbID, dsBindMapID, dsBindMapLabel) VALUES ('" + bMechDbID + "', '" + dsBindMapID + "', '" + SQLUtility.aposEscape(dsBindMapLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsBindSpec row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param dsBindSpecName Datastream binding spec name
* @param dsBindSpecOrdinality Datastream binding spec ordinality flag
* @param dsBindSpecCardinality Datastream binding cardinality
* @param dsBindSpecLabel Datastream binding spec lable
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamBindingSpecRow(Connection connection, String bMechDbID, String dsBindSpecName, String dsBindSpecOrdinality, String dsBindSpecCardinality, String dsBindSpecLabel) throws SQLException {
String insertionStatement = "INSERT INTO dsBindSpec (bMechDbID, dsBindSpecName, dsBindSpecOrdinality, dsBindSpecCardinality, dsBindSpecLabel) VALUES ('" + bMechDbID + "', '" + SQLUtility.aposEscape(dsBindSpecName) + "', '" + dsBindSpecOrdinality + "', '" + dsBindSpecCardinality + "', '" + SQLUtility.aposEscape(dsBindSpecLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a dsMIME row.
*
* @param connection JDBC DBMS connection
* @param dsBindKeyDbID Datastream binding key DBID
* @param dsMIMEName Datastream MIME type name
*
* @exception SQLException JDBC, SQL error
*/
public void insertDataStreamMIMERow(Connection connection, String dsBindKeyDbID, String dsMIMEName) throws SQLException {
String insertionStatement = "INSERT INTO dsMIME (dsBindKeyDbID, dsMIMEName) VALUES ('" + dsBindKeyDbID + "', '" + dsMIMEName + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a do row.
*
* @param connection JDBC DBMS connection
* @param doPID DigitalObject PID
* @param doLabel DigitalObject label
* @param doState State of digital object.
*
* @exception SQLException JDBC, SQL error
*/
public void insertDigitalObjectRow(Connection connection, String doPID, String doLabel, String doState) throws SQLException {
String insertionStatement = "INSERT INTO do (doPID, doLabel, doState) VALUES ('" + doPID + "', '" + SQLUtility.aposEscape(doLabel) + "', '" + doState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a doDissAssoc row.
*
* @param connection JDBC DBMS connection
* @param doDbID DigitalObject DBID
* @param dissDbID Disseminator DBID
*
* @exception SQLException JDBC, SQL error
*/
public void insertDigitalObjectDissAssocRow(Connection connection, String doDbID, String dissDbID) throws SQLException {
String insertionStatement = "INSERT INTO doDissAssoc (doDbID, dissDbID) VALUES ('" + doDbID + "', '" + dissDbID + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a Disseminator row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param bMechDbID Behavior mechanism DBID
* @param dissID Disseminator ID
* @param dissLabel Disseminator label
* @param dissState State of disseminator.
*
* @exception SQLException JDBC, SQL error
*/
public void insertDisseminatorRow(Connection connection, String bDefDbID, String bMechDbID, String dissID, String dissLabel, String dissState) throws SQLException {
String insertionStatement = "INSERT INTO diss (bDefDbID, bMechDbID, dissID, dissLabel, dissState) VALUES ('" + bDefDbID + "', '" + bMechDbID + "', '" + dissID + "', '" + SQLUtility.aposEscape(dissLabel) + "', '" + dissState + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a mechImpl row.
*
* @param connection JDBC DBMS connection
* @param bMechDbID Behavior mechanism DBID
* @param bDefDbID Behavior definition DBID
* @param methodDbID Method DBID
* @param dsBindKeyDbID Datastream binding key DBID
* @param protocolType Mechanism implementation protocol type
* @param returnType Mechanism implementation return type
* @param addressLocation Mechanism implementation address location
* @param operationLocation Mechanism implementation operation location
* @param policyDbID Policy DBID
*
* @exception SQLException JDBC, SQL error
*/
public void insertMechanismImplRow(Connection connection, String bMechDbID, String bDefDbID, String methodDbID, String dsBindKeyDbID, String protocolType, String returnType, String addressLocation, String operationLocation, String policyDbID) throws SQLException {
String insertionStatement = "INSERT INTO mechImpl (bMechDbID, bDefDbID, methodDbID, dsBindKeyDbID, protocolType, returnType, addressLocation, operationLocation, policyDbID) VALUES ('" + bMechDbID + "', '" + bDefDbID + "', '" + methodDbID + "', '" + dsBindKeyDbID + "', '" + protocolType + "', '" + returnType + "', '" + addressLocation + "', '" + operationLocation + "', '" + policyDbID + "')";
insertGen(connection, insertionStatement);
}
/**
*
* Inserts a method row.
*
* @param connection JDBC DBMS connection
* @param bDefDbID Behavior definition DBID
* @param methodName Behavior definition label
* @param methodLabel Behavior definition label
*
* @exception SQLException JDBC, SQL error
*/
public void insertMethodRow(Connection connection, String bDefDbID, String methodName, String methodLabel) throws SQLException {
String insertionStatement = "INSERT INTO method (bDefDbID, methodName, methodLabel) VALUES ('" + bDefDbID + "', '" + SQLUtility.aposEscape(methodName) + "', '" + SQLUtility.aposEscape(methodLabel) + "')";
insertGen(connection, insertionStatement);
}
/**
*
* @param connection An SQL Connection.
* @param methDBID The method database ID.
* @param bdefDBID The behavior Definition object database ID.
* @param parmName the parameter name.
* @param parmDefaultValue A default value for the parameter.
* @param parmDomainValues A list of possible values for the parameter.
* @param parmRequiredFlag A boolean flag indicating whether the
* parameter is required or not.
* @param parmLabel The parameter label.
* @param parmType The parameter type.
* @throws SQLException JDBC, SQL error
*/
public void insertMethodParmRow(Connection connection, String methDBID,
String bdefDBID, String parmName, String parmDefaultValue,
String parmDomainValues, String parmRequiredFlag,
String parmLabel, String parmType)
throws SQLException {
String insertionStatement = "INSERT INTO parm "
+ "(methodDbID, bDefDbID, parmName, parmDefaultValue, "
+ "parmDomainValues, parmRequiredFlag, parmLabel, "
+ "parmType) VALUES ('"
+ methDBID + "', '" + bdefDBID + "', '"
+ SQLUtility.aposEscape(parmName) + "', '" + SQLUtility.aposEscape(parmDefaultValue) + "', '"
+ SQLUtility.aposEscape(parmDomainValues) + "', '"
+ parmRequiredFlag + "', '" + SQLUtility.aposEscape(parmLabel) + "', '"
+ parmType + "')";
insertGen(connection, insertionStatement);
}
/**
*
* @param connection An SQL Connection.
* @param methDBID The method database ID.
* @param bmechDBID The behavior Mechanism object database ID.
* @param parmName the parameter name.
* @param parmDefaultValue A default value for the parameter.
* @param parmRequiredFlag A boolean flag indicating whether the
* parameter is required or not.
* @param parmDomainValues A list of possible values for the parameter.
* @param parmLabel The parameter label.
* @param parmType The parameter type.
* @throws SQLException JDBC, SQL error
*/
public void insertMechDefaultMethodParmRow(Connection connection, String methDBID,
String bmechDBID, String parmName, String parmDefaultValue,
String parmDomainValues, String parmRequiredFlag,
String parmLabel, String parmType)
throws SQLException {
String insertionStatement = "INSERT INTO mechDefParm "
+ "(methodDbID, bMechDbID, defParmName, defParmDefaultValue, "
+ "defParmDomainValues, defParmRequiredFlag, defParmLabel, "
+ "defParmType) VALUES ('"
+ methDBID + "', '" + bmechDBID + "', '"
+ SQLUtility.aposEscape(parmName) + "', '" + SQLUtility.aposEscape(parmDefaultValue) + "', '"
+ SQLUtility.aposEscape(parmDomainValues) + "', '"
+ parmRequiredFlag + "', '" + SQLUtility.aposEscape(parmLabel) + "', '"
+ parmType + "')";
insertGen(connection, insertionStatement);
}
/**
*
* General JDBC row insertion method.
*
* @param connection JDBC DBMS connection
* @param insertionStatement SQL row insertion statement
*
* @exception SQLException JDBC, SQL error
*/
public void insertGen(Connection connection, String insertionStatement) throws SQLException {
int rowCount = 0;
Statement statement = null;
statement = connection.createStatement();
logFinest("Doing DB Insert: " + insertionStatement);
rowCount = statement.executeUpdate(insertionStatement);
statement.close();
statement=null;
}
/**
*
* Looks up a BehaviorDefinition DBID.
*
* @param connection JDBC DBMS connection
* @param bDefPID Behavior definition PID
*
* @return The DBID of the specified Behavior Definition row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupBehaviorDefinitionDBID(Connection connection, String bDefPID) throws StorageDeviceException {
return lookupDBID1(connection, "bDefDbID", "bDef", "bDefPID", bDefPID);
}
/**
*
* Looks up a BehaviorMechanism DBID.
*
* @param connection JDBC DBMS connection
* @param bMechPID Behavior mechanism PID
*
* @return The DBID of the specified Behavior Mechanism row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupBehaviorMechanismDBID(Connection connection, String bMechPID) throws StorageDeviceException {
return lookupDBID1(connection, "bMechDbID", "bMech", "bMechPID", bMechPID);
}
/**
*
* Looks up a dsBindMap DBID.
*
* @param connection JDBC DBMS connection
* @param bMechDBID Behavior mechanism DBID
* @param dsBindingMapID Data stream binding map ID
*
* @return The DBID of the specified dsBindMap row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDataStreamBindingMapDBID(Connection connection, String bMechDBID, String dsBindingMapID) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "dsBindMapDbID", "dsBindMap", "bMechDbID", bMechDBID, "dsBindMapID", dsBindingMapID);
}
public String lookupDataStreamBinding(Connection connection, String doDbID, String dsBindKeyDbID, String dsBindMapDbID, String dsBindKeySeq, String dsID, String dsLocation, String dsState) throws StorageDeviceException {
return lookupDBID4(connection, "dsID", "dsBind",
"doDbID", doDbID,
"dsBindKeyDbID", dsBindKeyDbID,
"dsBindMapDbID", dsBindMapDbID,
"dsBindKeySeq", dsBindKeySeq,
"dsID", dsID,
"dsLocation", dsLocation,
"dsState", dsState);
}
//public String lookupDsBindingMapDBID(Connection connection, String bMechDBID, String dsBindingMapID) throws StorageDeviceException {
// return lookupDBID2FirstNum(connection, "dsBindMapDbID", "dsBindMap", "bMechDbID", bMechDBID, "dsBindMapID", dsBindingMapID);
//}
/**
*
* Looks up a dsBindSpec DBID.
*
* @param connection JDBC DBMS connection
* @param bMechDBID Behavior mechanism DBID
* @param dsBindingSpecName Data stream binding spec name
*
* @return The DBID of the specified dsBindSpec row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDataStreamBindingSpecDBID(Connection connection, String bMechDBID, String dsBindingSpecName) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "dsBindKeyDbID", "dsBindSpec", "bMechDbID", bMechDBID, "dsBindSpecName", dsBindingSpecName);
}
/**
*
* Looks up a do DBID.
*
* @param connection JDBC DBMS connection
* @param doPID Data object PID
*
* @return The DBID of the specified DigitalObject row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDigitalObjectDBID(Connection connection, String doPID) throws StorageDeviceException {
return lookupDBID1(connection, "doDbID", "do", "doPID", doPID);
}
/**
*
* Looks up a Disseminator DBID.
*
* @param connection JDBC DBMS connection
* @param bDefDBID Behavior definition DBID
* @param bMechDBID Behavior mechanism DBID
* @param dissID Disseminator ID
*
* @return The DBID of the specified Disseminator row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDisseminatorDBID(Connection connection, String bDefDBID, String bMechDBID, String dissID) throws StorageDeviceException {
Statement statement = null;
ResultSet rs = null;
String query = null;
String ID = null;
try
{
query = "SELECT dissDbID FROM diss WHERE ";
query += "bDefDbID = " + bDefDBID + " AND ";
query += "bMechDbID = " + bMechDBID + " AND ";
query += "dissID = '" + dissID + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
} finally {
rs=null;
statement=null;
}
}
return ID;
}
/**
*
* Looks up a method DBID.
*
* @param connection JDBC DBMS connection
* @param bDefDBID Behavior definition DBID
* @param methName Method name
*
* @return The DBID of the specified method row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupMethodDBID(Connection connection, String bDefDBID, String methName) throws StorageDeviceException {
return lookupDBID2FirstNum(connection, "methodDbID", "method", "bDefDbID", bDefDBID, "methodName", methName);
}
/**
*
* General JDBC lookup method with 1 lookup column value.
*
* @param connection JDBC DBMS connection
* @param DBIDName DBID column name
* @param tableName Table name
* @param lookupColumnName Lookup column name
* @param lookupColumnValue Lookup column value
*
* @return The DBID of the specified row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDBID1(Connection connection, String DBIDName, String tableName, String lookupColumnName, String lookupColumnValue) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName + " = '" + lookupColumnValue + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
} finally {
rs=null;
statement=null;
}
}
return ID;
}
/**
*
* General JDBC lookup method with 2 lookup column values.
*
* @param connection JDBC DBMS connection
* @param DBIDName DBID Column name
* @param tableName Table name
* @param lookupColumnName1 First lookup column name
* @param lookupColumnValue1 First lookup column value
* @param lookupColumnName2 Second lookup column name
* @param lookupColumnValue2 Second lookup column value
*
* @return The DBID of the specified row.
*
* @throws StorageDeviceException if db lookup fails for any reason.
*/
public String lookupDBID2(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName1 + " = '" + lookupColumnValue1 + "' AND ";
query += lookupColumnName2 + " = '" + lookupColumnValue2 + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
} finally {
rs=null;
statement=null;
}
}
return ID;
}
public String lookupDBID4(Connection connection, String DBIDName, String tableName,
String lookupColumnName1, String lookupColumnValue1,
String lookupColumnName2, String lookupColumnValue2,
String lookupColumnName3, String lookupColumnValue3,
String lookupColumnName4, String lookupColumnValue4,
String lookupColumnName5, String lookupColumnValue5,
String lookupColumnName6, String lookupColumnValue6,
String lookupColumnName7, String lookupColumnValue7) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName1 + " =" + lookupColumnValue1 + " AND ";
query += lookupColumnName2 + " =" + lookupColumnValue2 + " AND ";
query += lookupColumnName3 + " =" + lookupColumnValue3 + " AND ";
query += lookupColumnName4 + " =" + lookupColumnValue4 + " AND ";
query += lookupColumnName5 + " ='" + lookupColumnValue5 + "' AND ";
query += lookupColumnName6 + " ='" + lookupColumnValue6 + "' AND ";
query += lookupColumnName7 + " ='" + lookupColumnValue7 + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
} finally {
rs=null;
statement=null;
}
}
return ID;
}
public String lookupDBID2FirstNum(Connection connection, String DBIDName, String tableName, String lookupColumnName1, String lookupColumnValue1, String lookupColumnName2, String lookupColumnValue2) throws StorageDeviceException {
String query = null;
String ID = null;
Statement statement = null;
ResultSet rs = null;
try
{
query = "SELECT " + DBIDName + " FROM " + tableName + " WHERE ";
query += lookupColumnName1 + " =" + lookupColumnValue1 + " AND ";
query += lookupColumnName2 + " = '" + lookupColumnValue2 + "'";
logFinest("Doing Query: " + query);
statement = connection.createStatement();
rs = statement.executeQuery(query);
while (rs.next())
ID = rs.getString(1);
} catch (Throwable th)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + th.getClass().getName()
+ " \". The cause was \" " + th.getMessage() + " \"");
} finally
{
try
{
if (rs != null) rs.close();
if (statement != null) statement.close();
} catch (SQLException sqle)
{
throw new StorageDeviceException("[DBIDLookup] An error has "
+ "occurred. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage() + " \"");
} finally {
rs=null;
statement=null;
}
}
return ID;
}
private String encodeLocalURL(String locationString)
{
// Replace any occurences of the host:port of the local Fedora
// server with the internal serialization string "local.fedora.server."
// This will make sure that local URLs (self-referential to the
// local server) will be recognizable if the server host and
// port configuration changes after an object is stored in the
// repository.
if (fedoraServerPort.equalsIgnoreCase("80") &&
hostPattern.matcher(locationString).find())
{
//System.out.println("port is 80 and host-only pattern found - convert to l.f.s");
return hostPattern.matcher(
locationString).replaceAll("http://local.fedora.server/");
}
else
{
//System.out.println("looking for hostPort pattern to convert to l.f.s");
return hostPortPattern.matcher(
locationString).replaceAll("http://local.fedora.server/");
}
}
private String unencodeLocalURL(String storedLocationString)
{
// Replace any occurrences of the internal serialization string
// "local.fedora.server" with the current host and port of the
// local Fedora server. This translates local URLs (self-referential
// to the local server) back into resolvable URLs that reflect
// the currently configured host and port for the server.
if (fedoraServerPort.equalsIgnoreCase("80"))
{
return serializedLocalURLPattern.matcher(
storedLocationString).replaceAll(fedoraServerHost);
}
else
{
return serializedLocalURLPattern.matcher(
storedLocationString).replaceAll(
fedoraServerHost+":"+fedoraServerPort);
}
}
private void addDisseminators(String doPID, Disseminator[] disseminators, DOReader doReader, Connection connection)
throws ReplicationException, SQLException, ServerException
{
DSBindingMapAugmented[] allBindingMaps;
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doLabel;
String dsBindingKeyDBID;
int rc;
logFinest("DefaultDOReplicator.addDisseminators: Entering ------");
doDBID = lookupDigitalObjectDBID(connection, doPID);
for (int i=0; i<disseminators.length; ++i) {
bDefDBID = lookupBehaviorDefinitionDBID(connection,
disseminators[i].bDefID);
if (bDefDBID == null) {
throw new ReplicationException("BehaviorDefinition row "
+ "doesn't exist for PID: "
+ disseminators[i].bDefID);
}
bMechDBID = lookupBehaviorMechanismDBID(connection,
disseminators[i].bMechID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ disseminators[i].bMechID);
}
// Insert Disseminator row if it doesn't exist.
dissDBID = lookupDisseminatorDBID(connection, bDefDBID,
bMechDBID, disseminators[i].dissID);
if (dissDBID == null) {
// Disseminator row doesn't exist, add it.
insertDisseminatorRow(connection, bDefDBID, bMechDBID,
disseminators[i].dissID, disseminators[i].dissLabel, disseminators[i].dissState);
//insertDisseminatorRow(connection, bDefDBID, bMechDBID,
//disseminators[i].dissID, disseminators[i].dissLabel, disseminators[i].dissState, disseminators[i].dsBindMapID);
dissDBID = lookupDisseminatorDBID(connection, bDefDBID,
bMechDBID, disseminators[i].dissID);
if (dissDBID == null) {
throw new ReplicationException("diss row "
+ "doesn't exist for PID: "
+ disseminators[i].dissID);
}
}
// Insert doDissAssoc row
insertDigitalObjectDissAssocRow(connection, doDBID,
dissDBID);
}
allBindingMaps = doReader.GetDSBindingMaps(null);
for (int i=0; i<allBindingMaps.length; ++i) {
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length; ++j) {
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i
+ " j=" + j);
}
// Insert DataStreamBinding row
Datastream ds = doReader.getDatastream(allBindingMaps[i].dsBindingsAugmented[j].datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID);
// Add binding only if it does not exist.
logFinest("DefaultDOReplicator.addDisseminators: ----- adding dsBind row: "
+allBindingMaps[i].dsBindingsAugmented[j].datastreamID);
insertDataStreamBindingRow(connection, doDBID,
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
ds.DSState);
}
}
return;
}
/**
* <p> Permanently removes a disseminator from the database incuding
* all associated datastream bindings and datastream binding maps.
* Associated entries are removed from the following db tables:</p>
* <ul>
* <li>doDissAssoc - all entries matching pid of data object.</li>
* <li>diss - all entries matching disseminator ID provided that no
* other objects depend on this disseminator.</li>
* <li>dsBind - all entries matching pid of data object.</li>
* <li>dsBindMap - all entries matching associated bMech object pid
* provided that no other objects depend on this binding map.</li>
* </ul>
* @param pid Persistent identifier for the data object.
* @param dissIds Set of disseminator IDs to be removed.
* @param doReader An instance of DOReader.
* @param connection A database connection.
* @throws SQLException If something totally unexpected happened.
*/
private void purgeDisseminators(String pid, HashSet dissIds, HashSet bmapIds, DOReader doReader, Connection connection)
throws SQLException
{
logFinest("DefaultDOReplicator.purgeDisseminators: Entering ------");
Statement st=null;
Statement st2=null;
ResultSet results=null;
try {
st=connection.createStatement();
//
// READ
//
logFinest("DefaultDOReplicator.purgeDisseminators: Checking do table for " + pid + "...");
results=logAndExecuteQuery(st, "SELECT doDbID FROM "
+ "do WHERE doPID='" + pid + "'");
if (!results.next()) {
// must not be a digitalobject...exit early
logFinest("DefaultDOReplicator.purgeDisseminators: " + pid + " wasn't found in do table..."
+ "skipping deletion as such.");
return;
}
int dbid=results.getInt("doDbID");
results.close();
results=null;
logFinest("DefaultDOReplicator.purgeDisseminators: " + pid + " was found in do table (DBID="
+ dbid + ")");
logFinest("DefaultDOReplicator.purgeDisseminators: Getting dissDbID(s) from doDissAssoc "
+ "table...");
HashSet dissIdsNotShared = new HashSet();
logFinest("DefaultDOReplicator.purgeDisseminators: Getting dissDbID(s) from doDissAssoc "
+ "table unique to this object...");
logFinest("DefaultDOReplicator.purgeDisseminators: Found "
+ dissIds.size() + " dissDbId(s). ");
// Iterate over dissIds and separate those that are unique
// (i.e., not shared by other objects)
Iterator iterator = dissIds.iterator();
while (iterator.hasNext())
{
Integer id = (Integer)iterator.next();
logFinest("DefaultDOReplicator.purgeDisseminators: Getting occurrences of dissDbID(s) in "
+ "doDissAssoc table...");
results=logAndExecuteQuery(st, "SELECT COUNT(*) from "
+ "doDissAssoc WHERE dissDbID=" + id);
while (results.next())
{
Integer i1 = new Integer(results.getInt("COUNT(*)"));
if ( i1.intValue() == 1 )
{
// A dissDbID that occurs only once indicates that the
// disseminator is not used by other objects. In this case,
// we want to keep track of this dissDbID.
dissIdsNotShared.add(id);
}
}
results.close();
results=null;
}
// Iterate over bmapIds and separate those that are unique
// (i.e., not shared by other objects)
logFinest("DefaultDOReplicator.purgeDisseminators: Found "
+ bmapIds.size() + " dsBindMapDbId(s). ");
iterator = bmapIds.iterator();
HashSet bmapIdsInUse = new HashSet();
HashSet bmapIdsShared = new HashSet();
HashSet bmapIdsNotShared = new HashSet();
while (iterator.hasNext() )
{
Integer id = (Integer)iterator.next();
ResultSet rs = null;
logFinest("DefaultDOReplicator.purgeDisseminators: Getting associated bmapId(s) that are unique "
+ "for this object in diss table...");
st2 = connection.createStatement();
rs=logAndExecuteQuery(st2, "SELECT DISTINCT doDbID FROM "
+ "dsBind WHERE dsBindMapDbID=" + id);
int rowCount = 0;
while (rs.next())
{
rowCount++;
}
if ( rowCount == 1 )
{
// A dsBindMapDbId that occurs only once indicates that
// the dsBindMapId is not used by other objects. In this case,
// we want to keep track of this dsBindMapDbId.
bmapIdsNotShared.add(id);
}
rs.close();
rs=null;
st2.close();
st2=null;
}
//
// WRITE
//
int rowCount;
// In doDissAssoc table, we are removing rows specific to the
// doDbId, so remove all dissDbIds (both shared and nonShared).
logFinest("DefaultDOReplicator.purgeDisseminators: Attempting row deletion from doDissAssoc "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM "
+ "doDissAssoc WHERE doDbID=" + dbid
+ " AND ( " + inIntegerSetWhereConditionString("dissDbID", dissIds) + " )");
logFinest("DefaultDOReplicator.purgeDisseminators: Deleted " + rowCount + " row(s).");
// In dsBind table, we are removing rows specific to the doDbID,
// so remove all dsBindMapIds (both shared and nonShared).
logFinest("DefaultDOReplicator.purgeDisseminators: Attempting row deletion from dsBind table..");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBind "
+ "WHERE doDbID=" + dbid
+ " AND ( " + inIntegerSetWhereConditionString("dsBindMapDbID", bmapIds) + " )");
// In diss table, dissDbIds can be shared by other objects so only
// remove dissDbIds that are not shared.
logFinest("DefaultDOReplicator.purgeDisseminators: Attempting row deletion from diss table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM diss WHERE "
+ inIntegerSetWhereConditionString("dissDbID", dissIdsNotShared));
logFinest("DefaultDOReplicator.purgeDisseminators: Deleted " + rowCount + " row(s).");
// In dsBindMap table, dsBindMapIds can be shared by other objects
// so only remove dsBindMapIds that are not shared.
logFinest("DefaultDOReplicator.purgeDisseminators: Attempting row deletion from dsBindMap "
+ "table...");
rowCount=logAndExecuteUpdate(st, "DELETE FROM dsBindMap "
+ "WHERE " + inIntegerSetWhereConditionString(
"dsBindMapDbID", bmapIdsNotShared));
logFinest("DefaultDOReplicator.purgeDisseminators: Deleted " + rowCount + " row(s).");
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
if (st2!=null) st2.close();
} catch (SQLException sqle) {
} finally {
results=null;
st=null;
st2=null;
logFinest("DefaultDOReplicator.purgeDisseminators: Exiting ------");
}
}
}
}
| true | true | private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
logFinest("DefaultDOReplicator.updateComponents: Entering ------");
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// Get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID,doState,doLabel FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
String doState=results.getString("doState");
String doLabel=results.getString("doLabel");
results.close();
results=null;
ArrayList updates=new ArrayList();
// Check if state has changed for the digital object.
String objState = reader.GetObjectState();
if (!doState.equalsIgnoreCase(objState)) {
updates.add("UPDATE do SET doState='" + objState + "' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET objectState='" + objState + "' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// Check if label has changed for the digital object.
String objLabel = reader.GetObjectLabel();
if (!doLabel.equalsIgnoreCase(objLabel)) {
updates.add("UPDATE do SET doLabel='" + objLabel + "' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET label='" + objLabel + "' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
results=null;
// Do any required updates via a transaction.
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("DefaultDOReplication.updateComponents: "
+ "No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID);
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
if (dissDbIDs.size()==0 || reader.GetDisseminators(null, null).length!=dissDbIDs.size()) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "either has no disseminators or a new disseminator"
+ "has been added; components dont need updating.");
return false;
}
results.close();
results=null;
// Iterate over disseminators to check if any have been modified
Iterator dissIter = dissDbIDs.iterator();
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
// Get disseminator info for this disseminator.
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
results=null;
// Compare the latest version of the disseminator with what's in the db...
// Replace what's in db if they are different.
Disseminator diss=reader.GetDisseminator(dissID, null);
if (diss == null) {
// XML object has no disseminators
// so this must be a purgeComponents or a new object.
logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators");
return false;
}
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
if (!diss.dissLabel.equals(dissLabel))
logFinest("DefaultDOReplicator.updateComponents: dissLabel changed from '" + dissLabel + "' to '"
+ diss.dissLabel + "'");
if (!diss.dissState.equals(dissState))
logFinest("DefaultDOReplicator.updateComponents: dissState changed from '" + dissState + "' to '"
+ diss.dissState + "'");
// We might need to set the bMechDbID to the id for the new one,
// if the mechanism changed.
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
logFinest("DefaultDOReplicator.updateComponents: bMechPID changed from '" + bMechPID + "' to '"
+ diss.bMechID + "'");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
results=null;
}
// Update the diss table with all new, correct values.
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
+ "dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID
+ " AND bMechDbID=" + bMechDbID);
}
// Compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different.
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID);
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
results=null;
String newDSBindMapID=diss.dsBindMapID;
logFinest("DefaultDOReplicator.updateComponents: newDSBindMapID: "
+ newDSBindMapID + " origDSBindMapID: " + origDSBindMapID);
// Is this a new bindingMap?
if (!newDSBindMapID.equals(origDSBindMapID)) {
// Yes, dsBindingMap was modified so remove original bindingMap and datastreams.
// BindingMaps can be shared by other objects so first check to see if
// the orignial bindingMap is bound to datastreams of any other objects.
Statement st2 = connection.createStatement();
results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbId,dsBindMapDbId FROM dsBind WHERE dsBindMapDbId="+origDSBindMapDbID);
int numRows = 0;
while (results.next()) {
numRows++;
}
st2.close();
st2=null;
results.close();
results=null;
// Remove all datastreams for this binding map.
// If anything has changed, they will all be added back
// shortly from the current binding info the xml object.
String dsBindMapDBID = null;
dsBindMapDBID = lookupDataStreamBindingMapDBID(connection, (new Integer(bMechDbID)).toString(), origDSBindMapID);
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID
+ " AND dsBindMapDbID="+dsBindMapDBID);
logFinest("DefaultDOReplicator.updateComponents: deleted "
+ rowCount + " rows from dsBind");
// Is bindingMap shared?
if(numRows == 1) {
// No, the bindingMap is NOT shared by any other objects and can be removed.
rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID="
+ origDSBindMapDbID);
logFinest("DefaultDOReplicator.updateComponents: deleted "
+ rowCount + " rows from dsBindMapDbID");
} else {
//Yes, the bindingMap IS shared by other objects so leave bindingMap untouched.
logFinest("DefaultDOReplicator.updateComponents: dsBindMapID: "
+ origDSBindMapID + " is shared by other objects; it will NOT be deleted");
}
// Now add back new datastreams and dsBindMap associated with this disseminator
// using current info in xml object.
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
//String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
logFinest("DefaultDOReplicator.updateComponents: Bindings found: "+allBindingMaps.length);
for (int i=0; i<allBindingMaps.length; ++i) {
// Only update bindingMap that was modified.
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
logFinest("DefaultDOReplicator.updateComponents: "
+ "Adding back datastreams and ds binding map. New dsBindMapID: "
+ newDSBindMapID);
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Now insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
logFinest("DefaultDOReplicator.updateComponents: ADDing dsBindMap row");
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
// Now add back datastream bindings removed earlier.
logFinest("DefaultDOReplicator.updateComponents: Bindings found: "
+ allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length; ++j) {
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i + " j=" + j);
}
// Insert DataStreamBinding row
logFinest("DefaultDOReplicator.updateComponents: Adding back dsBind row for: "
+allBindingMaps[i].dsBindingsAugmented[j].datastreamID);
Datastream ds = reader.getDatastream(allBindingMaps[i].dsBindingsAugmented[j].datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID);
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
ds.DSState);
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
if (connection!=null) m_pool.free(connection);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
results=null;
st=null;
}
}
}
}
logFinest("DefaultDOReplicator.updateComponents: Exiting ------");
return true;
}
| private boolean updateComponents(DOReader reader)
throws ReplicationException {
Connection connection=null;
Statement st=null;
ResultSet results=null;
boolean triedUpdate=false;
boolean failed=false;
logFinest("DefaultDOReplicator.updateComponents: Entering ------");
try {
connection=m_pool.getConnection();
st=connection.createStatement();
// Get db ID for the digital object
results=logAndExecuteQuery(st, "SELECT doDbID,doState,doLabel FROM do WHERE "
+ "doPID='" + reader.GetObjectPID() + "'");
if (!results.next()) {
logFinest("DefaultDOReplication.updateComponents: Object is "
+ "new; components dont need updating.");
return false;
}
int doDbID=results.getInt("doDbID");
String doState=results.getString("doState");
String doLabel=results.getString("doLabel");
results.close();
results=null;
ArrayList updates=new ArrayList();
// Check if state has changed for the digital object.
String objState = reader.GetObjectState();
if (!doState.equalsIgnoreCase(objState)) {
updates.add("UPDATE do SET doState='" + objState + "' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET objectState='" + objState + "' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// Check if label has changed for the digital object.
String objLabel = reader.GetObjectLabel();
if (!doLabel.equalsIgnoreCase(objLabel)) {
updates.add("UPDATE do SET doLabel='" + objLabel + "' WHERE doDbID=" + doDbID);
updates.add("UPDATE doRegistry SET label='" + objLabel + "' WHERE doPID='" + reader.GetObjectPID() + "'");
}
// check if any mods to datastreams for this digital object
results=logAndExecuteQuery(st, "SELECT dsID, dsLabel, dsLocation, dsCurrentVersionID, dsState "
+ "FROM dsBind WHERE doDbID=" + doDbID);
while (results.next()) {
String dsID=results.getString("dsID");
String dsLabel=results.getString("dsLabel");
String dsCurrentVersionID=results.getString("dsCurrentVersionID");
String dsState=results.getString("dsState");
// sdp - local.fedora.server conversion
String dsLocation=unencodeLocalURL(results.getString("dsLocation"));
// compare the latest version of the datastream to what's in the db...
// if different, add to update list
Datastream ds=reader.GetDatastream(dsID, null);
if (!ds.DSLabel.equals(dsLabel)
|| !ds.DSLocation.equals(dsLocation)
|| !ds.DSVersionID.equals(dsCurrentVersionID)
|| !ds.DSState.equals(dsState)) {
updates.add("UPDATE dsBind SET dsLabel='"
+ SQLUtility.aposEscape(ds.DSLabel) + "', dsLocation='"
// sdp - local.fedora.server conversion
+ SQLUtility.aposEscape(encodeLocalURL(ds.DSLocation))
+ "', dsCurrentVersionID='" + ds.DSVersionID + "', "
+ "dsState='" + ds.DSState + "' "
+ " WHERE doDbID=" + doDbID + " AND dsID='" + dsID + "'");
}
}
results.close();
results=null;
// Do any required updates via a transaction.
if (updates.size()>0) {
connection.setAutoCommit(false);
triedUpdate=true;
for (int i=0; i<updates.size(); i++) {
String update=(String) updates.get(i);
logAndExecuteUpdate(st, update);
}
connection.commit();
} else {
logFinest("DefaultDOReplication.updateComponents: "
+ "No datastream labels or locations changed.");
}
// check if any mods to disseminators for this object...
// first get a list of disseminator db IDs
results=logAndExecuteQuery(st, "SELECT dissDbID FROM doDissAssoc WHERE "
+ "doDbID="+doDbID);
HashSet dissDbIDs = new HashSet();
while (results.next()) {
dissDbIDs.add(new Integer(results.getInt("dissDbID")));
}
if (dissDbIDs.size()==0 || reader.GetDisseminators(null, null).length!=dissDbIDs.size()) {
logFinest("DefaultDOReplication.updateComponents: Object "
+ "either has no disseminators or a new disseminator"
+ "has been added; components dont need updating.");
return false;
}
results.close();
results=null;
// Iterate over disseminators to check if any have been modified
Iterator dissIter = dissDbIDs.iterator();
while(dissIter.hasNext()) {
Integer dissDbID = (Integer) dissIter.next();
// Get disseminator info for this disseminator.
results=logAndExecuteQuery(st, "SELECT diss.bDefDbID, diss.bMechDbID, bMech.bMechPID, diss.dissID, diss.dissLabel, diss.dissState "
+ "FROM diss,bMech WHERE bMech.bMechDbID=diss.bMechDbID AND diss.dissDbID=" + dissDbID);
updates=new ArrayList();
int bDefDbID = 0;
int bMechDbID = 0;
String dissID=null;
String dissLabel=null;
String dissState=null;
String bMechPID=null;
while(results.next()) {
bDefDbID = results.getInt("bDefDbID");
bMechDbID = results.getInt("bMechDbID");
dissID=results.getString("dissID");
dissLabel=results.getString("dissLabel");
dissState=results.getString("dissState");
bMechPID=results.getString("bMechPID");
}
results.close();
results=null;
// Compare the latest version of the disseminator with what's in the db...
// Replace what's in db if they are different.
Disseminator diss=reader.GetDisseminator(dissID, null);
if (diss == null) {
// XML object has no disseminators
// so this must be a purgeComponents or a new object.
logFinest("DefaultDOReplicator.updateComponents: XML object has no disseminators");
return false;
}
if (!diss.dissLabel.equals(dissLabel)
|| !diss.bMechID.equals(bMechPID)
|| !diss.dissState.equals(dissState)) {
if (!diss.dissLabel.equals(dissLabel))
logFinest("DefaultDOReplicator.updateComponents: dissLabel changed from '" + dissLabel + "' to '"
+ diss.dissLabel + "'");
if (!diss.dissState.equals(dissState))
logFinest("DefaultDOReplicator.updateComponents: dissState changed from '" + dissState + "' to '"
+ diss.dissState + "'");
// We might need to set the bMechDbID to the id for the new one,
// if the mechanism changed.
int newBMechDbID;
if (diss.bMechID.equals(bMechPID)) {
newBMechDbID=bMechDbID;
} else {
logFinest("DefaultDOReplicator.updateComponents: bMechPID changed from '" + bMechPID + "' to '"
+ diss.bMechID + "'");
results=logAndExecuteQuery(st, "SELECT bMechDbID "
+ "FROM bMech "
+ "WHERE bMechPID='"
+ diss.bMechID + "'");
if (!results.next()) {
// shouldn't have gotten this far, but if so...
throw new ReplicationException("The behavior mechanism "
+ "changed to " + diss.bMechID + ", but there is no "
+ "record of that object in the dissemination db.");
}
newBMechDbID=results.getInt("bMechDbID");
results.close();
results=null;
}
// Update the diss table with all new, correct values.
logAndExecuteUpdate(st, "UPDATE diss SET dissLabel='"
+ SQLUtility.aposEscape(diss.dissLabel)
+ "', bMechDbID=" + newBMechDbID + ", "
+ "dissID='" + diss.dissID + "', "
+ "dissState='" + diss.dissState + "' "
+ " WHERE dissDbID=" + dissDbID + " AND bDefDbID=" + bDefDbID
+ " AND bMechDbID=" + bMechDbID);
}
// Compare the latest version of the disseminator's bindMap with what's in the db
// and replace what's in db if they are different.
results=logAndExecuteQuery(st, "SELECT DISTINCT dsBindMap.dsBindMapID,dsBindMap.dsBindMapDbID FROM dsBind,dsBindMap WHERE "
+ "dsBind.doDbID=" + doDbID + " AND dsBindMap.dsBindMapDbID=dsBind.dsBindMapDbID "
+ "AND dsBindMap.bMechDbID="+bMechDbID);
String origDSBindMapID=null;
int origDSBindMapDbID=0;
while (results.next()) {
origDSBindMapID=results.getString("dsBindMapID");
origDSBindMapDbID=results.getInt("dsBindMapDbID");
}
results.close();
results=null;
String newDSBindMapID=diss.dsBindMapID;
logFinest("DefaultDOReplicator.updateComponents: newDSBindMapID: "
+ newDSBindMapID + " origDSBindMapID: " + origDSBindMapID);
// Is this a new bindingMap?
if (!newDSBindMapID.equals(origDSBindMapID)) {
// Yes, dsBindingMap was modified so remove original bindingMap and datastreams.
// BindingMaps can be shared by other objects so first check to see if
// the orignial bindingMap is bound to datastreams of any other objects.
Statement st2 = connection.createStatement();
results=logAndExecuteQuery(st2,"SELECT DISTINCT doDbID,dsBindMapDbID FROM dsBind WHERE dsBindMapDbID="+origDSBindMapDbID);
int numRows = 0;
while (results.next()) {
numRows++;
}
st2.close();
st2=null;
results.close();
results=null;
// Remove all datastreams for this binding map.
// If anything has changed, they will all be added back
// shortly from the current binding info the xml object.
String dsBindMapDBID = null;
dsBindMapDBID = lookupDataStreamBindingMapDBID(connection, (new Integer(bMechDbID)).toString(), origDSBindMapID);
int rowCount = logAndExecuteUpdate(st,"DELETE FROM dsBind WHERE doDbID=" + doDbID
+ " AND dsBindMapDbID="+dsBindMapDBID);
logFinest("DefaultDOReplicator.updateComponents: deleted "
+ rowCount + " rows from dsBind");
// Is bindingMap shared?
if(numRows == 1) {
// No, the bindingMap is NOT shared by any other objects and can be removed.
rowCount = logAndExecuteUpdate(st, "DELETE FROM dsBindMap WHERE dsBindMapDbID="
+ origDSBindMapDbID);
logFinest("DefaultDOReplicator.updateComponents: deleted "
+ rowCount + " rows from dsBindMapDbID");
} else {
//Yes, the bindingMap IS shared by other objects so leave bindingMap untouched.
logFinest("DefaultDOReplicator.updateComponents: dsBindMapID: "
+ origDSBindMapID + " is shared by other objects; it will NOT be deleted");
}
// Now add back new datastreams and dsBindMap associated with this disseminator
// using current info in xml object.
DSBindingMapAugmented[] allBindingMaps;
Disseminator disseminators[];
String bDefDBID;
String bindingMapDBID;
String bMechDBID;
String dissDBID;
String doDBID;
String doPID;
//String doLabel;
String dsBindingKeyDBID;
allBindingMaps = reader.GetDSBindingMaps(null);
logFinest("DefaultDOReplicator.updateComponents: Bindings found: "+allBindingMaps.length);
for (int i=0; i<allBindingMaps.length; ++i) {
// Only update bindingMap that was modified.
if (allBindingMaps[i].dsBindMapID.equals(newDSBindMapID)) {
logFinest("DefaultDOReplicator.updateComponents: "
+ "Adding back datastreams and ds binding map. New dsBindMapID: "
+ newDSBindMapID);
bMechDBID = lookupBehaviorMechanismDBID(connection,
allBindingMaps[i].dsBindMechanismPID);
if (bMechDBID == null) {
throw new ReplicationException("BehaviorMechanism row "
+ "doesn't exist for PID: "
+ allBindingMaps[i].dsBindMechanismPID);
}
// Now insert dsBindMap row if it doesn't exist.
bindingMapDBID = lookupDataStreamBindingMapDBID(connection,
bMechDBID, allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
logFinest("DefaultDOReplicator.updateComponents: ADDing dsBindMap row");
// DataStreamBinding row doesn't exist, add it.
insertDataStreamBindingMapRow(connection, bMechDBID,
allBindingMaps[i].dsBindMapID,
allBindingMaps[i].dsBindMapLabel);
bindingMapDBID = lookupDataStreamBindingMapDBID(
connection,bMechDBID,allBindingMaps[i].dsBindMapID);
if (bindingMapDBID == null) {
throw new ReplicationException(
"lookupdsBindMapDBID row "
+ "doesn't exist for bMechDBID: " + bMechDBID
+ ", dsBindingMapID: "
+ allBindingMaps[i].dsBindMapID);
}
}
// Now add back datastream bindings removed earlier.
logFinest("DefaultDOReplicator.updateComponents: Bindings found: "
+ allBindingMaps[i].dsBindingsAugmented.length);
for (int j=0; j<allBindingMaps[i].dsBindingsAugmented.length; ++j) {
dsBindingKeyDBID = lookupDataStreamBindingSpecDBID(
connection, bMechDBID,
allBindingMaps[i].dsBindingsAugmented[j].
bindKeyName);
if (dsBindingKeyDBID == null) {
throw new ReplicationException(
"lookupDataStreamBindingDBID row doesn't "
+ "exist for bMechDBID: " + bMechDBID
+ ", bindKeyName: " + allBindingMaps[i].
dsBindingsAugmented[j].bindKeyName + "i=" + i + " j=" + j);
}
// Insert DataStreamBinding row
logFinest("DefaultDOReplicator.updateComponents: Adding back dsBind row for: "
+allBindingMaps[i].dsBindingsAugmented[j].datastreamID);
Datastream ds = reader.getDatastream(allBindingMaps[i].dsBindingsAugmented[j].datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID);
insertDataStreamBindingRow(connection, new Integer(doDbID).toString(),
dsBindingKeyDBID,
bindingMapDBID,
allBindingMaps[i].dsBindingsAugmented[j].seqNo,
allBindingMaps[i].dsBindingsAugmented[j].datastreamID,
allBindingMaps[i].dsBindingsAugmented[j].DSLabel,
allBindingMaps[i].dsBindingsAugmented[j].DSMIME,
// sdp - local.fedora.server conversion
encodeLocalURL(allBindingMaps[i].dsBindingsAugmented[j].DSLocation),
allBindingMaps[i].dsBindingsAugmented[j].DSControlGrp,
allBindingMaps[i].dsBindingsAugmented[j].DSVersionID,
"1",
ds.DSState);
}
}
}
}
}
} catch (SQLException sqle) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + sqle.getClass().getName()
+ " \". The cause was \" " + sqle.getMessage());
} catch (ServerException se) {
failed=true;
throw new ReplicationException("An error has occurred during "
+ "Replication. The error was \" " + se.getClass().getName()
+ " \". The cause was \" " + se.getMessage());
} catch (Exception e) {
e.printStackTrace();
} finally {
if (connection!=null) {
try {
if (triedUpdate && failed) connection.rollback();
} catch (Throwable th) {
logWarning("While rolling back: " + th.getClass().getName()
+ ": " + th.getMessage());
} finally {
try {
if (results != null) results.close();
if (st!=null) st.close();
connection.setAutoCommit(true);
if (connection!=null) m_pool.free(connection);
} catch (SQLException sqle) {
logWarning("While cleaning up: " + sqle.getClass().getName()
+ ": " + sqle.getMessage());
} finally {
results=null;
st=null;
}
}
}
}
logFinest("DefaultDOReplicator.updateComponents: Exiting ------");
return true;
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/objects/dLocation.java b/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
index 925d31f04..de4aaf9e4 100644
--- a/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
+++ b/src/main/java/net/aufdemrand/denizen/objects/dLocation.java
@@ -1,899 +1,899 @@
package net.aufdemrand.denizen.objects;
import net.aufdemrand.denizen.objects.dPlayer;
import net.aufdemrand.denizen.tags.Attribute;
import net.aufdemrand.denizen.utilities.DenizenAPI;
import net.aufdemrand.denizen.utilities.Utilities;
import net.aufdemrand.denizen.utilities.debugging.dB;
import net.aufdemrand.denizen.utilities.depends.Depends;
import net.aufdemrand.denizen.utilities.depends.WorldGuardUtilities;
import net.aufdemrand.denizen.utilities.entity.Rotation;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Material;
import org.bukkit.entity.Entity;
import org.bukkit.entity.LivingEntity;
import org.bukkit.entity.Player;
import org.bukkit.World;
import org.bukkit.block.Sign;
import java.util.*;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
public class dLocation extends org.bukkit.Location implements dObject {
// This pattern correctly reads both 0.9 and 0.8 notables
final static Pattern notablePattern =
Pattern.compile("(\\w+)[;,]((-?\\d+\\.?\\d*,){3,5}\\w+)",
Pattern.CASE_INSENSITIVE);
/////////////////////
// STATIC METHODS
/////////////////
public static Map<String, dLocation> uniqueObjects = new HashMap<String, dLocation>();
public static boolean isSaved(String id) {
return uniqueObjects.containsKey(id.toUpperCase());
}
public static boolean isSaved(dLocation location) {
return uniqueObjects.containsValue(location);
}
public static boolean isSaved(Location location) {
for (Map.Entry<String, dLocation> i : uniqueObjects.entrySet())
if (i.getValue() == location) return true;
return uniqueObjects.containsValue(location);
}
public static dLocation getSaved(String id) {
if (uniqueObjects.containsKey(id.toUpperCase()))
return uniqueObjects.get(id.toUpperCase());
else return null;
}
public static String getSaved(dLocation location) {
for (Map.Entry<String, dLocation> i : uniqueObjects.entrySet()) {
if (i.getValue().getBlockX() != location.getBlockX()) continue;
if (i.getValue().getBlockY() != location.getBlockY()) continue;
if (i.getValue().getBlockZ() != location.getBlockZ()) continue;
if (i.getValue().getWorld().getName() != location.getWorld().getName()) continue;
return i.getKey();
}
return null;
}
public static String getSaved(Location location) {
dLocation dLoc = new dLocation(location);
return getSaved(dLoc);
}
public static void saveAs(dLocation location, String id) {
if (location == null) return;
uniqueObjects.put(id.toUpperCase(), location);
}
public static void remove(String id) {
uniqueObjects.remove(id.toUpperCase());
}
/*
* Called on server startup or /denizen reload locations. Should probably not be called manually.
*/
public static void _recallLocations() {
List<String> loclist = DenizenAPI.getCurrentInstance().getSaves().getStringList("dScript.Locations");
uniqueObjects.clear();
for (String location : loclist) {
Matcher m = notablePattern.matcher(location);
if (m.matches()) {
String id = m.group(1);
dLocation loc = valueOf(m.group(2));
uniqueObjects.put(id, loc);
}
}
}
/*
* Called by Denizen internally on a server shutdown or /denizen save. Should probably
* not be called manually.
*/
public static void _saveLocations() {
List<String> loclist = new ArrayList<String>();
for (Map.Entry<String, dLocation> entry : uniqueObjects.entrySet())
loclist.add(entry.getKey() + ";"
+ entry.getValue().getBlockX()
+ "," + entry.getValue().getBlockY()
+ "," + entry.getValue().getBlockZ()
+ "," + entry.getValue().getYaw()
+ "," + entry.getValue().getPitch()
+ "," + entry.getValue().getWorld().getName());
DenizenAPI.getCurrentInstance().getSaves().set("dScript.Locations", loclist);
}
//////////////////
// OBJECT FETCHER
////////////////
/**
* Gets a Location Object from a string form of id,x,y,z,world
* or a dScript argument (location:)x,y,z,world. If including an Id,
* this location will persist and can be recalled at any time.
*
* @param string the string or dScript argument String
* @return a Location, or null if incorrectly formatted
*
*/
@ObjectFetcher("l")
public static dLocation valueOf(String string) {
if (string == null) return null;
////////
// Match @object format for saved dLocations
Matcher m;
final Pattern item_by_saved = Pattern.compile("(l@)(.+)");
m = item_by_saved.matcher(string);
if (m.matches() && isSaved(m.group(2)))
return getSaved(m.group(2));
////////
// Match location formats
// Split values
String[] split = string.replace("l@", "").split(",");
if (split.length == 4)
// If 4 values, standard dScript location format
// x,y,z,world
try {
return new dLocation(Bukkit.getWorld(split[3]),
Double.valueOf(split[0]),
Double.valueOf(split[1]),
Double.valueOf(split[2]));
} catch(Exception e) {
return null;
}
else if (split.length == 6)
// If 6 values, location with pitch/yaw
// x,y,z,yaw,pitch,world
try
{ return new dLocation(Bukkit.getWorld(split[5]),
Double.valueOf(split[0]),
Double.valueOf(split[1]),
Double.valueOf(split[2]),
Float.valueOf(split[3]),
Float.valueOf(split[4]));
} catch(Exception e) {
return null;
}
dB.log("valueOf dLocation returning null: " + string);
return null;
}
public static boolean matches(String string) {
final Pattern location_by_saved = Pattern.compile("(l@)(.+)");
Matcher m = location_by_saved.matcher(string);
if (m.matches())
return true;
final Pattern location =
Pattern.compile("(-?\\d+\\.?\\d*,){3,5}\\w+",
Pattern.CASE_INSENSITIVE);
m = location.matcher(string);
if (m.matches())
return true;
return false;
}
/**
* Turns a Bukkit Location into a Location, which has some helpful methods
* for working with dScript.
*
* @param location the Bukkit Location to reference
*/
public dLocation(Location location) {
// Just save the yaw and pitch as they are; don't check if they are
// higher than 0, because Minecraft yaws are weird and can have
// negative values
super(location.getWorld(), location.getX(), location.getY(), location.getZ(),
location.getYaw(), location.getPitch());
}
/**
* Turns a world and coordinates into a Location, which has some helpful methods
* for working with dScript. If working with temporary locations, this is
* a much better method to use than {@link #dLocation(org.bukkit.World, double, double, double)}.
*
* @param world the world in which the location resides
* @param x x-coordinate of the location
* @param y y-coordinate of the location
* @param z z-coordinate of the location
*
*/
public dLocation(World world, double x, double y, double z) {
super(world, x, y, z);
}
public dLocation(World world, double x, double y, double z, float yaw, float pitch) {
super(world, x, y, z, pitch, yaw);
}
@Override
public void setPitch(float pitch) {
super.setPitch(pitch);
}
@Override
public void setYaw(float yaw) {
super.setYaw(yaw);
}
public dLocation rememberAs(String id) {
dLocation.saveAs(this, id);
return this;
}
String prefix = "Location";
@Override
public String getType() {
return "Location";
}
@Override
public String getPrefix() {
return prefix;
}
@Override
public dLocation setPrefix(String prefix) {
this.prefix = prefix;
return this;
}
@Override
public String debug() {
return (isSaved(this) ? "<G>" + prefix + "='<A>" + getSaved(this) + "(<Y>" + identify()+ "<A>)<G>' "
: "<G>" + prefix + "='<Y>" + identify() + "<G>' ");
}
@Override
public boolean isUnique() {
if (isSaved(this)) return true;
return false; //To change body of implemented methods use File | Settings | File Templates.
}
@Override
public String identify() {
if (isSaved(this))
return "l@" + getSaved(this);
else if (getYaw() != 0.0 && getPitch() != 0.0) return "l@" + getX() + "," + getY()
+ "," + getZ() + "," + getPitch() + "," + getYaw() + "," + getWorld().getName();
else return "l@" + getX() + "," + getY()
+ "," + getZ() + "," + getWorld().getName();
}
@Override
public String toString() {
return identify();
}
@Override
public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--
// <[email protected]> -> Element
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(String.valueOf(getBlock().getHumidity()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(String.valueOf(getBlock().getTemperature()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns Bukkit biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(String.valueOf(getBlock().getBiome().name()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> dLocation
// Returns the dLocation of the block below the location.
// -->
if (attribute.startsWith("block.below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> dLocation
// Returns the dLocation of the block above the location.
// -->
if (attribute.startsWith("block.above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected][x,y,z]> -> dLocation
// Adds to location coordinates, and returns the sum.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--
// <[email protected]_pose> -> dLocation
// Returns the dLocation with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--
// <[email protected][<block>|...].within[X]> -> dList
// Returns a dList of blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected]_blocks[<block>|...].within[X]> -> dList
// Returns a dList of surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected][X]> -> dList
// Returns a dList of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected][X]> -> dList
// Returns a dList of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected]_entities.within[X]> -> dList
// Returns a dList of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
else return "null";
}
// <--
// <[email protected]> -> Element
// Returns the Bukkit material name of the block at the
// location.
// -->
if (attribute.startsWith("block.material"))
return new Element(getBlock().getType().toString()).getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns the compass direction of the block or entity
// at the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected][<location>]> -> Element(Number)
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--
// <[email protected][<location>].horizontal> -> Element(Number)
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--
// <[email protected][<location>].horizontal.multiworld> -> Element(Number)
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(String.valueOf(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(toLocation.getZ() - toLocation.getZ(), 2))))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(String.valueOf(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(toLocation.getZ() - toLocation.getZ(), 2))))
.getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected][<location>].vertical> -> Element(Number)
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--
// <[email protected][<location>].vertical.multiworld> -> Element(Number)
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(String.valueOf(Math.abs(this.getY() - toLocation.getY())))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(String.valueOf(Math.abs(this.getY() - toLocation.getY())))
.getAttribute(attribute.fulfill(2));
}
else return new Element(String.valueOf(this.distance(toLocation)))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected]> -> Element
// Returns the simple version of a dLocation.
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element
// Returns the formatted simple version of a dLocation.
// -->
if (attribute.startsWith("formatted.simple"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns the formatted version of a dLocation.
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_liquid> -> Element(Boolean)
// If the block at the location is a liquid, return
// true. Otherwise, returns false.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(String.valueOf(getBlock().isLiquid())).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element(Number)
// Returns the amount of light from blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(String.valueOf((int) getBlock().getLightFromBlocks()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(String.valueOf((int) getBlock().getLightFromSky()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(String.valueOf((int) getBlock().getLightLevel()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element(Number)
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(String.valueOf(getPitch())).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(String.valueOf
(getYaw())).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(String.valueOf
(Rotation.normalizeYaw(getYaw()))).getAttribute(attribute.fulfill(1));
}
// <--
- // <[email protected][<entity>]> -> Element(Boolean)
+ // <[email protected][<value>]> -> Element(Boolean)
// Returns true if the location's yaw is facing another
// entity or location. Otherwise, returns false.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--
- // <location.facing[<entity>].degrees[X]> -> Element(Boolean)
+ // <location.facing[<value>].degrees[X]> -> Element(Boolean)
// Returns true if the location's yaw is facing another
// entity or location, within a specified degree range.
// Otherwise, returns false.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--
// <[email protected]> -> Element(Number)
// Returns the current power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(String.valueOf(getBlock().getBlockPower()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_region[<name>]> -> Element(Boolean)
// If a region name is specified, returns true if the
// location is in that region, else it returns true if
// the location is in any region. Otherwise, returns false.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the player is in the specified region
if (attribute.hasContext(1)) {
String region = attribute.getContext(1);
return new Element(String.valueOf(WorldGuardUtilities.inRegion(this, region)))
.getAttribute(attribute.fulfill(1));
}
// Check if the player is in any region
else {
return new Element(String.valueOf(WorldGuardUtilities.inRegion(this)))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected]> -> dList
// Returns the list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> dWorld
// Returns the dWorld that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--
// <location.block.x> -> Element(Number)
// Returns the X coordinate of the block.
// -->
if (attribute.startsWith("block.x")) {
return new Element(getBlockX()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Y coordinate of the block.
// -->
if (attribute.startsWith("block.y")) {
return new Element(getBlockY()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Z coordinate of the block.
// -->
if (attribute.startsWith("block.z")) {
return new Element(getBlockZ()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]_contents> -> dList
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("block.sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--
- // <[email protected]_y> -> dLocation
- // Returns the location of the block at x,z with the highest y.
+ // <[email protected]> -> dLocation
+ // Returns the location of the highest at x,z that isn't air.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation())
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute.fulfill(0));
}
}
| false | true | public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--
// <[email protected]> -> Element
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(String.valueOf(getBlock().getHumidity()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(String.valueOf(getBlock().getTemperature()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns Bukkit biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(String.valueOf(getBlock().getBiome().name()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> dLocation
// Returns the dLocation of the block below the location.
// -->
if (attribute.startsWith("block.below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> dLocation
// Returns the dLocation of the block above the location.
// -->
if (attribute.startsWith("block.above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected][x,y,z]> -> dLocation
// Adds to location coordinates, and returns the sum.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--
// <[email protected]_pose> -> dLocation
// Returns the dLocation with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--
// <[email protected][<block>|...].within[X]> -> dList
// Returns a dList of blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected]_blocks[<block>|...].within[X]> -> dList
// Returns a dList of surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected][X]> -> dList
// Returns a dList of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected][X]> -> dList
// Returns a dList of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected]_entities.within[X]> -> dList
// Returns a dList of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
else return "null";
}
// <--
// <[email protected]> -> Element
// Returns the Bukkit material name of the block at the
// location.
// -->
if (attribute.startsWith("block.material"))
return new Element(getBlock().getType().toString()).getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns the compass direction of the block or entity
// at the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected][<location>]> -> Element(Number)
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--
// <[email protected][<location>].horizontal> -> Element(Number)
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--
// <[email protected][<location>].horizontal.multiworld> -> Element(Number)
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(String.valueOf(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(toLocation.getZ() - toLocation.getZ(), 2))))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(String.valueOf(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(toLocation.getZ() - toLocation.getZ(), 2))))
.getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected][<location>].vertical> -> Element(Number)
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--
// <[email protected][<location>].vertical.multiworld> -> Element(Number)
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(String.valueOf(Math.abs(this.getY() - toLocation.getY())))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(String.valueOf(Math.abs(this.getY() - toLocation.getY())))
.getAttribute(attribute.fulfill(2));
}
else return new Element(String.valueOf(this.distance(toLocation)))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected]> -> Element
// Returns the simple version of a dLocation.
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element
// Returns the formatted simple version of a dLocation.
// -->
if (attribute.startsWith("formatted.simple"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns the formatted version of a dLocation.
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_liquid> -> Element(Boolean)
// If the block at the location is a liquid, return
// true. Otherwise, returns false.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(String.valueOf(getBlock().isLiquid())).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element(Number)
// Returns the amount of light from blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(String.valueOf((int) getBlock().getLightFromBlocks()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(String.valueOf((int) getBlock().getLightFromSky()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(String.valueOf((int) getBlock().getLightLevel()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element(Number)
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(String.valueOf(getPitch())).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(String.valueOf
(getYaw())).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(String.valueOf
(Rotation.normalizeYaw(getYaw()))).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected][<entity>]> -> Element(Boolean)
// Returns true if the location's yaw is facing another
// entity or location. Otherwise, returns false.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--
// <location.facing[<entity>].degrees[X]> -> Element(Boolean)
// Returns true if the location's yaw is facing another
// entity or location, within a specified degree range.
// Otherwise, returns false.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--
// <[email protected]> -> Element(Number)
// Returns the current power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(String.valueOf(getBlock().getBlockPower()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_region[<name>]> -> Element(Boolean)
// If a region name is specified, returns true if the
// location is in that region, else it returns true if
// the location is in any region. Otherwise, returns false.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the player is in the specified region
if (attribute.hasContext(1)) {
String region = attribute.getContext(1);
return new Element(String.valueOf(WorldGuardUtilities.inRegion(this, region)))
.getAttribute(attribute.fulfill(1));
}
// Check if the player is in any region
else {
return new Element(String.valueOf(WorldGuardUtilities.inRegion(this)))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected]> -> dList
// Returns the list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> dWorld
// Returns the dWorld that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--
// <location.block.x> -> Element(Number)
// Returns the X coordinate of the block.
// -->
if (attribute.startsWith("block.x")) {
return new Element(getBlockX()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Y coordinate of the block.
// -->
if (attribute.startsWith("block.y")) {
return new Element(getBlockY()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Z coordinate of the block.
// -->
if (attribute.startsWith("block.z")) {
return new Element(getBlockZ()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]_contents> -> dList
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("block.sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--
// <[email protected]_y> -> dLocation
// Returns the location of the block at x,z with the highest y.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation())
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute.fulfill(0));
}
| public String getAttribute(Attribute attribute) {
if (attribute == null) return null;
// <--
// <[email protected]> -> Element
// Returns the formatted biome name at the location.
// -->
if (attribute.startsWith("biome.formatted"))
return new Element(getBlock().getBiome().name().toLowerCase().replace('_', ' '))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the current humidity at the location.
// -->
if (attribute.startsWith("biome.humidity"))
return new Element(String.valueOf(getBlock().getHumidity()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the current temperature at the location.
// -->
if (attribute.startsWith("biome.temperature"))
return new Element(String.valueOf(getBlock().getTemperature()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns Bukkit biome name at the location.
// -->
if (attribute.startsWith("biome"))
return new Element(String.valueOf(getBlock().getBiome().name()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> dLocation
// Returns the dLocation of the block below the location.
// -->
if (attribute.startsWith("block.below"))
return new dLocation(this.add(0,-1,0))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> dLocation
// Returns the dLocation of the block above the location.
// -->
if (attribute.startsWith("block.above"))
return new dLocation(this.add(0,1,0))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected][x,y,z]> -> dLocation
// Adds to location coordinates, and returns the sum.
// -->
if (attribute.startsWith("add")) {
if (attribute.hasContext(1) && attribute.getContext(1).split(",").length == 3) {
String[] ints = attribute.getContext(1).split(",", 3);
if ((aH.matchesDouble(ints[0]) || aH.matchesInteger(ints[0]))
&& (aH.matchesDouble(ints[1]) || aH.matchesInteger(ints[1]))
&& (aH.matchesDouble(ints[2]) || aH.matchesInteger(ints[2]))) {
return new dLocation(this.clone().add(Double.valueOf(ints[0]),
Double.valueOf(ints[1]),
Double.valueOf(ints[2]))).getAttribute(attribute.fulfill(1));
}
}
}
// <--
// <[email protected]_pose> -> dLocation
// Returns the dLocation with pitch and yaw.
// -->
if (attribute.startsWith("with_pose")) {
String context = attribute.getContext(1);
Float pitch = 0f;
Float yaw = 0f;
if (dEntity.matches(context)) {
dEntity ent = dEntity.valueOf(context);
if (ent.isSpawned()) {
pitch = ent.getBukkitEntity().getLocation().getPitch();
yaw = ent.getBukkitEntity().getLocation().getYaw();
}
} else if (context.split(",").length == 2) {
String[] split = context.split(",");
pitch = Float.valueOf(split[0]);
yaw = Float.valueOf(split[1]);
}
dLocation loc = dLocation.valueOf(identify());
loc.setPitch(pitch);
loc.setYaw(yaw);
return loc.getAttribute(attribute.fulfill(1));
}
if (attribute.startsWith("find") || attribute.startsWith("nearest")) {
attribute.fulfill(1);
// <--
// <[email protected][<block>|...].within[X]> -> dList
// Returns a dList of blocks within a radius.
// -->
if (attribute.startsWith("blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
// dB.log(materials + " " + radius + " ");
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData())))
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
} else found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected]_blocks[<block>|...].within[X]> -> dList
// Returns a dList of surface blocks within a radius.
// -->
else if (attribute.startsWith("surface_blocks")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dLocation> found = new ArrayList<dLocation>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
List<dObject> materials = new ArrayList<dObject>();
if (attribute.hasContext(1))
materials = dList.valueOf(attribute.getContext(1)).filter(dMaterial.class);
attribute.fulfill(2);
for (int x = -(radius); x <= radius; x++)
for (int y = -(radius); y <= radius; y++)
for (int z = -(radius); z <= radius; z++)
if (!materials.isEmpty()) {
for (dObject material : materials)
if (((dMaterial) material).matchesMaterialData(getBlock()
.getRelative(x,y,z).getType().getNewData(getBlock()
.getRelative(x,y,z).getData()))) {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
} else {
Location l = getBlock().getRelative(x,y,z).getLocation();
if (l.add(0,1,0).getBlock().getType() == Material.AIR
&& l.add(0,1,0).getBlock().getType() == Material.AIR)
found.add(new dLocation(getBlock().getRelative(x,y,z).getLocation()));
}
Collections.sort(found, new Comparator<dLocation>() {
@Override
public int compare(dLocation loc1, dLocation loc2) {
return (int) (distanceSquared(loc1) - distanceSquared(loc2));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected][X]> -> dList
// Returns a dList of players within a radius.
// -->
else if (attribute.startsWith("players")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dPlayer> found = new ArrayList<dPlayer>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Player player : Bukkit.getOnlinePlayers())
if (Utilities.checkLocation(this, player.getLocation(), radius))
found.add(new dPlayer(player));
Collections.sort(found, new Comparator<dPlayer>() {
@Override
public int compare(dPlayer pl1, dPlayer pl2) {
return (int) (distanceSquared(pl1.getLocation()) - distanceSquared(pl2.getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected][X]> -> dList
// Returns a dList of entities within a radius.
// -->
else if (attribute.startsWith("entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
// <--
// <[email protected]_entities.within[X]> -> dList
// Returns a dList of living entities within a radius.
// -->
else if (attribute.startsWith("living_entities")
&& attribute.getAttribute(2).startsWith("within")
&& attribute.hasContext(2)) {
ArrayList<dEntity> found = new ArrayList<dEntity>();
int radius = aH.matchesInteger(attribute.getContext(2)) ? attribute.getIntContext(2) : 10;
attribute.fulfill(2);
for (Entity entity : getWorld().getEntities())
if (entity instanceof LivingEntity
&& Utilities.checkLocation(this, entity.getLocation(), radius))
found.add(new dEntity(entity));
Collections.sort(found, new Comparator<dEntity>() {
@Override
public int compare(dEntity ent1, dEntity ent2) {
return (int) (distanceSquared(ent1.getBukkitEntity().getLocation()) - distanceSquared(ent2.getBukkitEntity().getLocation()));
}
});
return new dList(found).getAttribute(attribute);
}
else return "null";
}
// <--
// <[email protected]> -> Element
// Returns the Bukkit material name of the block at the
// location.
// -->
if (attribute.startsWith("block.material"))
return new Element(getBlock().getType().toString()).getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns the compass direction of the block or entity
// at the location.
// -->
if (attribute.startsWith("direction")) {
// Get the cardinal direction from this location to another
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
// Subtract this location's vector from the other location's vector,
// not the other way around
return new Element(Rotation.getCardinal(Rotation.getYaw
(dLocation.valueOf(attribute.getContext(1)).toVector().subtract(this.toVector())
.normalize())))
.getAttribute(attribute.fulfill(1));
}
// Get a cardinal direction from this location's yaw
else {
return new Element(Rotation.getCardinal(getYaw()))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected][<location>]> -> Element(Number)
// Returns the distance between 2 locations.
// -->
if (attribute.startsWith("distance")) {
if (attribute.hasContext(1) && dLocation.matches(attribute.getContext(1))) {
dLocation toLocation = dLocation.valueOf(attribute.getContext(1));
// <--
// <[email protected][<location>].horizontal> -> Element(Number)
// Returns the horizontal distance between 2 locations.
// -->
if (attribute.getAttribute(2).startsWith("horizontal")) {
// <--
// <[email protected][<location>].horizontal.multiworld> -> Element(Number)
// Returns the horizontal distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(String.valueOf(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(toLocation.getZ() - toLocation.getZ(), 2))))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(String.valueOf(Math.sqrt(
Math.pow(this.getX() - toLocation.getX(), 2) +
Math.pow(toLocation.getZ() - toLocation.getZ(), 2))))
.getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected][<location>].vertical> -> Element(Number)
// Returns the vertical distance between 2 locations.
// -->
else if (attribute.getAttribute(2).startsWith("vertical")) {
// <--
// <[email protected][<location>].vertical.multiworld> -> Element(Number)
// Returns the vertical distance between 2 multiworld locations.
// -->
if (attribute.getAttribute(3).startsWith("multiworld"))
return new Element(String.valueOf(Math.abs(this.getY() - toLocation.getY())))
.getAttribute(attribute.fulfill(3));
else if (this.getWorld() == toLocation.getWorld())
return new Element(String.valueOf(Math.abs(this.getY() - toLocation.getY())))
.getAttribute(attribute.fulfill(2));
}
else return new Element(String.valueOf(this.distance(toLocation)))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected]> -> Element
// Returns the simple version of a dLocation.
// -->
if (attribute.startsWith("simple"))
return new Element(getBlockX() + "," + getBlockY() + "," + getBlockZ()
+ "," + getWorld().getName()).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element
// Returns the formatted simple version of a dLocation.
// -->
if (attribute.startsWith("formatted.simple"))
return new Element("X '" + getBlockX()
+ "', Y '" + getBlockY()
+ "', Z '" + getBlockZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element
// Returns the formatted version of a dLocation.
// -->
if (attribute.startsWith("formatted"))
return new Element("X '" + getX()
+ "', Y '" + getY()
+ "', Z '" + getZ()
+ "', in world '" + getWorld().getName() + "'").getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_liquid> -> Element(Boolean)
// If the block at the location is a liquid, return
// true. Otherwise, returns false.
// -->
if (attribute.startsWith("is_liquid"))
return new Element(String.valueOf(getBlock().isLiquid())).getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element(Number)
// Returns the amount of light from blocks that is
// on the location.
// -->
if (attribute.startsWith("light.from_blocks") ||
attribute.startsWith("light.blocks"))
return new Element(String.valueOf((int) getBlock().getLightFromBlocks()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the amount of light from the sky that is
// on the location.
// -->
if (attribute.startsWith("light.from_sky") ||
attribute.startsWith("light.sky"))
return new Element(String.valueOf((int) getBlock().getLightFromSky()))
.getAttribute(attribute.fulfill(2));
// <--
// <[email protected]> -> Element(Number)
// Returns the total amount of light on the location.
// -->
if (attribute.startsWith("light"))
return new Element(String.valueOf((int) getBlock().getLightLevel()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]> -> Element(Number)
// Returns the pitch of the object at the location.
// -->
if (attribute.startsWith("pitch")) {
return new Element(String.valueOf(getPitch())).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the raw yaw of the object at the location.
// -->
if (attribute.startsWith("yaw.raw")) {
return new Element(String.valueOf
(getYaw())).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the normalized yaw of the object at the location.
// -->
if (attribute.startsWith("yaw")) {
return new Element(String.valueOf
(Rotation.normalizeYaw(getYaw()))).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected][<value>]> -> Element(Boolean)
// Returns true if the location's yaw is facing another
// entity or location. Otherwise, returns false.
// -->
if (attribute.startsWith("facing")) {
if (attribute.hasContext(1)) {
// The default number of degrees if there is no degrees attribute
int degrees = 45;
// The attribute to fulfill from
int attributePos = 1;
// <--
// <location.facing[<value>].degrees[X]> -> Element(Boolean)
// Returns true if the location's yaw is facing another
// entity or location, within a specified degree range.
// Otherwise, returns false.
// -->
if (attribute.getAttribute(2).startsWith("degrees") &&
attribute.hasContext(2) &&
aH.matchesInteger(attribute.getContext(2))) {
degrees = attribute.getIntContext(2);
attributePos++;
}
if (dLocation.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dLocation.valueOf(attribute.getContext(1)), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
else if (dEntity.matches(attribute.getContext(1))) {
return new Element(Rotation.isFacingLocation
(this, dEntity.valueOf(attribute.getContext(1))
.getBukkitEntity().getLocation(), degrees))
.getAttribute(attribute.fulfill(attributePos));
}
}
}
// <--
// <[email protected]> -> Element(Number)
// Returns the current power level of a block.
// -->
if (attribute.startsWith("power"))
return new Element(String.valueOf(getBlock().getBlockPower()))
.getAttribute(attribute.fulfill(1));
// <--
// <[email protected]_region[<name>]> -> Element(Boolean)
// If a region name is specified, returns true if the
// location is in that region, else it returns true if
// the location is in any region. Otherwise, returns false.
// -->
if (attribute.startsWith("in_region")) {
if (Depends.worldGuard == null) {
dB.echoError("Cannot check region! WorldGuard is not loaded!");
return null;
}
// Check if the player is in the specified region
if (attribute.hasContext(1)) {
String region = attribute.getContext(1);
return new Element(String.valueOf(WorldGuardUtilities.inRegion(this, region)))
.getAttribute(attribute.fulfill(1));
}
// Check if the player is in any region
else {
return new Element(String.valueOf(WorldGuardUtilities.inRegion(this)))
.getAttribute(attribute.fulfill(1));
}
}
// <--
// <[email protected]> -> dList
// Returns the list of regions that the location is in.
// -->
if (attribute.startsWith("regions")) {
return new dList(WorldGuardUtilities.getRegions(this))
.getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> dWorld
// Returns the dWorld that the location is in.
// -->
if (attribute.startsWith("world")) {
return dWorld.mirrorBukkitWorld(getWorld())
.getAttribute(attribute.fulfill(1));
}
// <--
// <location.block.x> -> Element(Number)
// Returns the X coordinate of the block.
// -->
if (attribute.startsWith("block.x")) {
return new Element(getBlockX()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Y coordinate of the block.
// -->
if (attribute.startsWith("block.y")) {
return new Element(getBlockY()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Z coordinate of the block.
// -->
if (attribute.startsWith("block.z")) {
return new Element(getBlockZ()).getAttribute(attribute.fulfill(2));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the X coordinate of the location.
// -->
if (attribute.startsWith("x")) {
return new Element(getX()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Y coordinate of the location.
// -->
if (attribute.startsWith("y")) {
return new Element(getY()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]> -> Element(Number)
// Returns the Z coordinate of the location.
// -->
if (attribute.startsWith("z")) {
return new Element(getZ()).getAttribute(attribute.fulfill(1));
}
// <--
// <[email protected]_contents> -> dList
// Returns a list of lines on a sign.
// -->
if (attribute.startsWith("block.sign_contents")) {
if (getBlock().getState() instanceof Sign) {
return new dList(Arrays.asList(((Sign) getBlock().getState()).getLines()))
.getAttribute(attribute.fulfill(2));
}
else return "null";
}
// <--
// <[email protected]> -> dLocation
// Returns the location of the highest at x,z that isn't air.
// -->
if (attribute.startsWith("highest")) {
return new dLocation(getWorld().getHighestBlockAt(this).getLocation())
.getAttribute(attribute.fulfill(1));
}
return new Element(identify()).getAttribute(attribute.fulfill(0));
}
|
diff --git a/src/org/geworkbench/engine/skin/Skin.java b/src/org/geworkbench/engine/skin/Skin.java
index 8a8d9976..7c72c878 100755
--- a/src/org/geworkbench/engine/skin/Skin.java
+++ b/src/org/geworkbench/engine/skin/Skin.java
@@ -1,870 +1,868 @@
package org.geworkbench.engine.skin;
import java.awt.AWTEvent;
import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Component;
import java.awt.Cursor;
import java.awt.Dimension;
import java.awt.GridLayout;
import java.awt.Point;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.MouseAdapter;
import java.awt.event.MouseEvent;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.io.BufferedReader;
import java.io.File;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.List;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;
import javax.swing.AbstractAction;
import javax.swing.BorderFactory;
import javax.swing.DefaultListModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComponent;
import javax.swing.JDialog;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JSplitPane;
import javax.swing.JTabbedPane;
import javax.swing.JToolBar;
import javax.swing.KeyStroke;
import javax.swing.event.ChangeEvent;
import javax.swing.event.ChangeListener;
import net.eleritec.docking.DockableAdapter;
import net.eleritec.docking.DockingManager;
import net.eleritec.docking.DockingPort;
import net.eleritec.docking.defaults.ComponentProviderAdapter;
import net.eleritec.docking.defaults.DefaultDockingPort;
import org.apache.commons.collections15.map.ReferenceMap;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.geworkbench.bison.datastructure.biocollections.DSDataSet;
import org.geworkbench.builtin.projects.Icons;
import org.geworkbench.engine.config.GUIFramework;
import org.geworkbench.engine.config.PluginDescriptor;
import org.geworkbench.engine.config.VisualPlugin;
import org.geworkbench.engine.config.Closable;
import org.geworkbench.engine.config.events.AppEventListenerException;
import org.geworkbench.engine.config.events.EventSource;
import org.geworkbench.engine.management.ComponentRegistry;
import org.geworkbench.events.ComponentDockingEvent;
import org.geworkbench.events.listeners.ComponentDockingListener;
import org.geworkbench.util.FilePathnameUtils;
import org.geworkbench.util.JAutoList;
/**
* <p>Title: Bioworks</p>
* <p>Description: Modular Application Framework for Gene Expession, Sequence and Genotype Analysis</p>
* <p>Copyright: Copyright (c) 2003 -2004</p>
* <p>Company: Columbia University</p>
*
* @author manjunath at genomecenter dot columbia dot edu
* @version 1.0
*/
public class Skin extends GUIFramework {
static Log log = LogFactory.getLog(Skin.class);
static HashMap visualRegistry = new HashMap();
JPanel contentPane;
JLabel statusBar = new JLabel();
BorderLayout borderLayout1 = new BorderLayout();
JSplitPane jSplitPane1 = new JSplitPane();
BorderLayout borderLayout5 = new BorderLayout();
DefaultDockingPort visualPanel = new DefaultDockingPort();
DefaultDockingPort commandPanel = new DefaultDockingPort();
BorderLayout borderLayout2 = new BorderLayout();
BorderLayout borderLayout3 = new BorderLayout();
JSplitPane jSplitPane2 = new JSplitPane();
JSplitPane jSplitPane3 = new JSplitPane();
BorderLayout borderLayout4 = new BorderLayout();
DefaultDockingPort selectionPanel = new DefaultDockingPort();
GridLayout gridLayout1 = new GridLayout();
JToolBar jToolBar = new JToolBar();
DefaultDockingPort projectPanel = new DefaultDockingPort();
BorderLayout borderLayout9 = new BorderLayout();
Hashtable areas = new Hashtable();
DockingNotifier eventSink = new DockingNotifier();
private Set<Class> acceptors;
private HashMap<Component, Class> mainComponentClass = new HashMap<Component, Class>();
private ReferenceMap<DSDataSet, String> visualLastSelected = new ReferenceMap<DSDataSet, String>();
private ReferenceMap<DSDataSet, String> commandLastSelected = new ReferenceMap<DSDataSet, String>();
private ReferenceMap<DSDataSet, String> selectionLastSelected = new ReferenceMap<DSDataSet, String>();
private ArrayList<DockableImpl> visualDockables = new ArrayList<DockableImpl>();
private ArrayList<DockableImpl> commandDockables = new ArrayList<DockableImpl>();
private ArrayList<DockableImpl> selectorDockables = new ArrayList<DockableImpl>();
private DSDataSet currentDataSet;
private boolean tabSwappingMode = false;
public static final String APP_SIZE_FILE = "appCoords.txt";
public String getVisualLastSelected(DSDataSet dataSet) {
return visualLastSelected.get(dataSet);
}
public String getCommandLastSelected(DSDataSet dataSet) {
return commandLastSelected.get(dataSet);
}
public String getSelectionLastSelected(DSDataSet dataSet) {
return selectionLastSelected.get(dataSet);
}
public void setVisualLastSelected(DSDataSet dataSet, String component) {
if (component != null) {
visualLastSelected.put(dataSet, component);
}
}
public void setCommandLastSelected(DSDataSet dataSet, String component) {
if (component != null) {
commandLastSelected.put(dataSet, component);
}
}
public void setSelectionLastSelected(DSDataSet dataSet, String component) {
if (component != null) {
selectionLastSelected.put(dataSet, component);
}
}
public Skin() {
registerAreas();
addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
Dimension finalSize = getSize();
Point finalLocation = getLocation();
File f = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
try {
PrintWriter out = new PrintWriter(new FileWriter(f));
out.println("" + finalSize.width);
out.println("" + finalSize.height);
out.println("" + finalLocation.x);
out.println("" + finalLocation.y);
out.close();
List<Object> list = ComponentRegistry.getRegistry().getComponentsList();
for(Object obj: list)
{
if ( obj instanceof Closable)
((Closable)obj).closing();
}
} catch (IOException ioe) {
ioe.printStackTrace();
} catch (Exception ex) {
ex.printStackTrace();
}
}
});
try {
jbInit();
} catch (Exception e) {
e.printStackTrace();
}
setDefaultCloseOperation(JFrame.DO_NOTHING_ON_CLOSE);
}
private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
this.setTitle(System.getProperty("application.title"));
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
contentPane.add(statusBar, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
}
private static class DialogResult {
public boolean cancelled = false;
}
private void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Iterator<Class> iterator = acceptors.iterator(); iterator.hasNext();) {
Class type = iterator.next();
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
// JPanel panel = new JPanel();
// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// dialog.getContentPane().add(panel);
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 4) Register enter and esc.
// String actionOK = "OK";
// String actionCancel = "Cancel";
// panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), actionOK);
// panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), actionCancel);
// panel.getActionMap().put(actionOK, new AbstractAction() {
// public void actionPerformed(ActionEvent event) {
// autoList.get
// }
// });
// panel.getActionMap().put(actionCancel, new AbstractAction() {
// public void actionPerformed(ActionEvent event) {
// dialog.dispose();
// }
// });
//
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
Set keys = areas.keySet();
boolean found = false;
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
areas.put(TOOL_AREA, jToolBar);
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
// public void remove(Component visualPlugin) {
// Collection containers = areas.values();
// Iterator iterator = containers.iterator();
// JPanel container = null;
// Component[] components = null;
// while (iterator.hasNext()) {
// Component comp = (Component) iterator.next();
// if (comp instanceof JPanel) {
// container = (JPanel) comp;
// components = container.getComponents();
// for (int i = 0; i < components.length; i++) {
// if (components[i] == visualPlugin) {
// container.remove(visualPlugin);
// return;
// }
// }
// }
// }
// visualRegistry.remove(visualPlugin);
/* The above code probably never worked because of the "return"
* Because this was not working, the visualRegistry.remove(visualPluginComponent);
* at the bottom of this method was able to function.
* The VISUAL_AREAand the COMMAND_AREA were being rebuilt by the
* addAppropriateComponents() method.
*
* The below code works, is more readable and removes components from jTabbed Panels.
* However it is not needed because of the adding of
* selectorDockables.
* addAppropriateComponents() uses selectorDockables to rebuild the
* SELECTION_AREA
* area of the GUI.
*
* setVisualizationType() if the method in projectSelection, and now in ProjectPanel,
* which calls addAppropriateComponents()
*
* */
// Set areasEntrySet = areas.entrySet();
// Iterator areasEntrySetIterator = areasEntrySet.iterator();
// while (areasEntrySetIterator.hasNext()) {
// Map.Entry mapEntry = (Map.Entry) areasEntrySetIterator.next();
// Component comp = (Component)mapEntry.getValue();
// if (comp instanceof JPanel) {
// JPanel jPanel = (JPanel) comp;
// Component[] jPanelComponents = jPanel.getComponents();
// for (int i = 0; i < jPanelComponents.length; i++) {
// Component jPanelComponent = jPanelComponents[i];
// if (jPanelComponent == visualPluginComponent) {
// jPanel.remove(visualPluginComponent);
// break;
// }else
// if (jPanelComponent instanceof JTabbedPane){
// JTabbedPane jTabbedPane = (JTabbedPane) jPanelComponent;
// int n = jTabbedPane.getTabCount();
// for (int j = 0; j < n; j++) {
// String tabbedPaneTitle = jTabbedPane.getTitleAt(j);
// String pluginName = visualPluginComponent.getName();
// if (tabbedPaneTitle.equals(pluginName)){
// jTabbedPane.remove(j);
// break;
// }
// }
// }
// }
// }
// }
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private void dockingFinished(DockableImpl comp) {
for (Enumeration e = areas.keys(); e.hasMoreElements();) {
String area = (String) e.nextElement();
Component port = (Component) areas.get(area);
Component container = comp.getDockable().getParent();
if (container instanceof JTabbedPane || container instanceof JSplitPane) {
if (container.getParent() == port) {
eventSink.throwEvent(comp.getPlugin(), area);
}
} else if (container instanceof DefaultDockingPort) {
if (container == port)
eventSink.throwEvent(comp.getPlugin(), area);
}
}
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
/* TODO implement me
private JButton minimize = new JButton();
private JButton remove = new JButton();
*/
private boolean docked = true;
/* TODO implement me
private ImageIcon close_grey = new ImageIcon(Skin.class.getResource("close_grey.gif"));
private ImageIcon close = new ImageIcon(Skin.class.getResource("close.gif"));
private ImageIcon close_active = new ImageIcon(Skin.class.getResource("close_active.gif"));
*/
private ImageIcon min_grey = new ImageIcon(Skin.class.getResource("min_grey.gif"));
private ImageIcon min = new ImageIcon(Skin.class.getResource("min.gif"));
private ImageIcon min_active = new ImageIcon(Skin.class.getResource("min_active.gif"));
/* TODO implement me
private ImageIcon max_grey = new ImageIcon(Skin.class.getResource("max_grey.gif"));
private ImageIcon max = new ImageIcon(Skin.class.getResource("max.gif"));
private ImageIcon max_active = new ImageIcon(Skin.class.getResource("max_active.gif"));
*/
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
/* TODO implement me
minimize.setPreferredSize(new Dimension(16, 16));
minimize.setBorderPainted(false);
minimize.setIcon(min_grey);
minimize.setRolloverEnabled(true);
minimize.setRolloverIcon(min);
minimize.setPressedIcon(min_active);
minimize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
minimize_actionPerformed(e);
}
});
remove.setPreferredSize(new Dimension(16, 16));
remove.setBorderPainted(false);
remove.setIcon(close_grey);
remove.setRolloverEnabled(true);
remove.setRolloverIcon(close);
remove.setPressedIcon(close_active);
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
remove_actionPerformed(e);
}
});
*/
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
/* TODO implement me
buttons.add(minimize);
buttons.add(remove);
*/
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void minimize_actionPerformed(ActionEvent e) {
//TODO Implement me
}
private void remove_actionPerformed(AWTEvent e) {
String areaName = getVisualArea(getPlugin());
if (areaName != null) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
remove(getPlugin());
} else {
remove(getPlugin());
frame.dispose();
}
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
dockingFinished(this);
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
- try {
+ if(index>=0) {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
- } catch (Exception e1) {
- log.warn(e1);
}
}
}
}
private class DockingNotifier extends EventSource {
public void throwEvent(Component source, String region) {
try {
throwEvent(ComponentDockingListener.class, "dockingAreaChanged", new ComponentDockingEvent(this, source, region));
} catch (AppEventListenerException aele) {
aele.printStackTrace();
}
}
}
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
for (Iterator iterator = acceptors.iterator(); iterator.hasNext();) {
Object o = iterator.next();
log.trace(o.toString());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
private void addAppropriateComponents(Set acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
// JTabbedPane visualpane = (JTabbedPane) ((DockingPort) areas.get(GUIFramework.VISUAL_AREA)).getDockedComponent();
// visualpane.removeAll();
Set components = visualRegistry.keySet();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Iterator visualIterator = components.iterator(); visualIterator.hasNext();) {
Component component = (Component) visualIterator.next();
if (visualRegistry.get(component).equals(screenRegion)) {
Class mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
}
| false | true | private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
this.setTitle(System.getProperty("application.title"));
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
contentPane.add(statusBar, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
}
private static class DialogResult {
public boolean cancelled = false;
}
private void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Iterator<Class> iterator = acceptors.iterator(); iterator.hasNext();) {
Class type = iterator.next();
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
// JPanel panel = new JPanel();
// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// dialog.getContentPane().add(panel);
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 4) Register enter and esc.
// String actionOK = "OK";
// String actionCancel = "Cancel";
// panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), actionOK);
// panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), actionCancel);
// panel.getActionMap().put(actionOK, new AbstractAction() {
// public void actionPerformed(ActionEvent event) {
// autoList.get
// }
// });
// panel.getActionMap().put(actionCancel, new AbstractAction() {
// public void actionPerformed(ActionEvent event) {
// dialog.dispose();
// }
// });
//
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
Set keys = areas.keySet();
boolean found = false;
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
areas.put(TOOL_AREA, jToolBar);
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
// public void remove(Component visualPlugin) {
// Collection containers = areas.values();
// Iterator iterator = containers.iterator();
// JPanel container = null;
// Component[] components = null;
// while (iterator.hasNext()) {
// Component comp = (Component) iterator.next();
// if (comp instanceof JPanel) {
// container = (JPanel) comp;
// components = container.getComponents();
// for (int i = 0; i < components.length; i++) {
// if (components[i] == visualPlugin) {
// container.remove(visualPlugin);
// return;
// }
// }
// }
// }
// visualRegistry.remove(visualPlugin);
/* The above code probably never worked because of the "return"
* Because this was not working, the visualRegistry.remove(visualPluginComponent);
* at the bottom of this method was able to function.
* The VISUAL_AREAand the COMMAND_AREA were being rebuilt by the
* addAppropriateComponents() method.
*
* The below code works, is more readable and removes components from jTabbed Panels.
* However it is not needed because of the adding of
* selectorDockables.
* addAppropriateComponents() uses selectorDockables to rebuild the
* SELECTION_AREA
* area of the GUI.
*
* setVisualizationType() if the method in projectSelection, and now in ProjectPanel,
* which calls addAppropriateComponents()
*
* */
// Set areasEntrySet = areas.entrySet();
// Iterator areasEntrySetIterator = areasEntrySet.iterator();
// while (areasEntrySetIterator.hasNext()) {
// Map.Entry mapEntry = (Map.Entry) areasEntrySetIterator.next();
// Component comp = (Component)mapEntry.getValue();
// if (comp instanceof JPanel) {
// JPanel jPanel = (JPanel) comp;
// Component[] jPanelComponents = jPanel.getComponents();
// for (int i = 0; i < jPanelComponents.length; i++) {
// Component jPanelComponent = jPanelComponents[i];
// if (jPanelComponent == visualPluginComponent) {
// jPanel.remove(visualPluginComponent);
// break;
// }else
// if (jPanelComponent instanceof JTabbedPane){
// JTabbedPane jTabbedPane = (JTabbedPane) jPanelComponent;
// int n = jTabbedPane.getTabCount();
// for (int j = 0; j < n; j++) {
// String tabbedPaneTitle = jTabbedPane.getTitleAt(j);
// String pluginName = visualPluginComponent.getName();
// if (tabbedPaneTitle.equals(pluginName)){
// jTabbedPane.remove(j);
// break;
// }
// }
// }
// }
// }
// }
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private void dockingFinished(DockableImpl comp) {
for (Enumeration e = areas.keys(); e.hasMoreElements();) {
String area = (String) e.nextElement();
Component port = (Component) areas.get(area);
Component container = comp.getDockable().getParent();
if (container instanceof JTabbedPane || container instanceof JSplitPane) {
if (container.getParent() == port) {
eventSink.throwEvent(comp.getPlugin(), area);
}
} else if (container instanceof DefaultDockingPort) {
if (container == port)
eventSink.throwEvent(comp.getPlugin(), area);
}
}
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
/* TODO implement me
private JButton minimize = new JButton();
private JButton remove = new JButton();
*/
private boolean docked = true;
/* TODO implement me
private ImageIcon close_grey = new ImageIcon(Skin.class.getResource("close_grey.gif"));
private ImageIcon close = new ImageIcon(Skin.class.getResource("close.gif"));
private ImageIcon close_active = new ImageIcon(Skin.class.getResource("close_active.gif"));
*/
private ImageIcon min_grey = new ImageIcon(Skin.class.getResource("min_grey.gif"));
private ImageIcon min = new ImageIcon(Skin.class.getResource("min.gif"));
private ImageIcon min_active = new ImageIcon(Skin.class.getResource("min_active.gif"));
/* TODO implement me
private ImageIcon max_grey = new ImageIcon(Skin.class.getResource("max_grey.gif"));
private ImageIcon max = new ImageIcon(Skin.class.getResource("max.gif"));
private ImageIcon max_active = new ImageIcon(Skin.class.getResource("max_active.gif"));
*/
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
/* TODO implement me
minimize.setPreferredSize(new Dimension(16, 16));
minimize.setBorderPainted(false);
minimize.setIcon(min_grey);
minimize.setRolloverEnabled(true);
minimize.setRolloverIcon(min);
minimize.setPressedIcon(min_active);
minimize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
minimize_actionPerformed(e);
}
});
remove.setPreferredSize(new Dimension(16, 16));
remove.setBorderPainted(false);
remove.setIcon(close_grey);
remove.setRolloverEnabled(true);
remove.setRolloverIcon(close);
remove.setPressedIcon(close_active);
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
remove_actionPerformed(e);
}
});
*/
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
/* TODO implement me
buttons.add(minimize);
buttons.add(remove);
*/
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void minimize_actionPerformed(ActionEvent e) {
//TODO Implement me
}
private void remove_actionPerformed(AWTEvent e) {
String areaName = getVisualArea(getPlugin());
if (areaName != null) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
remove(getPlugin());
} else {
remove(getPlugin());
frame.dispose();
}
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
dockingFinished(this);
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
try {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
} catch (Exception e1) {
log.warn(e1);
}
}
}
}
private class DockingNotifier extends EventSource {
public void throwEvent(Component source, String region) {
try {
throwEvent(ComponentDockingListener.class, "dockingAreaChanged", new ComponentDockingEvent(this, source, region));
} catch (AppEventListenerException aele) {
aele.printStackTrace();
}
}
}
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
for (Iterator iterator = acceptors.iterator(); iterator.hasNext();) {
Object o = iterator.next();
log.trace(o.toString());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
private void addAppropriateComponents(Set acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
// JTabbedPane visualpane = (JTabbedPane) ((DockingPort) areas.get(GUIFramework.VISUAL_AREA)).getDockedComponent();
// visualpane.removeAll();
Set components = visualRegistry.keySet();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Iterator visualIterator = components.iterator(); visualIterator.hasNext();) {
Component component = (Component) visualIterator.next();
if (visualRegistry.get(component).equals(screenRegion)) {
Class mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
}
| private void jbInit() throws Exception {
contentPane = (JPanel) this.getContentPane();
this.setIconImage(Icons.MICROARRAYS_ICON.getImage());
contentPane.setLayout(borderLayout1);
Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
int guiHeight = 0;
int guiWidth = 0;
boolean foundSize = false;
File sizeFile = new File(FilePathnameUtils.getTemporaryFilesDirectoryPath() + APP_SIZE_FILE);
if (sizeFile.exists()) {
try {
BufferedReader in = new BufferedReader(new FileReader(sizeFile));
guiWidth = Integer.parseInt(in.readLine());
guiHeight = Integer.parseInt(in.readLine());
int guiX = Integer.parseInt(in.readLine());
int guiY = Integer.parseInt(in.readLine());
setLocation(guiX, guiY);
foundSize = true;
} catch (Exception ex) {
ex.printStackTrace();
}
}
if (!foundSize) {
guiWidth = (int) (dim.getWidth() * 0.9);
guiHeight = (int) (dim.getHeight() * 0.9);
this.setLocation((dim.width - guiWidth) / 2, (dim.height - guiHeight) / 2);
}
setSize(new Dimension(guiWidth, guiHeight));
this.setTitle(System.getProperty("application.title"));
statusBar.setText(" ");
jSplitPane1.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane1.setDoubleBuffered(true);
jSplitPane1.setContinuousLayout(true);
jSplitPane1.setBackground(Color.black);
jSplitPane1.setDividerSize(8);
jSplitPane1.setOneTouchExpandable(true);
jSplitPane1.setResizeWeight(0);
jSplitPane2.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane2.setDoubleBuffered(true);
jSplitPane2.setContinuousLayout(true);
jSplitPane2.setDividerSize(8);
jSplitPane2.setOneTouchExpandable(true);
jSplitPane2.setResizeWeight(0.9);
jSplitPane2.setMinimumSize(new Dimension(0, 0));
jSplitPane3.setOrientation(JSplitPane.VERTICAL_SPLIT);
jSplitPane3.setBorder(BorderFactory.createLineBorder(Color.black));
jSplitPane3.setDoubleBuffered(true);
jSplitPane3.setContinuousLayout(true);
jSplitPane3.setDividerSize(8);
jSplitPane3.setOneTouchExpandable(true);
jSplitPane3.setResizeWeight(0.1);
jSplitPane3.setMinimumSize(new Dimension(0, 0));
contentPane.add(statusBar, BorderLayout.SOUTH);
contentPane.add(jSplitPane1, BorderLayout.CENTER);
jSplitPane1.add(jSplitPane2, JSplitPane.RIGHT);
jSplitPane2.add(commandPanel, JSplitPane.BOTTOM);
jSplitPane2.add(visualPanel, JSplitPane.TOP);
jSplitPane1.add(jSplitPane3, JSplitPane.LEFT);
jSplitPane3.add(selectionPanel, JSplitPane.BOTTOM);
jSplitPane3.add(projectPanel, JSplitPane.LEFT);
contentPane.add(jToolBar, BorderLayout.NORTH);
jSplitPane1.setDividerLocation(230);
jSplitPane2.setDividerLocation((int) (guiHeight * 0.60));
jSplitPane3.setDividerLocation((int) (guiHeight * 0.35));
visualPanel.setComponentProvider(new ComponentProvider(VISUAL_AREA));
commandPanel.setComponentProvider(new ComponentProvider(COMMAND_AREA));
selectionPanel.setComponentProvider(new ComponentProvider(SELECTION_AREA));
projectPanel.setComponentProvider(new ComponentProvider(PROJECT_AREA));
final String CANCEL_DIALOG = "cancel-dialog";
contentPane.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_F12, 0), CANCEL_DIALOG);
contentPane.getActionMap().put(CANCEL_DIALOG, new AbstractAction() {
public void actionPerformed(ActionEvent event) {
chooseComponent();
}
});// contentPane.addKeyListener(new KeyAdapter() {
}
private static class DialogResult {
public boolean cancelled = false;
}
private void chooseComponent() {
if (acceptors == null) {
// Get all appropriate acceptors
acceptors = new HashSet<Class>();
}
// 1) Get all visual components
ComponentRegistry registry = ComponentRegistry.getRegistry();
VisualPlugin[] plugins = registry.getModules(VisualPlugin.class);
ArrayList<String> availablePlugins = new ArrayList<String>();
for (int i = 0; i < plugins.length; i++) {
String name = registry.getDescriptorForPlugin(plugins[i]).getLabel();
for (Iterator<Class> iterator = acceptors.iterator(); iterator.hasNext();) {
Class type = iterator.next();
if (registry.getDescriptorForPluginClass(type).getLabel().equals(name)) {
availablePlugins.add(name);
break;
}
}
}
final String[] names = availablePlugins.toArray(new String[0]);
// 2) Sort alphabetically
Arrays.sort(names);
// 3) Create dialog with JAutoText (prefix mode)
DefaultListModel model = new DefaultListModel();
for (int i = 0; i < names.length; i++) {
model.addElement(names[i]);
}
final JDialog dialog = new JDialog();
final DialogResult dialogResult = new DialogResult();
dialog.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent e) {
dialogResult.cancelled = true;
}
});
final JAutoList autoList = new JAutoList(model) {
protected void keyPressed(KeyEvent event) {
if (event.getKeyChar() == '\n') {
dialogResult.cancelled = false;
dialog.dispose();
} else if (event.getKeyChar() == 0x1b) {
dialogResult.cancelled = true;
dialog.dispose();
} else {
super.keyPressed(event);
}
}
protected void elementDoubleClicked(int index, MouseEvent e) {
dialogResult.cancelled = false;
dialog.dispose();
}
};
autoList.setPrefixMode(true);
dialog.setTitle("Component");
// JPanel panel = new JPanel();
// panel.setLayout(new BoxLayout(panel, BoxLayout.Y_AXIS));
// dialog.getContentPane().add(panel);
dialog.getContentPane().add(autoList);
dialog.setModal(true);
dialog.pack();
dialog.setSize(200, 300);
Dimension size = dialog.getSize();
Dimension frameSize = getSize();
int x = getLocationOnScreen().x + (frameSize.width - size.width) / 2;
int y = getLocationOnScreen().y + (frameSize.height - size.height) / 2;
// 4) Register enter and esc.
// String actionOK = "OK";
// String actionCancel = "Cancel";
// panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ENTER, 0), actionOK);
// panel.getInputMap(JComponent.WHEN_IN_FOCUSED_WINDOW).put(KeyStroke.getKeyStroke(KeyEvent.VK_ESCAPE, 0), actionCancel);
// panel.getActionMap().put(actionOK, new AbstractAction() {
// public void actionPerformed(ActionEvent event) {
// autoList.get
// }
// });
// panel.getActionMap().put(actionCancel, new AbstractAction() {
// public void actionPerformed(ActionEvent event) {
// dialog.dispose();
// }
// });
//
// 5) Display and get result
dialog.setBounds(x, y, size.width, size.height);
dialog.setVisible(true);
if (!dialogResult.cancelled) {
int index = autoList.getHighlightedIndex();
Set keys = areas.keySet();
boolean found = false;
for (Iterator iterator = keys.iterator(); iterator.hasNext();) {
String key = (String) iterator.next();
if (areas.get(key) instanceof DefaultDockingPort) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(key);
if (port.getDockedComponent() instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) port.getDockedComponent();
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
String title = pane.getTitleAt(i);
if (title.equals(names[index])) {
pane.setSelectedIndex(i);
pane.getComponentAt(i).requestFocus();
found = true;
break;
}
}
if (found) {
break;
}
}
}
}
}
}
/**
* Associates Visual Areas with Component Holders
*/
protected void registerAreas() {
areas.put(TOOL_AREA, jToolBar);
areas.put(VISUAL_AREA, visualPanel);
areas.put(COMMAND_AREA, commandPanel);
areas.put(SELECTION_AREA, selectionPanel);
areas.put(PROJECT_AREA, projectPanel);
}
// Is this used?
public void addToContainer(String areaName, Component visualPlugin) {
DockableImpl wrapper = new DockableImpl(visualPlugin, visualPlugin.getName());
DockingManager.registerDockable(wrapper);
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
visualRegistry.put(visualPlugin, areaName);
}
/**
* Removes the designated <code>visualPlugin</code> from the GUI.
*
* @param visualPlugin component to be removed
*/
public void remove(Component visualPluginComponent) {
// public void remove(Component visualPlugin) {
// Collection containers = areas.values();
// Iterator iterator = containers.iterator();
// JPanel container = null;
// Component[] components = null;
// while (iterator.hasNext()) {
// Component comp = (Component) iterator.next();
// if (comp instanceof JPanel) {
// container = (JPanel) comp;
// components = container.getComponents();
// for (int i = 0; i < components.length; i++) {
// if (components[i] == visualPlugin) {
// container.remove(visualPlugin);
// return;
// }
// }
// }
// }
// visualRegistry.remove(visualPlugin);
/* The above code probably never worked because of the "return"
* Because this was not working, the visualRegistry.remove(visualPluginComponent);
* at the bottom of this method was able to function.
* The VISUAL_AREAand the COMMAND_AREA were being rebuilt by the
* addAppropriateComponents() method.
*
* The below code works, is more readable and removes components from jTabbed Panels.
* However it is not needed because of the adding of
* selectorDockables.
* addAppropriateComponents() uses selectorDockables to rebuild the
* SELECTION_AREA
* area of the GUI.
*
* setVisualizationType() if the method in projectSelection, and now in ProjectPanel,
* which calls addAppropriateComponents()
*
* */
// Set areasEntrySet = areas.entrySet();
// Iterator areasEntrySetIterator = areasEntrySet.iterator();
// while (areasEntrySetIterator.hasNext()) {
// Map.Entry mapEntry = (Map.Entry) areasEntrySetIterator.next();
// Component comp = (Component)mapEntry.getValue();
// if (comp instanceof JPanel) {
// JPanel jPanel = (JPanel) comp;
// Component[] jPanelComponents = jPanel.getComponents();
// for (int i = 0; i < jPanelComponents.length; i++) {
// Component jPanelComponent = jPanelComponents[i];
// if (jPanelComponent == visualPluginComponent) {
// jPanel.remove(visualPluginComponent);
// break;
// }else
// if (jPanelComponent instanceof JTabbedPane){
// JTabbedPane jTabbedPane = (JTabbedPane) jPanelComponent;
// int n = jTabbedPane.getTabCount();
// for (int j = 0; j < n; j++) {
// String tabbedPaneTitle = jTabbedPane.getTitleAt(j);
// String pluginName = visualPluginComponent.getName();
// if (tabbedPaneTitle.equals(pluginName)){
// jTabbedPane.remove(j);
// break;
// }
// }
// }
// }
// }
// }
mainComponentClass.remove(visualPluginComponent);
visualRegistry.remove(visualPluginComponent);
}
public String getVisualArea(Component visualPlugin) {
return (String) visualRegistry.get(visualPlugin);
}
public void addToContainer(String areaName, Component visualPlugin, String pluginName, Class mainPluginClass) {
visualPlugin.setName(pluginName);
DockableImpl wrapper = new DockableImpl(visualPlugin, pluginName);
DockingManager.registerDockable(wrapper);
if (!areaName.equals(GUIFramework.VISUAL_AREA) && !areaName.equals(GUIFramework.COMMAND_AREA)) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
port.dock(wrapper, DockingPort.CENTER_REGION);
} else {
log.debug("Plugin wanting to go to visual or command area: " + pluginName);
}
visualRegistry.put(visualPlugin, areaName);
mainComponentClass.put(visualPlugin, mainPluginClass);
}
private void dockingFinished(DockableImpl comp) {
for (Enumeration e = areas.keys(); e.hasMoreElements();) {
String area = (String) e.nextElement();
Component port = (Component) areas.get(area);
Component container = comp.getDockable().getParent();
if (container instanceof JTabbedPane || container instanceof JSplitPane) {
if (container.getParent() == port) {
eventSink.throwEvent(comp.getPlugin(), area);
}
} else if (container instanceof DefaultDockingPort) {
if (container == port)
eventSink.throwEvent(comp.getPlugin(), area);
}
}
}
private class DockableImpl extends DockableAdapter {
private JPanel wrapper = null;
private JLabel initiator = null;
private String description = null;
private Component plugin = null;
private JPanel buttons = new JPanel();
private JPanel topBar = new JPanel();
private JButton docker = new JButton();
/* TODO implement me
private JButton minimize = new JButton();
private JButton remove = new JButton();
*/
private boolean docked = true;
/* TODO implement me
private ImageIcon close_grey = new ImageIcon(Skin.class.getResource("close_grey.gif"));
private ImageIcon close = new ImageIcon(Skin.class.getResource("close.gif"));
private ImageIcon close_active = new ImageIcon(Skin.class.getResource("close_active.gif"));
*/
private ImageIcon min_grey = new ImageIcon(Skin.class.getResource("min_grey.gif"));
private ImageIcon min = new ImageIcon(Skin.class.getResource("min.gif"));
private ImageIcon min_active = new ImageIcon(Skin.class.getResource("min_active.gif"));
/* TODO implement me
private ImageIcon max_grey = new ImageIcon(Skin.class.getResource("max_grey.gif"));
private ImageIcon max = new ImageIcon(Skin.class.getResource("max.gif"));
private ImageIcon max_active = new ImageIcon(Skin.class.getResource("max_active.gif"));
*/
private ImageIcon dock_grey = new ImageIcon(Skin.class.getResource("dock_grey.gif"));
private ImageIcon dock = new ImageIcon(Skin.class.getResource("dock.gif"));
private ImageIcon dock_active = new ImageIcon(Skin.class.getResource("dock_active.gif"));
private ImageIcon undock_grey = new ImageIcon(Skin.class.getResource("undock_grey.gif"));
private ImageIcon undock = new ImageIcon(Skin.class.getResource("undock.gif"));
private ImageIcon undock_active = new ImageIcon(Skin.class.getResource("undock_active.gif"));
DockableImpl(Component plugin, String desc) {
this.plugin = plugin;
wrapper = new JPanel();
docker.setPreferredSize(new Dimension(16, 16));
docker.setBorderPainted(false);
docker.setIcon(undock_grey);
docker.setRolloverEnabled(true);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
docker_actionPerformed(e);
}
});
/* TODO implement me
minimize.setPreferredSize(new Dimension(16, 16));
minimize.setBorderPainted(false);
minimize.setIcon(min_grey);
minimize.setRolloverEnabled(true);
minimize.setRolloverIcon(min);
minimize.setPressedIcon(min_active);
minimize.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
minimize_actionPerformed(e);
}
});
remove.setPreferredSize(new Dimension(16, 16));
remove.setBorderPainted(false);
remove.setIcon(close_grey);
remove.setRolloverEnabled(true);
remove.setRolloverIcon(close);
remove.setPressedIcon(close_active);
remove.addActionListener(new ActionListener() {
public void actionPerformed(ActionEvent e) {
remove_actionPerformed(e);
}
});
*/
buttons.setLayout(new GridLayout(1, 3));
buttons.add(docker);
/* TODO implement me
buttons.add(minimize);
buttons.add(remove);
*/
initiator = new JLabel(" ");
initiator.setForeground(Color.darkGray);
initiator.setBackground(Color.getHSBColor(0.0f, 0.0f, 0.6f));
initiator.setOpaque(true);
initiator.addMouseListener(new MouseAdapter() {
public void mouseEntered(MouseEvent me) {
setMoveCursor(me);
}
public void mouseExited(MouseEvent me) {
setDefaultCursor(me);
}
});
topBar.setLayout(new BorderLayout());
topBar.add(initiator, BorderLayout.CENTER);
topBar.add(buttons, BorderLayout.EAST);
wrapper.setLayout(new BorderLayout());
wrapper.add(topBar, BorderLayout.NORTH);
wrapper.add(plugin, BorderLayout.CENTER);
description = desc;
}
private JFrame frame = null;
private void docker_actionPerformed(ActionEvent e) {
log.debug("Action performed.");
String areaName = getVisualArea(this.getPlugin());
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
undock(port);
return;
} else {
redock(port);
}
}
public void undock(final DefaultDockingPort port) {
log.debug("Undocking.");
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
port.repaint();
docker.setIcon(dock_grey);
docker.setRolloverIcon(dock);
docker.setPressedIcon(dock_active);
docker.setSelected(false);
docker.repaint();
frame = new JFrame(description);
frame.setUndecorated(false);
frame.addWindowListener(new WindowAdapter() {
public void windowClosing(WindowEvent we) {
redock(port);
}
});
frame.getContentPane().setLayout(new BorderLayout());
frame.getContentPane().add(wrapper, BorderLayout.CENTER);
frame.pack();
frame.setVisible(true);
frame.repaint();
docked = false;
return;
}
public void redock(DefaultDockingPort port) {
if (frame != null) {
log.debug("Redocking " + plugin);
docker.setIcon(undock_grey);
docker.setRolloverIcon(undock);
docker.setPressedIcon(undock_active);
docker.setSelected(false);
port.dock(this, DockingPort.CENTER_REGION);
port.reevaluateContainerTree();
port.revalidate();
docked = true;
frame.getContentPane().remove(wrapper);
frame.dispose();
}
}
private void minimize_actionPerformed(ActionEvent e) {
//TODO Implement me
}
private void remove_actionPerformed(AWTEvent e) {
String areaName = getVisualArea(getPlugin());
if (areaName != null) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(areaName);
if (docked) {
port.undock(wrapper);
port.reevaluateContainerTree();
port.revalidate();
remove(getPlugin());
} else {
remove(getPlugin());
frame.dispose();
}
}
}
private void setMoveCursor(MouseEvent me) {
initiator.setCursor(Cursor.getPredefinedCursor(Cursor.MOVE_CURSOR));
}
private void setDefaultCursor(MouseEvent me) {
initiator.setCursor(Cursor.getDefaultCursor());
}
public Component getDockable() {
return wrapper;
}
public String getDockableDesc() {
return description;
}
public Component getInitiator() {
return initiator;
}
public Component getPlugin() {
return plugin;
}
public void dockingCompleted() {
dockingFinished(this);
}
}
private class ComponentProvider extends ComponentProviderAdapter {
private String area;
public ComponentProvider(String area) {
this.area = area;
}
// Add change listeners to appropriate areas so
public JTabbedPane createTabbedPane() {
final JTabbedPane pane = new JTabbedPane();
if (area.equals(VISUAL_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, visualLastSelected));
} else if (area.equals(COMMAND_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, commandLastSelected));
} else if (area.equals(SELECTION_AREA)) {
pane.addChangeListener(new TabChangeListener(pane, selectionLastSelected));
}
return pane;
}
}
private class TabChangeListener implements ChangeListener {
private final JTabbedPane pane;
private final ReferenceMap<DSDataSet, String> lastSelected;
public TabChangeListener(JTabbedPane pane, ReferenceMap<DSDataSet, String> lastSelected) {
this.pane = pane;
this.lastSelected = lastSelected;
}
public void stateChanged(ChangeEvent e) {
if ((currentDataSet != null) && !tabSwappingMode) {
int index = pane.getSelectedIndex();
if(index>=0) {
lastSelected.put(currentDataSet, pane.getTitleAt(index));
}
}
}
}
private class DockingNotifier extends EventSource {
public void throwEvent(Component source, String region) {
try {
throwEvent(ComponentDockingListener.class, "dockingAreaChanged", new ComponentDockingEvent(this, source, region));
} catch (AppEventListenerException aele) {
aele.printStackTrace();
}
}
}
public void setVisualizationType(DSDataSet type) {
currentDataSet = type;
// These are default acceptors
acceptors = ComponentRegistry.getRegistry().getAcceptors(null);
if (type != null) {
acceptors.addAll(ComponentRegistry.getRegistry().getAcceptors(type.getClass()));
}
if (type == null) {
log.trace("Default acceptors found:");
} else {
log.trace("Found the following acceptors for type " + type.getClass());
}
for (Iterator iterator = acceptors.iterator(); iterator.hasNext();) {
Object o = iterator.next();
log.trace(o.toString());
}
// Set up Visual Area
tabSwappingMode = true;
addAppropriateComponents(acceptors, GUIFramework.VISUAL_AREA, visualDockables);
selectLastComponent(GUIFramework.VISUAL_AREA, visualLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.COMMAND_AREA, commandDockables);
selectLastComponent(GUIFramework.COMMAND_AREA, commandLastSelected.get(type));
selectLastComponent(GUIFramework.SELECTION_AREA, selectionLastSelected.get(type));
addAppropriateComponents(acceptors, GUIFramework.SELECTION_AREA, selectorDockables);
tabSwappingMode = false;
contentPane.revalidate();
contentPane.repaint();
}
private void addAppropriateComponents(Set acceptors, String screenRegion, ArrayList<DockableImpl> dockables) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
for (DockableImpl dockable : dockables) {
dockable.redock(port);
}
dockables.clear();
port.removeAll();
// JTabbedPane visualpane = (JTabbedPane) ((DockingPort) areas.get(GUIFramework.VISUAL_AREA)).getDockedComponent();
// visualpane.removeAll();
Set components = visualRegistry.keySet();
SortedMap<Integer, Component> tabsToAdd = new TreeMap<Integer, Component>();
for (Iterator visualIterator = components.iterator(); visualIterator.hasNext();) {
Component component = (Component) visualIterator.next();
if (visualRegistry.get(component).equals(screenRegion)) {
Class mainclass = mainComponentClass.get(component);
if (acceptors.contains(mainclass)) {
log.trace("Found component in "+screenRegion+" to show: " + mainclass.toString());
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainclass);
tabsToAdd.put(desc.getPreferredOrder(), component);
}
}
}
for (Integer tabIndex : tabsToAdd.keySet()) {
PluginDescriptor desc = ComponentRegistry.getRegistry().getDescriptorForPluginClass(mainComponentClass.get(tabsToAdd.get(tabIndex)));
Component component = tabsToAdd.get(tabIndex);
DockableImpl dockable = new DockableImpl(component, desc.getLabel());
dockables.add(dockable);
port.dock(dockable, DockingPort.CENTER_REGION);
}
port.invalidate();
}
private void selectLastComponent(String screenRegion, String selected) {
DefaultDockingPort port = (DefaultDockingPort) areas.get(screenRegion);
if (selected != null) {
Component docked = port.getDockedComponent();
if (docked instanceof JTabbedPane) {
JTabbedPane pane = (JTabbedPane) docked;
int n = pane.getTabCount();
for (int i = 0; i < n; i++) {
if (selected.equals(pane.getTitleAt(i))) {
pane.setSelectedIndex(i);
break;
}
}
}
}
}
}
|
diff --git a/util/src/test/java/com/ning/billing/util/dao/TestStringTemplateInheritance.java b/util/src/test/java/com/ning/billing/util/dao/TestStringTemplateInheritance.java
index 1306cfeb6..df148e12e 100644
--- a/util/src/test/java/com/ning/billing/util/dao/TestStringTemplateInheritance.java
+++ b/util/src/test/java/com/ning/billing/util/dao/TestStringTemplateInheritance.java
@@ -1,191 +1,192 @@
/*
* Copyright 2010-2012 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.billing.util.dao;
import java.io.InputStream;
import java.io.InputStreamReader;
import org.antlr.stringtemplate.StringTemplateGroup;
import org.testng.Assert;
import org.testng.annotations.AfterMethod;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.Test;
import com.ning.billing.util.UtilTestSuiteNoDB;
import com.google.common.collect.ImmutableMap;
public class TestStringTemplateInheritance extends UtilTestSuiteNoDB {
InputStream entityStream;
InputStream kombuchaStream;
@Override
@BeforeMethod(groups = "fast")
public void beforeMethod() throws Exception {
super.beforeMethod();
entityStream = this.getClass().getResourceAsStream("/com/ning/billing/util/entity/dao/EntitySqlDao.sql.stg");
kombuchaStream = this.getClass().getResourceAsStream("/com/ning/billing/util/dao/Kombucha.sql.stg");
}
@Override
@AfterMethod(groups = "fast")
public void afterMethod() throws Exception {
super.afterMethod();
if (entityStream != null) {
entityStream.close();
}
if (kombuchaStream != null) {
kombuchaStream.close();
}
}
@Test(groups = "fast")
public void testCheckQueries() throws Exception {
// From http://www.antlr.org/wiki/display/ST/ST+condensed+--+Templates+and+groups#STcondensed--Templatesandgroups-Withsupergroupfile:
// there is no mechanism for automatically loading a mentioned super-group file
new StringTemplateGroup(new InputStreamReader(entityStream));
final StringTemplateGroup kombucha = new StringTemplateGroup(new InputStreamReader(kombuchaStream));
// Verify non inherited template
Assert.assertEquals(kombucha.getInstanceOf("isIsTimeForKombucha").toString(), "select hour(current_timestamp()) = 17 as is_time;");
// Verify inherited templates
Assert.assertEquals(kombucha.getInstanceOf("getById").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getByRecordId").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.record_id = :recordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getRecordId").toString(), "select\n" +
" t.record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getHistoryRecordId").toString(), "select\n" +
" max(t.record_id)\n" +
"from kombucha_history t\n" +
"where t.target_record_id = :targetRecordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getAll").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
+ "order by t.record_id ASC\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("get", ImmutableMap.<String, String>of("orderBy", "recordId", "offset", "3", "rowCount", "12")).toString(), "select SQL_CALC_FOUND_ROWS\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"order by :orderBy\n" +
"limit :offset, :rowCount\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("test").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"limit 1\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("addHistoryFromTransaction").toString(), "insert into kombucha_history (\n" +
" id\n" +
", target_record_id\n" +
", change_type\n" +
", tea\n" +
", mushroom\n" +
", sugar\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :tea\n" +
", :mushroom\n" +
", :sugar\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("insertAuditFromTransaction").toString(), "insert into audit_log (\n" +
"id\n" +
", table_name\n" +
", target_record_id\n" +
", change_type\n" +
", created_by\n" +
", reason_code\n" +
", comments\n" +
", user_token\n" +
", created_date\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :tableName\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :createdBy\n" +
", :reasonCode\n" +
", :comments\n" +
", :userToken\n" +
", :createdDate\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
}
}
| true | true | public void testCheckQueries() throws Exception {
// From http://www.antlr.org/wiki/display/ST/ST+condensed+--+Templates+and+groups#STcondensed--Templatesandgroups-Withsupergroupfile:
// there is no mechanism for automatically loading a mentioned super-group file
new StringTemplateGroup(new InputStreamReader(entityStream));
final StringTemplateGroup kombucha = new StringTemplateGroup(new InputStreamReader(kombuchaStream));
// Verify non inherited template
Assert.assertEquals(kombucha.getInstanceOf("isIsTimeForKombucha").toString(), "select hour(current_timestamp()) = 17 as is_time;");
// Verify inherited templates
Assert.assertEquals(kombucha.getInstanceOf("getById").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getByRecordId").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.record_id = :recordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getRecordId").toString(), "select\n" +
" t.record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getHistoryRecordId").toString(), "select\n" +
" max(t.record_id)\n" +
"from kombucha_history t\n" +
"where t.target_record_id = :targetRecordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getAll").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("get", ImmutableMap.<String, String>of("orderBy", "recordId", "offset", "3", "rowCount", "12")).toString(), "select SQL_CALC_FOUND_ROWS\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"order by :orderBy\n" +
"limit :offset, :rowCount\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("test").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"limit 1\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("addHistoryFromTransaction").toString(), "insert into kombucha_history (\n" +
" id\n" +
", target_record_id\n" +
", change_type\n" +
", tea\n" +
", mushroom\n" +
", sugar\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :tea\n" +
", :mushroom\n" +
", :sugar\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("insertAuditFromTransaction").toString(), "insert into audit_log (\n" +
"id\n" +
", table_name\n" +
", target_record_id\n" +
", change_type\n" +
", created_by\n" +
", reason_code\n" +
", comments\n" +
", user_token\n" +
", created_date\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :tableName\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :createdBy\n" +
", :reasonCode\n" +
", :comments\n" +
", :userToken\n" +
", :createdDate\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
}
| public void testCheckQueries() throws Exception {
// From http://www.antlr.org/wiki/display/ST/ST+condensed+--+Templates+and+groups#STcondensed--Templatesandgroups-Withsupergroupfile:
// there is no mechanism for automatically loading a mentioned super-group file
new StringTemplateGroup(new InputStreamReader(entityStream));
final StringTemplateGroup kombucha = new StringTemplateGroup(new InputStreamReader(kombuchaStream));
// Verify non inherited template
Assert.assertEquals(kombucha.getInstanceOf("isIsTimeForKombucha").toString(), "select hour(current_timestamp()) = 17 as is_time;");
// Verify inherited templates
Assert.assertEquals(kombucha.getInstanceOf("getById").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getByRecordId").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.record_id = :recordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getRecordId").toString(), "select\n" +
" t.record_id\n" +
"from kombucha t\n" +
"where t.id = :id\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getHistoryRecordId").toString(), "select\n" +
" max(t.record_id)\n" +
"from kombucha_history t\n" +
"where t.target_record_id = :targetRecordId\n" +
"and t.tenant_record_id = :tenantRecordId\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("getAll").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"order by t.record_id ASC\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("get", ImmutableMap.<String, String>of("orderBy", "recordId", "offset", "3", "rowCount", "12")).toString(), "select SQL_CALC_FOUND_ROWS\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"order by :orderBy\n" +
"limit :offset, :rowCount\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("test").toString(), "select\n" +
" t.record_id\n" +
", t.id\n" +
", t.tea\n" +
", t.mushroom\n" +
", t.sugar\n" +
", t.account_record_id\n" +
", t.tenant_record_id\n" +
"from kombucha t\n" +
"where t.tenant_record_id = :tenantRecordId\n" +
"limit 1\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("addHistoryFromTransaction").toString(), "insert into kombucha_history (\n" +
" id\n" +
", target_record_id\n" +
", change_type\n" +
", tea\n" +
", mushroom\n" +
", sugar\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :tea\n" +
", :mushroom\n" +
", :sugar\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
Assert.assertEquals(kombucha.getInstanceOf("insertAuditFromTransaction").toString(), "insert into audit_log (\n" +
"id\n" +
", table_name\n" +
", target_record_id\n" +
", change_type\n" +
", created_by\n" +
", reason_code\n" +
", comments\n" +
", user_token\n" +
", created_date\n" +
", account_record_id\n" +
", tenant_record_id\n" +
")\n" +
"values (\n" +
" :id\n" +
", :tableName\n" +
", :targetRecordId\n" +
", :changeType\n" +
", :createdBy\n" +
", :reasonCode\n" +
", :comments\n" +
", :userToken\n" +
", :createdDate\n" +
", :accountRecordId\n" +
", :tenantRecordId\n" +
")\n" +
";");
}
|
diff --git a/src/vooga/scroller/model/ModelInputs.java b/src/vooga/scroller/model/ModelInputs.java
index f910a792..9a93adc1 100644
--- a/src/vooga/scroller/model/ModelInputs.java
+++ b/src/vooga/scroller/model/ModelInputs.java
@@ -1,96 +1,96 @@
package vooga.scroller.model;
import javax.swing.JComponent;
import util.Vector;
import vooga.scroller.input.AlertObject;
import vooga.scroller.input.Input;
import vooga.scroller.input.InputClassTarget;
import vooga.scroller.input.InputMethodTarget;
import vooga.scroller.input.PositionObject;
import vooga.scroller.sprites.superclasses.Player;
import vooga.scroller.util.Sprite;
/**
* Class that holds all user defined control methods. These methods can work
* on the player used in the construciton of this.
*
* @author Scott Valentine
*
*/
@InputClassTarget
public class ModelInputs {
private static final String TEST_CONTROLS = "vooga/scroller/resources/controls/TestMapping";
private Input myInput;
private Player myPlayer;
/**
* Creates a new set of ModelInputs based on
*
* @param player on which the controls will act
* @param view from where the controls come from.
*/
public ModelInputs (Player player, JComponent view) {
myInput = new Input(TEST_CONTROLS, view);
myPlayer = player;
myInput.addListenerTo(this);
}
// Note, these methods can be redefined to customize games.
// TODO: add more @InputMethodTarget methods
/**
* Player moves up
*
* @param alObj
*/
@InputMethodTarget(name = "jump")
public void jumpInput (AlertObject alObj) {
- if(myPlayer.getVelocity().getRelativeMagnitude(new Vector(Sprite.UP_DIRECTION,myPlayer.getVelocity().getMagnitude())) < 0.5) {
+ if(Math.abs(myPlayer.getVelocity().getComponentVector(Sprite.UP_DIRECTION).getMagnitude()) < 1) {
System.out.println("jump!");
myPlayer.addVector(new Vector(Sprite.UP_DIRECTION, 200));
}
}
/**
* Player moves down
*
* @param alObj
*/
@InputMethodTarget(name = "left")
public void leftInput (AlertObject alObj) {
myPlayer.translate(Player.LEFT_VELOCITY);
}
/**
* Player moves right
*
* @param alObj
*/
@InputMethodTarget(name = "right")
public void rightInput (AlertObject alObj) {
myPlayer.translate(Player.RIGHT_VELOCITY);
}
/**
* Player moves left
* @param alObj
*/
@InputMethodTarget(name = "down")
public void downInput (AlertObject alObj) {
myPlayer.addVector(new Vector(Sprite.DOWN_DIRECTION, 10));
}
@InputMethodTarget(name="test")
public void movementCoordTest(PositionObject posObj) {
myPlayer.setCenter(posObj.getX(), posObj.getY());
}
}
| true | true | public void jumpInput (AlertObject alObj) {
if(myPlayer.getVelocity().getRelativeMagnitude(new Vector(Sprite.UP_DIRECTION,myPlayer.getVelocity().getMagnitude())) < 0.5) {
System.out.println("jump!");
myPlayer.addVector(new Vector(Sprite.UP_DIRECTION, 200));
}
}
| public void jumpInput (AlertObject alObj) {
if(Math.abs(myPlayer.getVelocity().getComponentVector(Sprite.UP_DIRECTION).getMagnitude()) < 1) {
System.out.println("jump!");
myPlayer.addVector(new Vector(Sprite.UP_DIRECTION, 200));
}
}
|
diff --git a/genetica-libraries/src/main/java/umcg/genetica/math/matrix2/MatrixHandling.java b/genetica-libraries/src/main/java/umcg/genetica/math/matrix2/MatrixHandling.java
index 9abf43c2..1710c452 100644
--- a/genetica-libraries/src/main/java/umcg/genetica/math/matrix2/MatrixHandling.java
+++ b/genetica-libraries/src/main/java/umcg/genetica/math/matrix2/MatrixHandling.java
@@ -1,447 +1,447 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package umcg.genetica.math.matrix2;
import cern.colt.matrix.tdouble.DoubleMatrix1D;
import cern.colt.matrix.tdouble.DoubleMatrix2D;
import cern.colt.matrix.tdouble.impl.DenseDoubleMatrix2D;
import cern.colt.matrix.tdouble.impl.DenseLargeDoubleMatrix2D;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.HashSet;
import java.util.LinkedHashMap;
import java.util.Map.Entry;
import org.apache.commons.collections.primitives.ArrayDoubleList;
/**
*
* @author MarcJan
*/
public class MatrixHandling {
/**
* Remove columns with to many missing values
*
* @param dataset DoubleMatrixDataset Expression matrix
* @param hashColumnsToInclude Ids of samples to include
* @param missingValue, missing value to check on. If not neccesary put to double.NaN
*/
public static void RemoveColumnsWithToManyMissingValues(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, int maxMissingValuesPerColumn, double missingValue) {
HashSet<String> columnsToInclude = new HashSet<String>();
for (int c = 0; c < dataset.columns(); ++c) {
int nrMissing = 0;
for (int r = 0; r < dataset.rows(); ++r) {
if (dataset.getMatrix().get(r, c) == missingValue || Double.isNaN(dataset.getMatrix().get(r, c))) {
nrMissing++;
}
}
if (nrMissing >= maxMissingValuesPerColumn) {
System.out.println("Excluding:\t" + c + "\t" + dataset.getColObjects().get(c) + "\t" + nrMissing);
} else {
columnsToInclude.add(dataset.getColObjects().get(c));
}
}
CreatSubsetBasedOnColumns(dataset, columnsToInclude, true);
}
/**
* Remove rows with to many missing values
*
* @param dataset DoubleMatrixDataset Expression matrix
* @param hashRowsToInclude Ids of rowss to include
* @param missingValue, missing value to check on. If not neccesary put to double.NaN
*/
public static void RemoveRowsWithToManyMissingValues(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, int maxMissingValuesPerRow, double missingValue) {
String[] rowNames = dataset.getRowObjects().toArray(new String[0]);
HashSet<String> hashRowsToInclude = new HashSet<String>();
for (int r = 0; r < dataset.rows(); ++r) {
int nrMissing = 0;
for (int c = 0; c < dataset.columns(); ++c) {
if (dataset.getMatrix().get(r, c) == missingValue || Double.isNaN(dataset.getMatrix().get(r, c))) {
nrMissing++;
}
}
if (nrMissing >= maxMissingValuesPerRow) {
System.out.println("Excluding:\t" + r + "\t" + rowNames[r] + "\t" + nrMissing);
}else {
hashRowsToInclude.add(rowNames[r]);
}
}
CreatSubsetBasedOnRows(dataset, hashRowsToInclude, false);
}
/**
* Remove identical samples, based on all expression values
*
* @param dataset DoubleMatrixDataset Expression matrix
*/
public static void RemoveDuplicatesSamples(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset) {
HashSet<String> removeEntry = new HashSet<String>();
for (int c = 0; c < dataset.columns(); ++c) {
DoubleMatrix1D colc = dataset.getMatrix().viewColumn(c);
for (int c2 = 0; c2 < dataset.columns(); ++c2) {
DoubleMatrix1D colc2 = dataset.getMatrix().viewColumn(c2);
boolean identical = true;
for(int r=0; r < dataset.rows(); ++r){
if(colc.getQuick(r) != colc2.getQuick(r)){
identical = false;
break;
}
}
if(identical){
removeEntry.add(dataset.getColObjects().get(c));
}
}
}
if (removeEntry.size() > 0) {
RemoveColumns(dataset, removeEntry);
}
}
/**
* Append a static prefix to the column names
*
* @param in
* @param prefix
*/
public static void appendPrefixToColnames(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> in, String prefix) {
LinkedHashMap<String, Integer> newColObjects = new LinkedHashMap<String, Integer>();
for (Entry<String, Integer> t : in.getHashCols().entrySet()) {
StringBuilder colName = new StringBuilder();
colName.append(prefix);
colName.append("_");
colName.append(t);
newColObjects.put(colName.toString(), t.getValue());
}
in.setHashCols(newColObjects);
}
/**
* Replace missing values in the double matrix per sample. Using either the
* mean if useMedian is false or the median is useMedian is true.
*
* @param rawData
* @param useMedian
* @param NaValue
*/
public static void ReplaceMissingValuesPerColumn(DoubleMatrix2D rawData, boolean useMedian, double NaValue) {
for (int s = 0; s < rawData.columns(); ++s) {
System.out.println("Processing sample: " + s);
boolean needsReplacement = false;
ArrayDoubleList nonNAvalues = new ArrayDoubleList();
for (int p = 0; p < rawData.rows(); ++p) {
if (rawData.get(p, s) == NaValue) {
needsReplacement = true;
} else {
nonNAvalues.add(rawData.get(p, s));
}
}
if (needsReplacement) {
double replacementValue;
if (useMedian) {
replacementValue = JSci.maths.ArrayMath.median(nonNAvalues.toArray(new double[0]));
} else {
replacementValue = JSci.maths.ArrayMath.mean(nonNAvalues.toArray(new double[0]));
}
for (int p = 0; p < rawData.rows(); ++p) {
if (rawData.get(p, s) == NaValue) {
rawData.set(p, s, replacementValue);
}
}
}
}
}
/**
* Replace missing values in the double matrix per sample. Using either the
* mean if useMedian is false or the median is useMedian is true.
*
* @param rawData
* @param useMedian
* @param NaValue
*/
public static void ReplaceMissingValuesPerRow(DoubleMatrix2D rawData, boolean useMedian, double NaValue) {
for (int p = 0; p < rawData.rows(); ++p) {
System.out.println("Processing row: " + p);
boolean needsReplacement = false;
ArrayDoubleList nonNAvalues = new ArrayDoubleList();
for (int s = 0; s < rawData.rows(); ++s) {
if (rawData.get(p, s) == NaValue) {
needsReplacement = true;
} else {
nonNAvalues.add(rawData.get(p, s));
}
}
if (needsReplacement) {
double replacementValue;
if (useMedian) {
replacementValue = JSci.maths.ArrayMath.median(nonNAvalues.toArray(new double[0]));
} else {
replacementValue = JSci.maths.ArrayMath.mean(nonNAvalues.toArray(new double[0]));
}
for (int s = 0; s < rawData.rows(); ++s) {
if (rawData.get(p, s) == NaValue) {
rawData.set(p, s, replacementValue);
}
}
}
}
}
//Hier moeten we nog even aan sleutelen.
/**
* Remove probes without correct mapping known on forehand
*
* @param dataset DoubleMatrixDataset containing the matrix of interest
* @param probesToBeRemoved ArrayList<String> with identifiers of probes
* that should be removed
*/
public static DoubleMatrixDataset<String, String> RemoveProbes(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, HashSet<String> probesToBeRemoved) {
return CreatSubsetBasedOnRows(dataset, probesToBeRemoved, true);
}
private static void fixOrdering(LinkedHashMap<String, Integer> hashMap) {
int i=0;
for(Entry<String, Integer> e : hashMap.entrySet()){
e.setValue(i);
i++;
}
}
public static void RenameRows(DoubleMatrixDataset<String, ?> dataset, HashMap<String, String> mappedProbeList) {
LinkedHashMap<String, Integer> newRowNames = new LinkedHashMap<String, Integer>(dataset.rows());
for (Entry<String, Integer> e : dataset.getHashRows().entrySet()) {
if ((mappedProbeList.containsKey(e.getKey()))) {
newRowNames.put(mappedProbeList.get(e.getKey()), e.getValue());
} else {
newRowNames.put(e.getKey(), e.getValue());
}
}
dataset.setHashRows(newRowNames);
}
/**
* Remove rows without correct mapping known on forehand
*
* @param dataset DoubleMatrixDataset containing the matrix of interest
* @param probesToBeRemoved ArrayList<String> with identifiers of probes
* that should be removed
*/
public DoubleMatrixDataset<String, String> RemoveRows(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, HashSet<String> probesToBeRemoved) {
return CreatSubsetBasedOnRows(dataset, probesToBeRemoved, true);
}
/**
* Remove or filter rows.
*
* @param dataset DoubleMatrixDataset containing the matrix of interest
* @param rowNames ArrayList<String> with identifiers of probes that
* @param removeRows, if true row ids in rowNames are removed if false rowNames are selected others are removed.
* should be removed
*/
public static DoubleMatrixDataset<String, String> CreatSubsetBasedOnRows(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, HashSet<String> rowNames, boolean removeRows) {
int newSize = 0;
HashSet<String> removeList = new HashSet<String>();
if(removeRows){
for (String t : dataset.getRowObjects()) {
if (!rowNames.contains(t)) {
newSize++;
} else {
removeList.add(t);
}
}
if(removeList.isEmpty()){
return(dataset);
}
} else {
for (String t : dataset.getRowObjects()) {
if (rowNames.contains(t)) {
newSize++;
} else {
removeList.add(t);
}
}
if(newSize == dataset.rows()){
return(dataset);
}
}
double[][] newRawData = new double[newSize][dataset.columns()];
int probeId = -1;
ArrayList<String> rowObj = dataset.getRowObjects();
if(removeRows){
for (int p = 0; p < dataset.rows(); ++p) {
if (!(rowNames.contains(rowObj.get(p)))) {
probeId++;
newRawData[probeId] = dataset.getMatrix().viewRow(p).toArray();
}
}
} else {
for (int p = 0; p < dataset.rows(); ++p) {
if ((rowNames.contains(rowObj.get(p)))) {
probeId++;
newRawData[probeId] = dataset.getMatrix().viewRow(p).toArray();
}
}
}
for (String r : removeList) {
dataset.hashRows.remove(r);
}
fixOrdering(dataset.hashRows);
if ((dataset.columns() * newRawData.length) < (Integer.MAX_VALUE - 2)) {
dataset = new SmallDoubleMatrixDataset<String, String>(new DenseDoubleMatrix2D(newRawData), dataset.hashRows, dataset.hashCols);
} else {
DenseLargeDoubleMatrix2D matrix = new DenseLargeDoubleMatrix2D(newRawData.length, dataset.columns());
matrix.assign(newRawData);
dataset = new LargeDoubleMatrixDataset<String, String>(matrix, dataset.hashRows, dataset.hashCols);
}
return(dataset);
}
/**
* Remove samples on forehand
*
* @param dataset DoubleMatrixDataset containing the matrix of interest
* @param samplesToBeRemoved ArrayList<String> with identifiers of probes
* that should be removed
*/
public static DoubleMatrixDataset<String, String> RemoveSamples(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, HashSet<String> samplesToBeRemoved) {
return CreatSubsetBasedOnColumns(dataset, samplesToBeRemoved, true);
}
/**
* Remove samples on forehand
*
* @param dataset DoubleMatrixDataset containing the matrix of interest
* @param samplesToBeRemoved ArrayList<String> with identifiers of probes
* that should be removed
*/
public static DoubleMatrixDataset<String, String> RemoveColumns(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, HashSet<String> samplesToBeRemoved) {
return CreatSubsetBasedOnColumns(dataset, samplesToBeRemoved, true);
}
/**
* Filter out columns.
* Keep all columns that in in the hashset.
*
* @param dataset
* @param colNames
* @param remove, if true col ids in colNames are removed if false colNames are selected others are removed.
*/
public static DoubleMatrixDataset<String, String> CreatSubsetBasedOnColumns(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, HashSet<String> colNames, boolean remove) {
int newSize = 0;
HashSet<String> removeList = new HashSet<String>();
if(remove){
for (String t : dataset.getColObjects()) {
if (!colNames.contains(t)) {
newSize++;
} else {
removeList.add(t);
- }
- if(removeList.isEmpty()){
- return(dataset);
- }
+ }
+ }
+ if(removeList.isEmpty()){
+ return(dataset);
}
} else {
for (String t : dataset.getColObjects()) {
if (colNames.contains(t)) {
newSize++;
} else {
removeList.add(t);
}
}
if(newSize == dataset.columns()){
return(dataset);
}
}
double[][] newRawData = new double[dataset.rows()][newSize];
int sampleId = -1;
ArrayList<String> colObj = dataset.getColObjects();
if(remove){
for (int s = 0; s < dataset.columns(); ++s) {
if (!(colNames.contains(colObj.get(s)))) {
sampleId++;
for (int p = 0; p < dataset.rows(); ++p) {
newRawData[p][sampleId] = dataset.getMatrix().get(p, s);
}
}
}
} else {
for (int s = 0; s < dataset.columns(); ++s) {
if ((colNames.contains(colObj.get(s)))) {
sampleId++;
for (int p = 0; p < dataset.rows(); ++p) {
newRawData[p][sampleId] = dataset.getMatrix().get(p, s);
}
}
}
}
for (String r : removeList) {
dataset.hashCols.remove(r);
}
fixOrdering(dataset.hashCols);
if ((dataset.rows() * newRawData[0].length) < (Integer.MAX_VALUE - 2)) {
dataset = new SmallDoubleMatrixDataset<String, String>(new DenseDoubleMatrix2D(newRawData), dataset.hashRows, dataset.hashCols);
} else {
DenseLargeDoubleMatrix2D matrix = new DenseLargeDoubleMatrix2D(dataset.rows(), newRawData[0].length);
matrix.assign(newRawData);
dataset = new LargeDoubleMatrixDataset<String, String>(matrix, dataset.hashRows, dataset.hashCols);
}
return(dataset);
}
public static void RenameCols(umcg.genetica.math.matrix2.DoubleMatrixDataset<?, String> dataset, HashMap<String, String> newNames) {
LinkedHashMap<String, Integer> newColNames = new LinkedHashMap<String, Integer>(dataset.columns());
for (Entry<String, Integer> e : dataset.getHashCols().entrySet()) {
if ((newNames.containsKey(e.getKey()))) {
newColNames.put(newNames.get(e.getKey()), e.getValue());
} else {
newColNames.put(e.getKey(), e.getValue());
}
}
dataset.setHashCols(newColNames);
}
}
| true | true | public static DoubleMatrixDataset<String, String> CreatSubsetBasedOnColumns(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, HashSet<String> colNames, boolean remove) {
int newSize = 0;
HashSet<String> removeList = new HashSet<String>();
if(remove){
for (String t : dataset.getColObjects()) {
if (!colNames.contains(t)) {
newSize++;
} else {
removeList.add(t);
}
if(removeList.isEmpty()){
return(dataset);
}
}
} else {
for (String t : dataset.getColObjects()) {
if (colNames.contains(t)) {
newSize++;
} else {
removeList.add(t);
}
}
if(newSize == dataset.columns()){
return(dataset);
}
}
double[][] newRawData = new double[dataset.rows()][newSize];
int sampleId = -1;
ArrayList<String> colObj = dataset.getColObjects();
if(remove){
for (int s = 0; s < dataset.columns(); ++s) {
if (!(colNames.contains(colObj.get(s)))) {
sampleId++;
for (int p = 0; p < dataset.rows(); ++p) {
newRawData[p][sampleId] = dataset.getMatrix().get(p, s);
}
}
}
} else {
for (int s = 0; s < dataset.columns(); ++s) {
if ((colNames.contains(colObj.get(s)))) {
sampleId++;
for (int p = 0; p < dataset.rows(); ++p) {
newRawData[p][sampleId] = dataset.getMatrix().get(p, s);
}
}
}
}
for (String r : removeList) {
dataset.hashCols.remove(r);
}
fixOrdering(dataset.hashCols);
if ((dataset.rows() * newRawData[0].length) < (Integer.MAX_VALUE - 2)) {
dataset = new SmallDoubleMatrixDataset<String, String>(new DenseDoubleMatrix2D(newRawData), dataset.hashRows, dataset.hashCols);
} else {
DenseLargeDoubleMatrix2D matrix = new DenseLargeDoubleMatrix2D(dataset.rows(), newRawData[0].length);
matrix.assign(newRawData);
dataset = new LargeDoubleMatrixDataset<String, String>(matrix, dataset.hashRows, dataset.hashCols);
}
return(dataset);
}
| public static DoubleMatrixDataset<String, String> CreatSubsetBasedOnColumns(umcg.genetica.math.matrix2.DoubleMatrixDataset<String, String> dataset, HashSet<String> colNames, boolean remove) {
int newSize = 0;
HashSet<String> removeList = new HashSet<String>();
if(remove){
for (String t : dataset.getColObjects()) {
if (!colNames.contains(t)) {
newSize++;
} else {
removeList.add(t);
}
}
if(removeList.isEmpty()){
return(dataset);
}
} else {
for (String t : dataset.getColObjects()) {
if (colNames.contains(t)) {
newSize++;
} else {
removeList.add(t);
}
}
if(newSize == dataset.columns()){
return(dataset);
}
}
double[][] newRawData = new double[dataset.rows()][newSize];
int sampleId = -1;
ArrayList<String> colObj = dataset.getColObjects();
if(remove){
for (int s = 0; s < dataset.columns(); ++s) {
if (!(colNames.contains(colObj.get(s)))) {
sampleId++;
for (int p = 0; p < dataset.rows(); ++p) {
newRawData[p][sampleId] = dataset.getMatrix().get(p, s);
}
}
}
} else {
for (int s = 0; s < dataset.columns(); ++s) {
if ((colNames.contains(colObj.get(s)))) {
sampleId++;
for (int p = 0; p < dataset.rows(); ++p) {
newRawData[p][sampleId] = dataset.getMatrix().get(p, s);
}
}
}
}
for (String r : removeList) {
dataset.hashCols.remove(r);
}
fixOrdering(dataset.hashCols);
if ((dataset.rows() * newRawData[0].length) < (Integer.MAX_VALUE - 2)) {
dataset = new SmallDoubleMatrixDataset<String, String>(new DenseDoubleMatrix2D(newRawData), dataset.hashRows, dataset.hashCols);
} else {
DenseLargeDoubleMatrix2D matrix = new DenseLargeDoubleMatrix2D(dataset.rows(), newRawData[0].length);
matrix.assign(newRawData);
dataset = new LargeDoubleMatrixDataset<String, String>(matrix, dataset.hashRows, dataset.hashCols);
}
return(dataset);
}
|
diff --git a/src/main/java/com/akzia/googleapi/geocoding/Result.java b/src/main/java/com/akzia/googleapi/geocoding/Result.java
index f126530..8fda2c2 100644
--- a/src/main/java/com/akzia/googleapi/geocoding/Result.java
+++ b/src/main/java/com/akzia/googleapi/geocoding/Result.java
@@ -1,88 +1,88 @@
package com.akzia.googleapi.geocoding;
import com.google.gson.annotations.SerializedName;
import java.util.List;
public class Result {
/**
* formatted_address is a string containing the human-readable address of this location.
* Often this address is equivalent to the "postal address," which sometimes differs from country to country.
* (Note that some countries, such as the United Kingdom, do not allow distribution of true postal addresses
* due to licensing restrictions.) This address is generally composed of one or more address components.
* For example, the address "111 8th Avenue, New York, NY" contains separate address components for "111"
* (the street number, "8th Avenue" (the route), "New York" (the city) and "NY" (the US state).
* These address components contain additional information as noted below.
*/
@SerializedName("formatted_address")
private String formattedAddress;
@SerializedName("geometry")
private Geometry geometry;
/**
* containing the separate address components
*/
@SerializedName("address_components")
private List<AddressComponent> addressComponents;
public Result() {
}
public String getFormattedAddress() {
return formattedAddress;
}
public void setFormattedAddress(String formattedAddress) {
this.formattedAddress = formattedAddress;
}
public Geometry getGeometry() {
return geometry;
}
public void setGeometry(Geometry geometry) {
this.geometry = geometry;
}
public List<AddressComponent> getAddressComponents() {
return addressComponents;
}
public void setAddressComponents(List<AddressComponent> addressComponents) {
this.addressComponents = addressComponents;
}
public String getFormattedResult() {
String streetAddress = null;
String streetNumber = null;
String city = null;
for (AddressComponent component : getAddressComponents()) {
if (component.getTypes().contains(Type.STREET_NUMBER)) {
streetNumber = component.getShortName();
} else if (component.getTypes().contains(Type.STREET_ADDRESS)) {
streetAddress = component.getShortName();
} else if (component.getTypes().contains(Type.ROUTE)) {
streetAddress = component.getShortName();
} else if (component.getTypes().contains(Type.LOCALITY)) {
city = component.getShortName();
}
}
if (streetAddress != null && streetNumber != null && city != null) {
- return streetAddress + ", " + streetNumber + ", " + city;
+ return city + ", " + streetAddress + ", " + streetNumber;
} else {
return getFormattedAddress();
}
}
@Override
public String toString() {
return "Result{" +
"formattedAddress='" + formattedAddress + '\'' +
", geometry=" + geometry +
", addressComponents=" + addressComponents +
'}';
}
}
| true | true | public String getFormattedResult() {
String streetAddress = null;
String streetNumber = null;
String city = null;
for (AddressComponent component : getAddressComponents()) {
if (component.getTypes().contains(Type.STREET_NUMBER)) {
streetNumber = component.getShortName();
} else if (component.getTypes().contains(Type.STREET_ADDRESS)) {
streetAddress = component.getShortName();
} else if (component.getTypes().contains(Type.ROUTE)) {
streetAddress = component.getShortName();
} else if (component.getTypes().contains(Type.LOCALITY)) {
city = component.getShortName();
}
}
if (streetAddress != null && streetNumber != null && city != null) {
return streetAddress + ", " + streetNumber + ", " + city;
} else {
return getFormattedAddress();
}
}
| public String getFormattedResult() {
String streetAddress = null;
String streetNumber = null;
String city = null;
for (AddressComponent component : getAddressComponents()) {
if (component.getTypes().contains(Type.STREET_NUMBER)) {
streetNumber = component.getShortName();
} else if (component.getTypes().contains(Type.STREET_ADDRESS)) {
streetAddress = component.getShortName();
} else if (component.getTypes().contains(Type.ROUTE)) {
streetAddress = component.getShortName();
} else if (component.getTypes().contains(Type.LOCALITY)) {
city = component.getShortName();
}
}
if (streetAddress != null && streetNumber != null && city != null) {
return city + ", " + streetAddress + ", " + streetNumber;
} else {
return getFormattedAddress();
}
}
|
diff --git a/src/gov/nih/ncgc/bard/search/SolrSearch.java b/src/gov/nih/ncgc/bard/search/SolrSearch.java
index 3ca07d1..f4984d7 100644
--- a/src/gov/nih/ncgc/bard/search/SolrSearch.java
+++ b/src/gov/nih/ncgc/bard/search/SolrSearch.java
@@ -1,217 +1,217 @@
package gov.nih.ncgc.bard.search;
import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.WebResource;
import gov.nih.ncgc.bard.tools.DBUtils;
import nu.xom.*;
import org.apache.solr.client.solrj.SolrQuery;
import org.apache.solr.client.solrj.SolrServerException;
import org.apache.solr.client.solrj.response.QueryResponse;
import org.apache.solr.common.SolrDocument;
import org.apache.solr.common.SolrDocumentList;
import java.net.MalformedURLException;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
/**
* A one line summary.
*
* @author Rajarshi Guha
*/
public abstract class SolrSearch implements ISolrSearch {
protected String query = null;
protected int numHit = -1;
protected List<Facet> facets;
protected SearchResult results = null;
protected String CORE_NAME = null;
protected String solrURL = "http://localhost:8090/solr";
protected SolrSearch(String query) {
this.query = query;
}
public List<Facet> getFacets() {
return facets;
}
public int getHitCount() {
return numHit;
}
public String getQuery() {
return query;
}
public SearchResult getSearchResults() {
return results;
}
public void setSolrURL(String url) {
solrURL = url;
}
public String getSolrURL() {
return solrURL;
}
protected List<SolrDocument> copyRange(List<SolrDocument> docs, Integer skip, Integer top, boolean detailed, String... fields) {
List<SolrDocument> ret = new ArrayList<SolrDocument>();
if (top == null) top = 10;
if (skip == null) skip = 0;
for (int i = skip; i < (skip + top); i++) {
if (i >= docs.size()) continue;
docs.get(i).removeFields("text");
if (!detailed) {
SolrDocument newDoc = new SolrDocument();
for (String field : fields) newDoc.addField(field, docs.get(i).getFieldValue(field));
ret.add(newDoc);
} else ret.add(docs.get(i));
}
return ret;
}
public Map<String, List<String>> suggest(SolrField[] fields, String q, Integer n) throws MalformedURLException, SolrServerException {
return SearchUtil.getTerms(getSolrURL() + CORE_NAME, fields, q + ".*", n);
}
/**
* Get field names associated with a Solr document.
* <p/>
* As we store Solr entity documents in different cores, we can identify fields
* based on the name of the core.
*
* @return A list of {@link SolrField} objects.
* @throws Exception
*/
public List<SolrField> getFieldNames() throws Exception {
if (CORE_NAME == null) throw new Exception("Must have a valid CORE_NAME");
String lukeUrl = getSolrURL() + CORE_NAME + "admin/luke?numTerms=0";
List<SolrField> fieldNames = new ArrayList<SolrField>();
Client client = Client.create();
WebResource resource = client.resource(lukeUrl);
ClientResponse response = resource.get(ClientResponse.class);
int status = response.getStatus();
if (status != 200) {
throw new Exception("There was a problem querying " + lukeUrl);
}
String xml = response.getEntity(String.class);
Document doc = new Builder(false).build(xml, null);
Nodes nodes = doc.query("/response/lst[@name='fields']");
if (nodes.size() > 0) {
Node node = nodes.get(0);
for (int i = 0; i < node.getChildCount(); i++) {
Node n = node.getChild(i);
String name = ((Element) n).getAttribute("name").getValue();
if (name.endsWith("text")) continue;
Node sn = n.getChild(0);
String type = sn.getValue();
fieldNames.add(new SolrField(name, type));
}
}
client.destroy();
return fieldNames;
}
/**
* Initiale highlighting.
* <p/>
* This initialization is pretty much independent of the entity we're searching on, hence
* it's placement in the superclass.
*
* @param solrQuery The query object
* @param highlightField which field to highlight on
* @return the updated query object
*/
protected SolrQuery setHighlighting(SolrQuery solrQuery, String highlightField) {
solrQuery = solrQuery.setHighlight(true).
setHighlightSnippets(1).
setHighlightFragsize(300).
setHighlightSimplePre("<b>").
setHighlightSimplePost("</b>");
return solrQuery.addHighlightField(highlightField);
}
/**
* Convert user specified field based filters to the Solr form.
*
* @param solrQuery the query object
* @param filter the filter string
* @return the updated query object
*/
protected SolrQuery setFilterQueries(SolrQuery solrQuery, String filter) {
if (filter == null) return solrQuery;
try {
List<SolrField> fields = getFieldNames();
List<String> fnames = new ArrayList<String>();
for (SolrField field : fields) fnames.add(field.getName());
Map<String, List<String>> fq = SearchUtil.extractFilterQueries(filter, getFieldNames());
for (Map.Entry<String, List<String>> entry : fq.entrySet()) {
String fname = entry.getKey();
List<String> fvalues = entry.getValue();
if (!fnames.contains(fname)) continue;
StringBuilder sb = new StringBuilder();
sb.append(fvalues.get(0));
for (int i = 1; i < fvalues.size(); i++) {
- if (fvalues.contains("["))
+ if (fvalues.get(i).contains("["))
sb.append(" OR ").append(fvalues.get(i)); // name + ":" + fvalue
else {
sb.append(" OR ").append("\"").append(fvalues.get(i).replace("\"", "")).append("\"");
sb.append(" OR ").append(fvalues.get(i));
}
}
if (fvalues.size() == 1) {
solrQuery.addFilterQuery(fname + ":" + sb.toString()+"");
}
else solrQuery.addFilterQuery(fname + ":(" + sb.toString()+")");
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return solrQuery;
}
protected List<SolrDocument> getHighlightedDocuments(QueryResponse response, String primaryKey, String highlightField) {
List<SolrDocument> docs = new ArrayList<SolrDocument>();
SolrDocumentList sdl = response.getResults();
for (SolrDocument doc : sdl) {
String pkey = (String) doc.getFieldValue(primaryKey);
if (response.getHighlighting() != null && highlightField != null) {
List<String> hls = response.getHighlighting().get(pkey).get(highlightField);
if (hls != null) {
doc.addField("highlight", hls.get(0));
}
}
doc.removeFields("anno_val");
doc.removeFields("anno_key");
docs.add(doc);
}
return docs;
}
protected String putEtag(List<Long> ids, Class klass) throws Exception {
DBUtils db = new DBUtils();
try {
String etag = db.newETag(query, klass.getName());
db.putETag(etag, ids.toArray(new Long[0]));
results.setETag(etag);
return etag;
} finally {
try {
db.closeConnection();
} catch (Exception ex) {
ex.printStackTrace();
}
}
}
}
| true | true | protected SolrQuery setFilterQueries(SolrQuery solrQuery, String filter) {
if (filter == null) return solrQuery;
try {
List<SolrField> fields = getFieldNames();
List<String> fnames = new ArrayList<String>();
for (SolrField field : fields) fnames.add(field.getName());
Map<String, List<String>> fq = SearchUtil.extractFilterQueries(filter, getFieldNames());
for (Map.Entry<String, List<String>> entry : fq.entrySet()) {
String fname = entry.getKey();
List<String> fvalues = entry.getValue();
if (!fnames.contains(fname)) continue;
StringBuilder sb = new StringBuilder();
sb.append(fvalues.get(0));
for (int i = 1; i < fvalues.size(); i++) {
if (fvalues.contains("["))
sb.append(" OR ").append(fvalues.get(i)); // name + ":" + fvalue
else {
sb.append(" OR ").append("\"").append(fvalues.get(i).replace("\"", "")).append("\"");
sb.append(" OR ").append(fvalues.get(i));
}
}
if (fvalues.size() == 1) {
solrQuery.addFilterQuery(fname + ":" + sb.toString()+"");
}
else solrQuery.addFilterQuery(fname + ":(" + sb.toString()+")");
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return solrQuery;
}
| protected SolrQuery setFilterQueries(SolrQuery solrQuery, String filter) {
if (filter == null) return solrQuery;
try {
List<SolrField> fields = getFieldNames();
List<String> fnames = new ArrayList<String>();
for (SolrField field : fields) fnames.add(field.getName());
Map<String, List<String>> fq = SearchUtil.extractFilterQueries(filter, getFieldNames());
for (Map.Entry<String, List<String>> entry : fq.entrySet()) {
String fname = entry.getKey();
List<String> fvalues = entry.getValue();
if (!fnames.contains(fname)) continue;
StringBuilder sb = new StringBuilder();
sb.append(fvalues.get(0));
for (int i = 1; i < fvalues.size(); i++) {
if (fvalues.get(i).contains("["))
sb.append(" OR ").append(fvalues.get(i)); // name + ":" + fvalue
else {
sb.append(" OR ").append("\"").append(fvalues.get(i).replace("\"", "")).append("\"");
sb.append(" OR ").append(fvalues.get(i));
}
}
if (fvalues.size() == 1) {
solrQuery.addFilterQuery(fname + ":" + sb.toString()+"");
}
else solrQuery.addFilterQuery(fname + ":(" + sb.toString()+")");
}
} catch (Exception e) {
e.printStackTrace(); //To change body of catch statement use File | Settings | File Templates.
}
return solrQuery;
}
|
diff --git a/src/main/java/forms/ModelForm.java b/src/main/java/forms/ModelForm.java
index c93b22b..c5fd963 100644
--- a/src/main/java/forms/ModelForm.java
+++ b/src/main/java/forms/ModelForm.java
@@ -1,91 +1,91 @@
package forms;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.HashMap;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
public abstract class ModelForm<T> {
protected T instance;
private ErrorList errors;
public T getInstance() {
return instance;
}
public void setInstance(T instance) {
this.instance = instance;
}
public abstract boolean isValid();
public T save() throws ValidationException {
if ( !isValid() ) {
throw new ValidationException("Form data was not valid");
}
return null;
}
public void clean() {
Method[] methods = this.getClass().getDeclaredMethods();
for ( Method method : methods ) {
if ( method.getName().startsWith("clean") && !method.getName().equals("clean") ) {
method.setAccessible(true);
try {
method.invoke(this);
} catch (IllegalAccessException | InvocationTargetException ignored) {
}
}
}
}
public ErrorList getErrors() {
if ( errors == null )
errors = new ErrorList();
return errors;
}
public String getErrorsDisplay() {
return getErrors().getErrorsDisplay();
}
class ErrorList {
protected Map<String, List<String>> errors;
ErrorList() {
this.errors = new HashMap<>();
}
public void appendError(String field, String message) {
List<String> list = errors.get(field);
if ( list == null )
list = new LinkedList<>();
list.add(message);
errors.put(field, list);
}
public String getErrorsDisplay() {
StringBuilder sb = new StringBuilder("<html>");
sb.append("<h3>Input was not valid</h3>");
for ( Map.Entry<String, List<String>> e : errors.entrySet() ) {
sb.append("<h4>");
sb.append(e.getKey()).append(":");
sb.append("</h4>");
for ( String s : e.getValue() ) {
sb.append("<ul>");
sb.append("<li>");
sb.append(s);
sb.append("</li>");
sb.append("</ul>");
}
- sb.append("</html>");
}
+ sb.append("</html>");
System.out.println(sb.toString());
return sb.toString();
}
}
}
| false | true | public String getErrorsDisplay() {
StringBuilder sb = new StringBuilder("<html>");
sb.append("<h3>Input was not valid</h3>");
for ( Map.Entry<String, List<String>> e : errors.entrySet() ) {
sb.append("<h4>");
sb.append(e.getKey()).append(":");
sb.append("</h4>");
for ( String s : e.getValue() ) {
sb.append("<ul>");
sb.append("<li>");
sb.append(s);
sb.append("</li>");
sb.append("</ul>");
}
sb.append("</html>");
}
System.out.println(sb.toString());
return sb.toString();
}
| public String getErrorsDisplay() {
StringBuilder sb = new StringBuilder("<html>");
sb.append("<h3>Input was not valid</h3>");
for ( Map.Entry<String, List<String>> e : errors.entrySet() ) {
sb.append("<h4>");
sb.append(e.getKey()).append(":");
sb.append("</h4>");
for ( String s : e.getValue() ) {
sb.append("<ul>");
sb.append("<li>");
sb.append(s);
sb.append("</li>");
sb.append("</ul>");
}
}
sb.append("</html>");
System.out.println(sb.toString());
return sb.toString();
}
|
diff --git a/camel-talendjob/src/main/java/org/talend/camel/TalendProducer.java b/camel-talendjob/src/main/java/org/talend/camel/TalendProducer.java
index b1adf4413..084d24522 100644
--- a/camel-talendjob/src/main/java/org/talend/camel/TalendProducer.java
+++ b/camel-talendjob/src/main/java/org/talend/camel/TalendProducer.java
@@ -1,117 +1,117 @@
/*
* #%L
* Camel Talend Job Component
* %%
* Copyright (C) 2011 - 2012 Talend 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.
* #L%
*/
package org.talend.camel;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collection;
import java.util.Map;
import org.apache.camel.Exchange;
import org.apache.camel.RuntimeCamelException;
import org.apache.camel.impl.DefaultProducer;
import org.apache.camel.util.ObjectHelper;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import routines.system.api.TalendJob;
/**
* <p>
* The Talend producer.
* </p>
*/
public class TalendProducer extends DefaultProducer {
private static final transient Logger LOG = LoggerFactory.getLogger(TalendProducer.class);
public TalendProducer(TalendEndpoint endpoint) {
super(endpoint);
}
public void process(Exchange exchange) throws Exception {
TalendJob jobInstance = ((TalendEndpoint) getEndpoint())
.getJobInstance();
String context = ((TalendEndpoint) getEndpoint()).getContext();
Method setExchangeMethod = ((TalendEndpoint) getEndpoint())
.getSetExchangeMethod();
Map<String, String> propertiesMap = getEndpoint()
.getCamelContext().getProperties();
Collection<String> args = new ArrayList<String>();
if (context != null) {
args.add("--context=" + context);
}
if (((TalendEndpoint)getEndpoint()).isPropagateHeader()) {
populateTalendContextParamsWithCamelHeaders(exchange, args);
}
addTalendContextParamsFromCTalendJobContext(propertiesMap, args);
invokeTalendJob(jobInstance, args.toArray(new String[args.size()]), setExchangeMethod, exchange);
}
private static void addTalendContextParamsFromCTalendJobContext(
Map<String, String> propertiesMap, Collection<String> args) {
if (propertiesMap != null) {
for (Map.Entry<String, String> entry : propertiesMap.entrySet()) {
args.add("--context_param " + entry.getKey() + '=' + entry.getValue());
}
}
}
private static void populateTalendContextParamsWithCamelHeaders(Exchange exchange, Collection<String> args) {
Map<String, Object> headers = exchange.getIn().getHeaders();
for (Map.Entry<String, Object> header : headers.entrySet()) {
Object headerValue = header.getValue();
if (headerValue != null) {
String headerStringValue = exchange.getContext().getTypeConverter().convertTo(String.class, exchange, headerValue);
args.add("--context_param " + header.getKey() + '=' + headerStringValue);
}
}
}
private void invokeTalendJob(TalendJob jobInstance, String[] args, Method setExchangeMethod, Exchange exchange) {
if(setExchangeMethod != null){
LOG.debug("Pass the exchange from router to Job");
ObjectHelper.invokeMethod(setExchangeMethod, jobInstance, exchange);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Invoking Talend job '" + jobInstance.getClass().getCanonicalName()
+ ".runJob(String[] args)' with args: " + Arrays.toString(args));
}
ClassLoader oldContextCL = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(jobInstance.getClass().getClassLoader());
int result = jobInstance.runJobInTOS(args);
if (result != 0) {
throw new RuntimeCamelException("Execution of Talend job '"
+ jobInstance.getClass().getCanonicalName() + "' with args: "
- + args.toString() + "' failed, see stderr for details"); // Talend logs errors using System.err.println
+ + Arrays.toString(args) + "' failed, see stderr for details"); // Talend logs errors using System.err.println
}
} finally {
Thread.currentThread().setContextClassLoader(oldContextCL);
}
}
}
| true | true | private void invokeTalendJob(TalendJob jobInstance, String[] args, Method setExchangeMethod, Exchange exchange) {
if(setExchangeMethod != null){
LOG.debug("Pass the exchange from router to Job");
ObjectHelper.invokeMethod(setExchangeMethod, jobInstance, exchange);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Invoking Talend job '" + jobInstance.getClass().getCanonicalName()
+ ".runJob(String[] args)' with args: " + Arrays.toString(args));
}
ClassLoader oldContextCL = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(jobInstance.getClass().getClassLoader());
int result = jobInstance.runJobInTOS(args);
if (result != 0) {
throw new RuntimeCamelException("Execution of Talend job '"
+ jobInstance.getClass().getCanonicalName() + "' with args: "
+ args.toString() + "' failed, see stderr for details"); // Talend logs errors using System.err.println
}
} finally {
Thread.currentThread().setContextClassLoader(oldContextCL);
}
}
| private void invokeTalendJob(TalendJob jobInstance, String[] args, Method setExchangeMethod, Exchange exchange) {
if(setExchangeMethod != null){
LOG.debug("Pass the exchange from router to Job");
ObjectHelper.invokeMethod(setExchangeMethod, jobInstance, exchange);
}
if (LOG.isDebugEnabled()) {
LOG.debug("Invoking Talend job '" + jobInstance.getClass().getCanonicalName()
+ ".runJob(String[] args)' with args: " + Arrays.toString(args));
}
ClassLoader oldContextCL = Thread.currentThread().getContextClassLoader();
try {
Thread.currentThread().setContextClassLoader(jobInstance.getClass().getClassLoader());
int result = jobInstance.runJobInTOS(args);
if (result != 0) {
throw new RuntimeCamelException("Execution of Talend job '"
+ jobInstance.getClass().getCanonicalName() + "' with args: "
+ Arrays.toString(args) + "' failed, see stderr for details"); // Talend logs errors using System.err.println
}
} finally {
Thread.currentThread().setContextClassLoader(oldContextCL);
}
}
|
diff --git a/src/main/java/org/jboss/as/jpa/processor/PersistenceRefProcessor.java b/src/main/java/org/jboss/as/jpa/processor/PersistenceRefProcessor.java
index efbe169..9223ed2 100644
--- a/src/main/java/org/jboss/as/jpa/processor/PersistenceRefProcessor.java
+++ b/src/main/java/org/jboss/as/jpa/processor/PersistenceRefProcessor.java
@@ -1,223 +1,224 @@
/*
* JBoss, Home of Professional Open Source.
* Copyright 2011, Red Hat, Inc., and individual contributors
* as indicated by the @author tags. See the copyright.txt file in the
* distribution for a full listing of individual contributors.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package org.jboss.as.jpa.processor;
import org.jboss.as.ee.component.AbstractDeploymentDescriptorBindingsProcessor;
import org.jboss.as.ee.component.BindingConfiguration;
import org.jboss.as.ee.component.ComponentDescription;
import org.jboss.as.ee.component.DeploymentDescriptorEnvironment;
import org.jboss.as.ee.component.EEModuleDescription;
import org.jboss.as.ee.component.InjectionSource;
import org.jboss.as.ee.component.LookupInjectionSource;
import org.jboss.as.jpa.container.PersistenceUnitSearch;
import org.jboss.as.jpa.injectors.PersistenceContextInjectionSource;
import org.jboss.as.jpa.injectors.PersistenceUnitInjectionSource;
import org.jboss.as.jpa.service.PersistenceUnitService;
import org.jboss.as.server.deployment.DeploymentUnit;
import org.jboss.as.server.deployment.DeploymentUnitProcessingException;
import org.jboss.as.server.deployment.reflect.DeploymentReflectionIndex;
import org.jboss.metadata.javaee.spec.PersistenceContextReferenceMetaData;
import org.jboss.metadata.javaee.spec.PersistenceContextReferencesMetaData;
import org.jboss.metadata.javaee.spec.PersistenceUnitReferenceMetaData;
import org.jboss.metadata.javaee.spec.PersistenceUnitReferencesMetaData;
import org.jboss.metadata.javaee.spec.PropertiesMetaData;
import org.jboss.metadata.javaee.spec.PropertyMetaData;
import org.jboss.msc.service.ServiceName;
import javax.persistence.EntityManager;
import javax.persistence.EntityManagerFactory;
import javax.persistence.PersistenceContextType;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
/**
* Deployment processor responsible for processing persistence unit / context references from deployment descriptors.
*
* @author Stuart Douglas
*/
public class PersistenceRefProcessor extends AbstractDeploymentDescriptorBindingsProcessor {
@Override
protected List<BindingConfiguration> processDescriptorEntries(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, EEModuleDescription moduleDescription, ComponentDescription componentDescription, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex) throws DeploymentUnitProcessingException {
List<BindingConfiguration> bindings = new ArrayList<BindingConfiguration>();
bindings.addAll(getPersistenceUnitRefs(deploymentUnit, environment, classLoader, deploymentReflectionIndex, moduleDescription, componentDescription));
bindings.addAll(getPersistenceContextRefs(deploymentUnit, environment, classLoader, deploymentReflectionIndex, moduleDescription, componentDescription));
return bindings;
}
/**
* Resolves persistence-unit-ref
*
* @param environment The environment to resolve the elements for
* @param classLoader The deployment class loader
* @param deploymentReflectionIndex The reflection index
* @return The bindings for the environment entries
*/
private List<BindingConfiguration> getPersistenceUnitRefs(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, EEModuleDescription moduleDescription, ComponentDescription componentDescription) throws DeploymentUnitProcessingException {
List<BindingConfiguration> bindingConfigurations = new ArrayList<BindingConfiguration>();
if (environment.getEnvironment() == null) {
return bindingConfigurations;
}
PersistenceUnitReferencesMetaData persistenceUnitRefs = environment.getEnvironment().getPersistenceUnitRefs();
if (persistenceUnitRefs != null) {
if (persistenceUnitRefs.size() > 0) {
JPADeploymentMarker.mark(deploymentUnit);
}
for (PersistenceUnitReferenceMetaData puRef : persistenceUnitRefs) {
String name = puRef.getName();
String persistenceUnitName = puRef.getPersistenceUnitName();
String lookup = puRef.getLookupName();
if (!isEmpty(lookup) && !isEmpty(persistenceUnitName)) {
throw new DeploymentUnitProcessingException("Cannot specify both <lookup-name> (" + lookup + ") and persistence-unit-name (" + persistenceUnitName + ") in <persistence-unit-ref/> for " + componentDescription);
}
if (!name.startsWith("java:")) {
name = environment.getDefaultContext() + name;
}
// our injection (source) comes from the local (ENC) lookup, no matter what.
LookupInjectionSource injectionSource = new LookupInjectionSource(name);
//add any injection targets
processInjectionTargets(moduleDescription, injectionSource, classLoader, deploymentReflectionIndex, puRef, EntityManagerFactory.class);
BindingConfiguration bindingConfiguration = null;
if (!isEmpty(lookup)) {
bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(lookup));
} else if (!isEmpty(persistenceUnitName)) {
InjectionSource puBindingSource = this.getPersistenceUnitBindingSource(deploymentUnit, persistenceUnitName);
bindingConfiguration = new BindingConfiguration(name, puBindingSource);
} else {
throw new RuntimeException("Support for persistence-unit-ref without a lookup or persistence-unit-name, isn't yet implemented");
}
bindingConfigurations.add(bindingConfiguration);
}
}
return bindingConfigurations;
}
/**
* Resolves persistence-unit-ref
*
* @param environment The environment to resolve the elements for
* @param classLoader The deployment class loader
* @param deploymentReflectionIndex The reflection index
* @return The bindings for the environment entries
*/
private List<BindingConfiguration> getPersistenceContextRefs(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, EEModuleDescription moduleDescription, ComponentDescription componentDescription) throws DeploymentUnitProcessingException {
List<BindingConfiguration> bindingConfigurations = new ArrayList<BindingConfiguration>();
if (environment.getEnvironment() == null) {
return bindingConfigurations;
}
PersistenceContextReferencesMetaData persistenceUnitRefs = environment.getEnvironment().getPersistenceContextRefs();
if (persistenceUnitRefs != null) {
for (PersistenceContextReferenceMetaData puRef : persistenceUnitRefs) {
String name = puRef.getName();
String persistenceUnitName = puRef.getPersistenceUnitName();
String lookup = puRef.getLookupName();
if (!isEmpty(lookup) && !isEmpty(persistenceUnitName)) {
throw new DeploymentUnitProcessingException("Cannot specify both <lookup-name> (" + lookup + ") and persistence-unit-name (" + persistenceUnitName + ") in <persistence-context-ref/> for " + componentDescription);
}
if (!name.startsWith("java:")) {
name = environment.getDefaultContext() + name;
}
// our injection (source) comes from the local (ENC) lookup, no matter what.
LookupInjectionSource injectionSource = new LookupInjectionSource(name);
//add any injection targets
processInjectionTargets(moduleDescription, injectionSource, classLoader, deploymentReflectionIndex, puRef, EntityManager.class);
BindingConfiguration bindingConfiguration = null;
if (!isEmpty(lookup)) {
bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(lookup));
} else if (!isEmpty(persistenceUnitName)) {
PropertiesMetaData properties = puRef.getProperties();
Map map = new HashMap();
if (properties != null) {
for (PropertyMetaData prop : properties) {
map.put(prop.getKey(), prop.getValue());
}
}
PersistenceContextType type = puRef.getPersistenceContextType() == null ? PersistenceContextType.TRANSACTION : puRef.getPersistenceContextType();
InjectionSource pcBindingSource = this.getPersistenceContextBindingSource(deploymentUnit, persistenceUnitName, type, map);
bindingConfiguration = new BindingConfiguration(name, pcBindingSource);
} else {
throw new RuntimeException("Support for persistence-context-ref without a lookup or persistence-unit-name, isn't yet implemented");
}
+ bindingConfigurations.add(bindingConfiguration);
}
}
return bindingConfigurations;
}
private InjectionSource getPersistenceUnitBindingSource(
final DeploymentUnit deploymentUnit,
final String unitName)
throws DeploymentUnitProcessingException {
String scopedPuName = getScopedPuName(deploymentUnit, unitName);
ServiceName puServiceName = getPuServiceName(scopedPuName);
return new PersistenceUnitInjectionSource(puServiceName, deploymentUnit, scopedPuName, EntityManagerFactory.class.getName());
}
private InjectionSource getPersistenceContextBindingSource(
final DeploymentUnit deploymentUnit,
final String unitName, PersistenceContextType type, Map properties)
throws DeploymentUnitProcessingException {
String scopedPuName = getScopedPuName(deploymentUnit, unitName);
ServiceName puServiceName = getPuServiceName(scopedPuName);
return new PersistenceContextInjectionSource(type, properties, puServiceName, deploymentUnit, scopedPuName, EntityManager.class.getName());
}
private String getScopedPuName(final DeploymentUnit deploymentUnit, final String puName)
throws DeploymentUnitProcessingException {
String scopedPuName;
scopedPuName = PersistenceUnitSearch.resolvePersistenceUnitSupplier(deploymentUnit, puName);
if (null == scopedPuName) {
throw new DeploymentUnitProcessingException("Can't find a deployment unit named " + puName + " at " + deploymentUnit);
}
return scopedPuName;
}
private ServiceName getPuServiceName(String scopedPuName)
throws DeploymentUnitProcessingException {
return PersistenceUnitService.getPUServiceName(scopedPuName);
}
private boolean isEmpty(String string) {
return string == null || string.isEmpty();
}
}
| true | true | private List<BindingConfiguration> getPersistenceContextRefs(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, EEModuleDescription moduleDescription, ComponentDescription componentDescription) throws DeploymentUnitProcessingException {
List<BindingConfiguration> bindingConfigurations = new ArrayList<BindingConfiguration>();
if (environment.getEnvironment() == null) {
return bindingConfigurations;
}
PersistenceContextReferencesMetaData persistenceUnitRefs = environment.getEnvironment().getPersistenceContextRefs();
if (persistenceUnitRefs != null) {
for (PersistenceContextReferenceMetaData puRef : persistenceUnitRefs) {
String name = puRef.getName();
String persistenceUnitName = puRef.getPersistenceUnitName();
String lookup = puRef.getLookupName();
if (!isEmpty(lookup) && !isEmpty(persistenceUnitName)) {
throw new DeploymentUnitProcessingException("Cannot specify both <lookup-name> (" + lookup + ") and persistence-unit-name (" + persistenceUnitName + ") in <persistence-context-ref/> for " + componentDescription);
}
if (!name.startsWith("java:")) {
name = environment.getDefaultContext() + name;
}
// our injection (source) comes from the local (ENC) lookup, no matter what.
LookupInjectionSource injectionSource = new LookupInjectionSource(name);
//add any injection targets
processInjectionTargets(moduleDescription, injectionSource, classLoader, deploymentReflectionIndex, puRef, EntityManager.class);
BindingConfiguration bindingConfiguration = null;
if (!isEmpty(lookup)) {
bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(lookup));
} else if (!isEmpty(persistenceUnitName)) {
PropertiesMetaData properties = puRef.getProperties();
Map map = new HashMap();
if (properties != null) {
for (PropertyMetaData prop : properties) {
map.put(prop.getKey(), prop.getValue());
}
}
PersistenceContextType type = puRef.getPersistenceContextType() == null ? PersistenceContextType.TRANSACTION : puRef.getPersistenceContextType();
InjectionSource pcBindingSource = this.getPersistenceContextBindingSource(deploymentUnit, persistenceUnitName, type, map);
bindingConfiguration = new BindingConfiguration(name, pcBindingSource);
} else {
throw new RuntimeException("Support for persistence-context-ref without a lookup or persistence-unit-name, isn't yet implemented");
}
}
}
return bindingConfigurations;
}
| private List<BindingConfiguration> getPersistenceContextRefs(DeploymentUnit deploymentUnit, DeploymentDescriptorEnvironment environment, ClassLoader classLoader, DeploymentReflectionIndex deploymentReflectionIndex, EEModuleDescription moduleDescription, ComponentDescription componentDescription) throws DeploymentUnitProcessingException {
List<BindingConfiguration> bindingConfigurations = new ArrayList<BindingConfiguration>();
if (environment.getEnvironment() == null) {
return bindingConfigurations;
}
PersistenceContextReferencesMetaData persistenceUnitRefs = environment.getEnvironment().getPersistenceContextRefs();
if (persistenceUnitRefs != null) {
for (PersistenceContextReferenceMetaData puRef : persistenceUnitRefs) {
String name = puRef.getName();
String persistenceUnitName = puRef.getPersistenceUnitName();
String lookup = puRef.getLookupName();
if (!isEmpty(lookup) && !isEmpty(persistenceUnitName)) {
throw new DeploymentUnitProcessingException("Cannot specify both <lookup-name> (" + lookup + ") and persistence-unit-name (" + persistenceUnitName + ") in <persistence-context-ref/> for " + componentDescription);
}
if (!name.startsWith("java:")) {
name = environment.getDefaultContext() + name;
}
// our injection (source) comes from the local (ENC) lookup, no matter what.
LookupInjectionSource injectionSource = new LookupInjectionSource(name);
//add any injection targets
processInjectionTargets(moduleDescription, injectionSource, classLoader, deploymentReflectionIndex, puRef, EntityManager.class);
BindingConfiguration bindingConfiguration = null;
if (!isEmpty(lookup)) {
bindingConfiguration = new BindingConfiguration(name, new LookupInjectionSource(lookup));
} else if (!isEmpty(persistenceUnitName)) {
PropertiesMetaData properties = puRef.getProperties();
Map map = new HashMap();
if (properties != null) {
for (PropertyMetaData prop : properties) {
map.put(prop.getKey(), prop.getValue());
}
}
PersistenceContextType type = puRef.getPersistenceContextType() == null ? PersistenceContextType.TRANSACTION : puRef.getPersistenceContextType();
InjectionSource pcBindingSource = this.getPersistenceContextBindingSource(deploymentUnit, persistenceUnitName, type, map);
bindingConfiguration = new BindingConfiguration(name, pcBindingSource);
} else {
throw new RuntimeException("Support for persistence-context-ref without a lookup or persistence-unit-name, isn't yet implemented");
}
bindingConfigurations.add(bindingConfiguration);
}
}
return bindingConfigurations;
}
|
diff --git a/application/src/main/java/org/richfaces/tests/metamer/bean/RichToggleControlBean.java b/application/src/main/java/org/richfaces/tests/metamer/bean/RichToggleControlBean.java
index 8c0d2c84..0f8dd470 100644
--- a/application/src/main/java/org/richfaces/tests/metamer/bean/RichToggleControlBean.java
+++ b/application/src/main/java/org/richfaces/tests/metamer/bean/RichToggleControlBean.java
@@ -1,74 +1,74 @@
/*******************************************************************************
* JBoss, Home of Professional Open Source
* Copyright 2010, Red Hat, Inc. 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.richfaces.tests.metamer.bean;
import java.io.Serializable;
import javax.annotation.PostConstruct;
import javax.faces.bean.ManagedBean;
import javax.faces.bean.ViewScoped;
import org.richfaces.component.behavior.ToggleControl;
import org.richfaces.tests.metamer.Attributes;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
/**
* Managed bean for rich:toggleControl.
*
* @author <a href="mailto:[email protected]">Pavol Pitonak</a>
* @version $Revision$
*/
@ManagedBean(name = "richToggleControlBean")
@ViewScoped
public class RichToggleControlBean implements Serializable {
private static final long serialVersionUID = -1L;
private static Logger logger;
private Attributes attributes;
/**
* Initializes the managed bean.
*/
@PostConstruct
public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getBehaviorAttributes(ToggleControl.class, getClass());
- attributes.setAttribute("forPanel", "panel1");
+ attributes.setAttribute("targetPanel", "panel1");
attributes.setAttribute("targetItem", "item1");
// TODO following attributes have to be tested in another way
attributes.remove("disableDefault");
attributes.remove("event"); // has to be literal
}
public Attributes getAttributes() {
return attributes;
}
public void setAttributes(Attributes attributes) {
this.attributes = attributes;
}
}
| true | true | public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getBehaviorAttributes(ToggleControl.class, getClass());
attributes.setAttribute("forPanel", "panel1");
attributes.setAttribute("targetItem", "item1");
// TODO following attributes have to be tested in another way
attributes.remove("disableDefault");
attributes.remove("event"); // has to be literal
}
| public void init() {
logger = LoggerFactory.getLogger(getClass());
logger.debug("initializing bean " + getClass().getName());
attributes = Attributes.getBehaviorAttributes(ToggleControl.class, getClass());
attributes.setAttribute("targetPanel", "panel1");
attributes.setAttribute("targetItem", "item1");
// TODO following attributes have to be tested in another way
attributes.remove("disableDefault");
attributes.remove("event"); // has to be literal
}
|
diff --git a/WordToGuess.java b/WordToGuess.java
index 248e631..e3d5502 100644
--- a/WordToGuess.java
+++ b/WordToGuess.java
@@ -1,98 +1,98 @@
import greenfoot.*; // (World, Actor, GreenfootImage, Greenfoot and MouseInfo)
/**
* Write a description of class WordToGuess here.
*
* @author (your name)
* @version (a version number or a date)
*/
public class WordToGuess extends Actor
{
/**
* Act - do whatever the WordToGuess wants to do. This method is called whenever
* the 'Act' or 'Run' button gets pressed in the environment.
*/
//private String alphabetGuessed;
private String word;
private int indexOfAlphabet;
World world;
public WordToGuess(){
indexOfAlphabet =0;
}
public void act()
{
// Add your action code here.
}
public void setAlphabetGuessed(String alphabet, World w)
{
System.out.println("User guessed "+ alphabet);
world =w;
//word = WordList.getWord();
checkForLetterInString(alphabet);
}
private void placeGuessedAlphabet(String alphabet, int[] arr, int size){
int xAlpha, yAlpha, j;
xAlpha =50;
yAlpha = 100 ;
j=0;
for(int i=0; (i<word.length())&&(size > 0); i++)
{
if(arr[j]== i){
System.out.println("inside draw");
Message message = new Message(alphabet);
world.addObject(message, xAlpha,yAlpha-20);
j++;
size--;
}
xAlpha+=70;
}
}
private void checkForLetterInString(String alphabet){
String wordFromDB = WordList.getWord();
word = wordFromDB.toUpperCase();
System.out.println("word is "+ word);
int[] alphabetPosition = new int[word.length()];
int index =0;
int size = -1;
int pos =0;
- for(int i=index;i< word.length(); i ++){
+ for(int i=pos;i< word.length(); i ++){
if((index =word.indexOf(alphabet, pos))!= -1){
System.out.println("inside if");
alphabetPosition[++size]= index;
- pos++;
+ pos=index+1;
}
else
break;
}
if(size != -1){
placeGuessedAlphabet(alphabet, alphabetPosition, size+1);
System.out.println("leter there");
}
else
System.out.println("Letter is not present");
}
}
| false | true | private void checkForLetterInString(String alphabet){
String wordFromDB = WordList.getWord();
word = wordFromDB.toUpperCase();
System.out.println("word is "+ word);
int[] alphabetPosition = new int[word.length()];
int index =0;
int size = -1;
int pos =0;
for(int i=index;i< word.length(); i ++){
if((index =word.indexOf(alphabet, pos))!= -1){
System.out.println("inside if");
alphabetPosition[++size]= index;
pos++;
}
else
break;
}
if(size != -1){
placeGuessedAlphabet(alphabet, alphabetPosition, size+1);
System.out.println("leter there");
}
else
System.out.println("Letter is not present");
}
| private void checkForLetterInString(String alphabet){
String wordFromDB = WordList.getWord();
word = wordFromDB.toUpperCase();
System.out.println("word is "+ word);
int[] alphabetPosition = new int[word.length()];
int index =0;
int size = -1;
int pos =0;
for(int i=pos;i< word.length(); i ++){
if((index =word.indexOf(alphabet, pos))!= -1){
System.out.println("inside if");
alphabetPosition[++size]= index;
pos=index+1;
}
else
break;
}
if(size != -1){
placeGuessedAlphabet(alphabet, alphabetPosition, size+1);
System.out.println("leter there");
}
else
System.out.println("Letter is not present");
}
|
diff --git a/eclipse/plugins/net.sf.orcc.cal.ui/src/net/sf/orcc/cal/ui/builder/ActorBuilder.java b/eclipse/plugins/net.sf.orcc.cal.ui/src/net/sf/orcc/cal/ui/builder/ActorBuilder.java
index 7b0a9b0e7..438375cb2 100644
--- a/eclipse/plugins/net.sf.orcc.cal.ui/src/net/sf/orcc/cal/ui/builder/ActorBuilder.java
+++ b/eclipse/plugins/net.sf.orcc.cal.ui/src/net/sf/orcc/cal/ui/builder/ActorBuilder.java
@@ -1,224 +1,229 @@
/*
* Copyright (c) 2010, IETR/INSA of Rennes
* 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 IETR/INSA of Rennes 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.sf.orcc.cal.ui.builder;
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
import net.sf.orcc.OrccProjectNature;
import net.sf.orcc.cache.CacheManager;
import net.sf.orcc.cal.cal.AstEntity;
import net.sf.orcc.cal.cal.CalPackage;
import net.sf.orcc.frontend.Frontend;
import net.sf.orcc.ir.Entity;
import net.sf.orcc.util.EcoreHelper;
import net.sf.orcc.util.OrccUtil;
import org.eclipse.core.resources.IFile;
import org.eclipse.core.resources.IFolder;
import org.eclipse.core.resources.IMarker;
import org.eclipse.core.resources.IProject;
import org.eclipse.core.resources.IProjectDescription;
import org.eclipse.core.resources.IResource;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.emf.ecore.EObject;
import org.eclipse.emf.ecore.EValidator;
import org.eclipse.emf.ecore.resource.Resource;
import org.eclipse.emf.ecore.resource.ResourceSet;
import org.eclipse.xtext.builder.IXtextBuilderParticipant;
import org.eclipse.xtext.naming.QualifiedName;
import org.eclipse.xtext.resource.IResourceDescription;
import org.eclipse.xtext.resource.IResourceDescription.Delta;
import org.eclipse.xtext.resource.IResourceDescriptions;
import com.google.inject.Inject;
/**
* This class defines an actor builder invoked by Xtext. The class is referenced
* by an extension point in the plugin.xml as an Xtext builder participant.
*
* @author Matthieu Wipliez
*
*/
public class ActorBuilder implements IXtextBuilderParticipant {
@Inject
private IResourceDescriptions descs;
@Override
public void build(IBuildContext context, IProgressMonitor monitor)
throws CoreException {
// only build Orcc projects
IProject project = context.getBuiltProject();
if (!project.hasNature(OrccProjectNature.NATURE_ID)) {
if (project.hasNature("net.sf.orcc.ui.OrccNature")) {
migrateNature(project);
} else {
return;
}
}
// set output folder
IFolder outputFolder = OrccUtil.getOutputFolder(project);
if (outputFolder == null) {
return;
}
Frontend.instance.setOutputFolder(outputFolder);
// if build is cleaning, remove output folder completely
BuildType type = context.getBuildType();
if (type == BuildType.CLEAN) {
// first refresh so that everything can be removed by delete
outputFolder.refreshLocal(IResource.DEPTH_INFINITE, null);
outputFolder.delete(true, null);
}
// clear cache associated with removed files
for (Delta delta : context.getDeltas()) {
if (delta.getNew() == null) {
CacheManager.instance.removeCache(delta.getUri());
}
}
// store result of build
List<Entity> entities = new ArrayList<Entity>();
Set<IResourceDescription> builtDescs = new HashSet<IResourceDescription>();
// build actors/units
ResourceSet set = context.getResourceSet();
monitor.beginTask("Building actors", context.getDeltas().size());
for (Delta delta : context.getDeltas()) {
if (delta.getNew() != null) {
IResourceDescription desc = delta.getNew();
builtDescs.add(desc);
Entity entity = build(set, desc);
if (entity != null) {
entities.add(entity);
}
}
if (monitor.isCanceled()) {
break;
}
monitor.worked(1);
}
// find out all entities that import things from the built entities
Set<IResourceDescription> dependentDescs = new HashSet<IResourceDescription>();
for (Entity entity : entities) {
String entityName = entity.getName().toLowerCase();
for (IResourceDescription desc : descs.getAllResourceDescriptions()) {
- for (QualifiedName name : desc.getImportedNames()) {
- if (name.toString().startsWith(entityName)
- && !builtDescs.contains(desc)) {
- // don't add if the description was just built
- dependentDescs.add(desc);
+ try {
+ for (QualifiedName name : desc.getImportedNames()) {
+ if (name.toString().startsWith(entityName)
+ && !builtDescs.contains(desc)) {
+ // don't add if the description was just built
+ dependentDescs.add(desc);
+ }
}
+ } catch (UnsupportedOperationException e) {
+ // getImportedNames() may be unsupported (even if the
+ // documentation does not indicate it...)
}
}
}
// build dependent descs
for (IResourceDescription desc : dependentDescs) {
// remove cache associated with dependent entity
CacheManager.instance.removeCache(desc.getURI());
build(set, desc);
}
// to free up some memory
CacheManager.instance.unloadAllCaches();
monitor.done();
}
private Entity build(ResourceSet set, IResourceDescription desc)
throws CoreException {
// load resource and compile
Resource resource = set.getResource(desc.getURI(), true);
for (EObject obj : resource.getContents()) {
if (obj.eClass().equals(CalPackage.eINSTANCE.getAstEntity())) {
AstEntity entity = (AstEntity) obj;
IFile file = EcoreHelper.getFile(resource);
if (hasErrors(file)) {
return null;
} else {
return Frontend.getEntity(entity);
}
}
}
return null;
}
/**
* Returns <code>true</code> if the given file has errors.
*
* @param file
* a file containing an entity (actor/unit)
* @return <code>true</code> if the given file has errors
* @throws CoreException
*/
private boolean hasErrors(IFile file) throws CoreException {
IMarker[] markers = file.findMarkers(EValidator.MARKER, true,
IResource.DEPTH_INFINITE);
for (IMarker marker : markers) {
if (IMarker.SEVERITY_ERROR == marker.getAttribute(IMarker.SEVERITY,
IMarker.SEVERITY_INFO)) {
// an error => no compilation
return true;
}
}
return false;
}
/**
* Migrates the old Orcc nature to the new one.
*
* @param project
* project affected
* @throws CoreException
*/
private void migrateNature(IProject project) throws CoreException {
IProjectDescription desc = project.getDescription();
String[] natures = desc.getNatureIds();
for (int i = 0; i < natures.length; i++) {
if ("net.sf.orcc.ui.OrccNature".equals(natures[i])) {
natures[i] = OrccProjectNature.NATURE_ID;
}
}
desc.setNatureIds(natures);
project.setDescription(desc, null);
}
}
| false | true | public void build(IBuildContext context, IProgressMonitor monitor)
throws CoreException {
// only build Orcc projects
IProject project = context.getBuiltProject();
if (!project.hasNature(OrccProjectNature.NATURE_ID)) {
if (project.hasNature("net.sf.orcc.ui.OrccNature")) {
migrateNature(project);
} else {
return;
}
}
// set output folder
IFolder outputFolder = OrccUtil.getOutputFolder(project);
if (outputFolder == null) {
return;
}
Frontend.instance.setOutputFolder(outputFolder);
// if build is cleaning, remove output folder completely
BuildType type = context.getBuildType();
if (type == BuildType.CLEAN) {
// first refresh so that everything can be removed by delete
outputFolder.refreshLocal(IResource.DEPTH_INFINITE, null);
outputFolder.delete(true, null);
}
// clear cache associated with removed files
for (Delta delta : context.getDeltas()) {
if (delta.getNew() == null) {
CacheManager.instance.removeCache(delta.getUri());
}
}
// store result of build
List<Entity> entities = new ArrayList<Entity>();
Set<IResourceDescription> builtDescs = new HashSet<IResourceDescription>();
// build actors/units
ResourceSet set = context.getResourceSet();
monitor.beginTask("Building actors", context.getDeltas().size());
for (Delta delta : context.getDeltas()) {
if (delta.getNew() != null) {
IResourceDescription desc = delta.getNew();
builtDescs.add(desc);
Entity entity = build(set, desc);
if (entity != null) {
entities.add(entity);
}
}
if (monitor.isCanceled()) {
break;
}
monitor.worked(1);
}
// find out all entities that import things from the built entities
Set<IResourceDescription> dependentDescs = new HashSet<IResourceDescription>();
for (Entity entity : entities) {
String entityName = entity.getName().toLowerCase();
for (IResourceDescription desc : descs.getAllResourceDescriptions()) {
for (QualifiedName name : desc.getImportedNames()) {
if (name.toString().startsWith(entityName)
&& !builtDescs.contains(desc)) {
// don't add if the description was just built
dependentDescs.add(desc);
}
}
}
}
// build dependent descs
for (IResourceDescription desc : dependentDescs) {
// remove cache associated with dependent entity
CacheManager.instance.removeCache(desc.getURI());
build(set, desc);
}
// to free up some memory
CacheManager.instance.unloadAllCaches();
monitor.done();
}
| public void build(IBuildContext context, IProgressMonitor monitor)
throws CoreException {
// only build Orcc projects
IProject project = context.getBuiltProject();
if (!project.hasNature(OrccProjectNature.NATURE_ID)) {
if (project.hasNature("net.sf.orcc.ui.OrccNature")) {
migrateNature(project);
} else {
return;
}
}
// set output folder
IFolder outputFolder = OrccUtil.getOutputFolder(project);
if (outputFolder == null) {
return;
}
Frontend.instance.setOutputFolder(outputFolder);
// if build is cleaning, remove output folder completely
BuildType type = context.getBuildType();
if (type == BuildType.CLEAN) {
// first refresh so that everything can be removed by delete
outputFolder.refreshLocal(IResource.DEPTH_INFINITE, null);
outputFolder.delete(true, null);
}
// clear cache associated with removed files
for (Delta delta : context.getDeltas()) {
if (delta.getNew() == null) {
CacheManager.instance.removeCache(delta.getUri());
}
}
// store result of build
List<Entity> entities = new ArrayList<Entity>();
Set<IResourceDescription> builtDescs = new HashSet<IResourceDescription>();
// build actors/units
ResourceSet set = context.getResourceSet();
monitor.beginTask("Building actors", context.getDeltas().size());
for (Delta delta : context.getDeltas()) {
if (delta.getNew() != null) {
IResourceDescription desc = delta.getNew();
builtDescs.add(desc);
Entity entity = build(set, desc);
if (entity != null) {
entities.add(entity);
}
}
if (monitor.isCanceled()) {
break;
}
monitor.worked(1);
}
// find out all entities that import things from the built entities
Set<IResourceDescription> dependentDescs = new HashSet<IResourceDescription>();
for (Entity entity : entities) {
String entityName = entity.getName().toLowerCase();
for (IResourceDescription desc : descs.getAllResourceDescriptions()) {
try {
for (QualifiedName name : desc.getImportedNames()) {
if (name.toString().startsWith(entityName)
&& !builtDescs.contains(desc)) {
// don't add if the description was just built
dependentDescs.add(desc);
}
}
} catch (UnsupportedOperationException e) {
// getImportedNames() may be unsupported (even if the
// documentation does not indicate it...)
}
}
}
// build dependent descs
for (IResourceDescription desc : dependentDescs) {
// remove cache associated with dependent entity
CacheManager.instance.removeCache(desc.getURI());
build(set, desc);
}
// to free up some memory
CacheManager.instance.unloadAllCaches();
monitor.done();
}
|
diff --git a/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java b/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java
index 68dd3ee12ef..a8c31294086 100644
--- a/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java
+++ b/src/main/java/org/elasticsearch/index/engine/robin/RobinEngine.java
@@ -1,1630 +1,1630 @@
/*
* Licensed to ElasticSearch and Shay Banon under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. ElasticSearch 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.elasticsearch.index.engine.robin;
import com.google.common.collect.Lists;
import org.apache.lucene.index.*;
import org.apache.lucene.index.IndexWriter.IndexReaderWarmer;
import org.apache.lucene.search.IndexSearcher;
import org.apache.lucene.search.Query;
import org.apache.lucene.search.SearcherFactory;
import org.apache.lucene.search.SearcherManager;
import org.apache.lucene.store.AlreadyClosedException;
import org.apache.lucene.store.LockObtainFailedException;
import org.apache.lucene.util.BytesRef;
import org.apache.lucene.util.IOUtils;
import org.elasticsearch.ElasticSearchException;
import org.elasticsearch.ElasticSearchIllegalStateException;
import org.elasticsearch.cluster.routing.operation.hash.djb.DjbHashFunction;
import org.elasticsearch.common.Nullable;
import org.elasticsearch.common.Preconditions;
import org.elasticsearch.common.collect.MapBuilder;
import org.elasticsearch.common.inject.Inject;
import org.elasticsearch.common.lucene.HashedBytesRef;
import org.elasticsearch.common.lucene.Lucene;
import org.elasticsearch.common.lucene.search.XFilteredQuery;
import org.elasticsearch.common.lucene.uid.Versions;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.unit.ByteSizeUnit;
import org.elasticsearch.common.unit.ByteSizeValue;
import org.elasticsearch.common.unit.TimeValue;
import org.elasticsearch.common.util.concurrent.ConcurrentCollections;
import org.elasticsearch.common.util.concurrent.EsExecutors;
import org.elasticsearch.index.VersionType;
import org.elasticsearch.index.analysis.AnalysisService;
import org.elasticsearch.index.codec.CodecService;
import org.elasticsearch.index.deletionpolicy.SnapshotDeletionPolicy;
import org.elasticsearch.index.deletionpolicy.SnapshotIndexCommit;
import org.elasticsearch.index.engine.*;
import org.elasticsearch.index.indexing.ShardIndexingService;
import org.elasticsearch.index.mapper.Uid;
import org.elasticsearch.index.merge.OnGoingMerge;
import org.elasticsearch.index.merge.policy.IndexUpgraderMergePolicy;
import org.elasticsearch.index.merge.policy.MergePolicyProvider;
import org.elasticsearch.index.merge.scheduler.MergeSchedulerProvider;
import org.elasticsearch.index.search.nested.IncludeNestedDocsQuery;
import org.elasticsearch.index.settings.IndexSettings;
import org.elasticsearch.index.settings.IndexSettingsService;
import org.elasticsearch.index.shard.AbstractIndexShardComponent;
import org.elasticsearch.index.shard.ShardId;
import org.elasticsearch.index.similarity.SimilarityService;
import org.elasticsearch.index.store.Store;
import org.elasticsearch.index.translog.Translog;
import org.elasticsearch.index.translog.TranslogStreams;
import org.elasticsearch.indices.warmer.IndicesWarmer;
import org.elasticsearch.indices.warmer.InternalIndicesWarmer;
import org.elasticsearch.threadpool.ThreadPool;
import java.io.IOException;
import java.util.*;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.atomic.AtomicBoolean;
import java.util.concurrent.atomic.AtomicInteger;
import java.util.concurrent.atomic.AtomicLong;
import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReadWriteLock;
import java.util.concurrent.locks.ReentrantLock;
import java.util.concurrent.locks.ReentrantReadWriteLock;
/**
*
*/
public class RobinEngine extends AbstractIndexShardComponent implements Engine {
private volatile ByteSizeValue indexingBufferSize;
private volatile int termIndexInterval;
private volatile int termIndexDivisor;
private volatile int indexConcurrency;
private volatile boolean compoundOnFlush = true;
private long gcDeletesInMillis;
private volatile boolean enableGcDeletes = true;
private volatile String codecName;
private final ThreadPool threadPool;
private final ShardIndexingService indexingService;
private final IndexSettingsService indexSettingsService;
@Nullable
private final InternalIndicesWarmer warmer;
private final Store store;
private final SnapshotDeletionPolicy deletionPolicy;
private final Translog translog;
private final MergePolicyProvider mergePolicyProvider;
private final MergeSchedulerProvider mergeScheduler;
private final AnalysisService analysisService;
private final SimilarityService similarityService;
private final CodecService codecService;
private final ReadWriteLock rwl = new ReentrantReadWriteLock();
private volatile IndexWriter indexWriter;
private final SearcherFactory searcherFactory = new RobinSearchFactory();
private volatile SearcherManager searcherManager;
private volatile boolean closed = false;
// flag indicating if a dirty operation has occurred since the last refresh
private volatile boolean dirty = false;
private volatile boolean possibleMergeNeeded = false;
private final AtomicBoolean optimizeMutex = new AtomicBoolean();
// we use flushNeeded here, since if there are no changes, then the commit won't write
// will not really happen, and then the commitUserData and the new translog will not be reflected
private volatile boolean flushNeeded = false;
private final AtomicInteger flushing = new AtomicInteger();
private final Lock flushLock = new ReentrantLock();
private final RecoveryCounter onGoingRecoveries = new RecoveryCounter();
// A uid (in the form of BytesRef) to the version map
// we use the hashed variant since we iterate over it and check removal and additions on existing keys
private final ConcurrentMap<HashedBytesRef, VersionValue> versionMap;
private final Object[] dirtyLocks;
private final Object refreshMutex = new Object();
private final ApplySettings applySettings = new ApplySettings();
private volatile boolean failOnMergeFailure;
private Throwable failedEngine = null;
private final Object failedEngineMutex = new Object();
private final CopyOnWriteArrayList<FailedEngineListener> failedEngineListeners = new CopyOnWriteArrayList<FailedEngineListener>();
private final AtomicLong translogIdGenerator = new AtomicLong();
private SegmentInfos lastCommittedSegmentInfos;
@Inject
public RobinEngine(ShardId shardId, @IndexSettings Settings indexSettings, ThreadPool threadPool,
IndexSettingsService indexSettingsService, ShardIndexingService indexingService, @Nullable IndicesWarmer warmer,
Store store, SnapshotDeletionPolicy deletionPolicy, Translog translog,
MergePolicyProvider mergePolicyProvider, MergeSchedulerProvider mergeScheduler,
AnalysisService analysisService, SimilarityService similarityService, CodecService codecService) throws EngineException {
super(shardId, indexSettings);
Preconditions.checkNotNull(store, "Store must be provided to the engine");
Preconditions.checkNotNull(deletionPolicy, "Snapshot deletion policy must be provided to the engine");
Preconditions.checkNotNull(translog, "Translog must be provided to the engine");
this.gcDeletesInMillis = indexSettings.getAsTime(INDEX_GC_DELETES, TimeValue.timeValueSeconds(60)).millis();
this.indexingBufferSize = componentSettings.getAsBytesSize("index_buffer_size", new ByteSizeValue(64, ByteSizeUnit.MB)); // not really important, as it is set by the IndexingMemory manager
this.termIndexInterval = indexSettings.getAsInt(INDEX_TERM_INDEX_INTERVAL, IndexWriterConfig.DEFAULT_TERM_INDEX_INTERVAL);
this.termIndexDivisor = indexSettings.getAsInt(INDEX_TERM_INDEX_DIVISOR, 1); // IndexReader#DEFAULT_TERMS_INDEX_DIVISOR
this.codecName = indexSettings.get(INDEX_CODEC, "default");
this.threadPool = threadPool;
this.indexSettingsService = indexSettingsService;
this.indexingService = indexingService;
this.warmer = (InternalIndicesWarmer) warmer;
this.store = store;
this.deletionPolicy = deletionPolicy;
this.translog = translog;
this.mergePolicyProvider = mergePolicyProvider;
this.mergeScheduler = mergeScheduler;
this.analysisService = analysisService;
this.similarityService = similarityService;
this.codecService = codecService;
this.compoundOnFlush = indexSettings.getAsBoolean(INDEX_COMPOUND_ON_FLUSH, this.compoundOnFlush);
this.indexConcurrency = indexSettings.getAsInt(INDEX_INDEX_CONCURRENCY, Math.max(IndexWriterConfig.DEFAULT_MAX_THREAD_STATES, (int) (EsExecutors.boundedNumberOfProcessors(indexSettings) * 0.65)));
this.versionMap = ConcurrentCollections.newConcurrentMapWithAggressiveConcurrency();
this.dirtyLocks = new Object[indexConcurrency * 50]; // we multiply it to have enough...
for (int i = 0; i < dirtyLocks.length; i++) {
dirtyLocks[i] = new Object();
}
this.indexSettingsService.addListener(applySettings);
this.failOnMergeFailure = indexSettings.getAsBoolean(INDEX_FAIL_ON_MERGE_FAILURE, true);
if (failOnMergeFailure) {
this.mergeScheduler.addFailureListener(new FailEngineOnMergeFailure());
}
}
@Override
public void updateIndexingBufferSize(ByteSizeValue indexingBufferSize) {
ByteSizeValue preValue = this.indexingBufferSize;
rwl.readLock().lock();
try {
this.indexingBufferSize = indexingBufferSize;
IndexWriter indexWriter = this.indexWriter;
if (indexWriter != null) {
indexWriter.getConfig().setRAMBufferSizeMB(this.indexingBufferSize.mbFrac());
}
} finally {
rwl.readLock().unlock();
}
if (preValue.bytes() != indexingBufferSize.bytes()) {
// its inactive, make sure we do a full flush in this case, since the memory
// changes only after a "data" change has happened to the writer
if (indexingBufferSize == Engine.INACTIVE_SHARD_INDEXING_BUFFER && preValue != Engine.INACTIVE_SHARD_INDEXING_BUFFER) {
logger.debug("updating index_buffer_size from [{}] to (inactive) [{}]", preValue, indexingBufferSize);
try {
flush(new Flush().type(Flush.Type.NEW_WRITER));
} catch (EngineClosedException e) {
// ignore
} catch (FlushNotAllowedEngineException e) {
// ignore
} catch (Throwable e) {
logger.warn("failed to flush after setting shard to inactive", e);
}
} else {
logger.debug("updating index_buffer_size from [{}] to [{}]", preValue, indexingBufferSize);
}
}
}
@Override
public void addFailedEngineListener(FailedEngineListener listener) {
failedEngineListeners.add(listener);
}
@Override
public void start() throws EngineException {
rwl.writeLock().lock();
try {
if (indexWriter != null) {
throw new EngineAlreadyStartedException(shardId);
}
if (closed) {
throw new EngineClosedException(shardId);
}
if (logger.isDebugEnabled()) {
logger.debug("starting engine");
}
try {
this.indexWriter = createWriter();
} catch (IOException e) {
throw new EngineCreationFailureException(shardId, "failed to create engine", e);
}
try {
// commit on a just opened writer will commit even if there are no changes done to it
// we rely on that for the commit data translog id key
if (Lucene.indexExists(store.directory())) {
Map<String, String> commitUserData = Lucene.readSegmentInfos(store.directory()).getUserData();
if (commitUserData.containsKey(Translog.TRANSLOG_ID_KEY)) {
translogIdGenerator.set(Long.parseLong(commitUserData.get(Translog.TRANSLOG_ID_KEY)));
} else {
translogIdGenerator.set(System.currentTimeMillis());
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogIdGenerator.get())).map());
indexWriter.commit();
}
} else {
translogIdGenerator.set(System.currentTimeMillis());
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogIdGenerator.get())).map());
indexWriter.commit();
}
translog.newTranslog(translogIdGenerator.get());
this.searcherManager = buildSearchManager(indexWriter);
readLastCommittedSegmentsInfo();
} catch (IOException e) {
try {
indexWriter.rollback();
} catch (IOException e1) {
// ignore
} finally {
IOUtils.closeWhileHandlingException(indexWriter);
}
throw new EngineCreationFailureException(shardId, "failed to open reader on writer", e);
}
} finally {
rwl.writeLock().unlock();
}
}
private void readLastCommittedSegmentsInfo() throws IOException {
SegmentInfos infos = new SegmentInfos();
infos.read(store.directory());
lastCommittedSegmentInfos = infos;
}
@Override
public TimeValue defaultRefreshInterval() {
return new TimeValue(1, TimeUnit.SECONDS);
}
@Override
public void enableGcDeletes(boolean enableGcDeletes) {
this.enableGcDeletes = enableGcDeletes;
}
public GetResult get(Get get) throws EngineException {
rwl.readLock().lock();
try {
if (get.realtime()) {
VersionValue versionValue = versionMap.get(versionKey(get.uid()));
if (versionValue != null) {
if (versionValue.delete()) {
return GetResult.NOT_EXISTS;
}
if (get.version() != Versions.MATCH_ANY) {
if (get.versionType().isVersionConflict(versionValue.version(), get.version())) {
Uid uid = Uid.createUid(get.uid().text());
throw new VersionConflictEngineException(shardId, uid.type(), uid.id(), versionValue.version(), get.version());
}
}
if (!get.loadSource()) {
return new GetResult(true, versionValue.version(), null);
}
byte[] data = translog.read(versionValue.translogLocation());
if (data != null) {
try {
Translog.Source source = TranslogStreams.readSource(data);
return new GetResult(true, versionValue.version(), source);
} catch (IOException e) {
// switched on us, read it from the reader
}
}
}
}
// no version, get the version from the index, we know that we refresh on flush
Searcher searcher = acquireSearcher("get");
final Versions.DocIdAndVersion docIdAndVersion;
try {
docIdAndVersion = Versions.loadDocIdAndVersion(searcher.reader(), get.uid());
} catch (Throwable e) {
searcher.release();
//TODO: A better exception goes here
throw new EngineException(shardId(), "Couldn't resolve version", e);
}
if (get.version() != Versions.MATCH_ANY && docIdAndVersion != null) {
if (get.versionType().isVersionConflict(docIdAndVersion.version, get.version())) {
searcher.release();
Uid uid = Uid.createUid(get.uid().text());
throw new VersionConflictEngineException(shardId, uid.type(), uid.id(), docIdAndVersion.version, get.version());
}
}
if (docIdAndVersion != null) {
// don't release the searcher on this path, it is the responsability of the caller to call GetResult.release
return new GetResult(searcher, docIdAndVersion);
} else {
searcher.release();
return GetResult.NOT_EXISTS;
}
} finally {
rwl.readLock().unlock();
}
}
@Override
public void create(Create create) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId, failedEngine);
}
innerCreate(create, writer);
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new CreateFailedEngineException(shardId, create, e);
} catch (OutOfMemoryError e) {
failEngine(e);
throw new CreateFailedEngineException(shardId, create, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new CreateFailedEngineException(shardId, create, e);
} finally {
rwl.readLock().unlock();
}
}
private void innerCreate(Create create, IndexWriter writer) throws IOException {
synchronized (dirtyLock(create.uid())) {
HashedBytesRef versionKey = versionKey(create.uid());
final long currentVersion;
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(create.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
// same logic as index
long updatedVersion;
long expectedVersion = create.version();
if (create.origin() == Operation.Origin.PRIMARY) {
if (create.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, create.type(), create.id(), currentVersion, expectedVersion);
}
updatedVersion = create.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, create.type(), create.id(), currentVersion, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
// if the doc does not exists or it exists but not delete
if (versionValue != null) {
if (!versionValue.delete()) {
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new DocumentAlreadyExistsException(shardId, create.type(), create.id());
}
}
} else if (currentVersion != Versions.NOT_FOUND) {
// its not deleted, its already there
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new DocumentAlreadyExistsException(shardId, create.type(), create.id());
}
}
create.version(updatedVersion);
if (create.docs().size() > 1) {
writer.addDocuments(create.docs(), create.analyzer());
} else {
writer.addDocument(create.docs().get(0), create.analyzer());
}
Translog.Location translogLocation = translog.add(new Translog.Create(create));
versionMap.put(versionKey, new VersionValue(updatedVersion, false, threadPool.estimatedTimeInMillis(), translogLocation));
indexingService.postCreateUnderLock(create);
}
}
@Override
public void index(Index index) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId, failedEngine);
}
innerIndex(index, writer);
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new IndexFailedEngineException(shardId, index, e);
} catch (OutOfMemoryError e) {
failEngine(e);
throw new IndexFailedEngineException(shardId, index, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new IndexFailedEngineException(shardId, index, e);
} finally {
rwl.readLock().unlock();
}
}
private void innerIndex(Index index, IndexWriter writer) throws IOException {
synchronized (dirtyLock(index.uid())) {
HashedBytesRef versionKey = versionKey(index.uid());
final long currentVersion;
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(index.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
long updatedVersion;
long expectedVersion = index.version();
if (index.origin() == Operation.Origin.PRIMARY) {
if (index.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, index.type(), index.id(), currentVersion, expectedVersion);
}
updatedVersion = index.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (index.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, index.type(), index.id(), currentVersion, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
index.version(updatedVersion);
if (currentVersion == Versions.NOT_FOUND) {
// document does not exists, we can optimize for create
index.created(true);
if (index.docs().size() > 1) {
writer.addDocuments(index.docs(), index.analyzer());
} else {
writer.addDocument(index.docs().get(0), index.analyzer());
}
} else {
if (versionValue != null) {
index.created(versionValue.delete()); // we have a delete which is not GC'ed...
}
if (index.docs().size() > 1) {
writer.updateDocuments(index.uid(), index.docs(), index.analyzer());
} else {
writer.updateDocument(index.uid(), index.docs().get(0), index.analyzer());
}
}
Translog.Location translogLocation = translog.add(new Translog.Index(index));
versionMap.put(versionKey, new VersionValue(updatedVersion, false, threadPool.estimatedTimeInMillis(), translogLocation));
indexingService.postIndexUnderLock(index);
}
}
@Override
public void delete(Delete delete) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId, failedEngine);
}
innerDelete(delete, writer);
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new DeleteFailedEngineException(shardId, delete, e);
} catch (OutOfMemoryError e) {
failEngine(e);
throw new DeleteFailedEngineException(shardId, delete, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new DeleteFailedEngineException(shardId, delete, e);
} finally {
rwl.readLock().unlock();
}
}
private void innerDelete(Delete delete, IndexWriter writer) throws IOException {
synchronized (dirtyLock(delete.uid())) {
final long currentVersion;
HashedBytesRef versionKey = versionKey(delete.uid());
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(delete.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
long updatedVersion;
long expectedVersion = delete.version();
if (delete.origin() == Operation.Origin.PRIMARY) {
if (delete.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, delete.type(), delete.id(), currentVersion, expectedVersion);
}
updatedVersion = delete.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (delete.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, delete.type(), delete.id(), currentVersion - 1, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
if (currentVersion == Versions.NOT_FOUND) {
// doc does not exists and no prior deletes
delete.version(updatedVersion).notFound(true);
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
} else if (versionValue != null && versionValue.delete()) {
// a "delete on delete", in this case, we still increment the version, log it, and return that version
delete.version(updatedVersion).notFound(true);
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
} else {
delete.version(updatedVersion);
writer.deleteDocuments(delete.uid());
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
}
indexingService.postDeleteUnderLock(delete);
}
}
@Override
public void delete(DeleteByQuery delete) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId);
}
Query query;
if (delete.nested() && delete.aliasFilter() != null) {
query = new IncludeNestedDocsQuery(new XFilteredQuery(delete.query(), delete.aliasFilter()), delete.parentFilter());
} else if (delete.nested()) {
query = new IncludeNestedDocsQuery(delete.query(), delete.parentFilter());
} else if (delete.aliasFilter() != null) {
query = new XFilteredQuery(delete.query(), delete.aliasFilter());
} else {
query = delete.query();
}
writer.deleteDocuments(query);
translog.add(new Translog.DeleteByQuery(delete));
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new DeleteByQueryFailedEngineException(shardId, delete, e);
} finally {
rwl.readLock().unlock();
}
//TODO: This is heavy, since we refresh, but we really have to...
refreshVersioningTable(System.currentTimeMillis());
}
@Override
public final Searcher acquireSearcher(String source) throws EngineException {
SearcherManager manager = this.searcherManager;
if (manager == null) {
throw new EngineClosedException(shardId);
}
try {
IndexSearcher searcher = manager.acquire();
return newSearcher(source, searcher, manager);
- } catch (IOException ex) {
+ } catch (Throwable ex) {
logger.error("failed to acquire searcher, source {}", ex, source);
throw new EngineException(shardId, ex.getMessage());
}
}
protected Searcher newSearcher(String source, IndexSearcher searcher, SearcherManager manager) {
return new RobinSearcher(source, searcher, manager);
}
@Override
public boolean refreshNeeded() {
return dirty;
}
@Override
public boolean possibleMergeNeeded() {
return this.possibleMergeNeeded;
}
@Override
public void refresh(Refresh refresh) throws EngineException {
if (indexWriter == null) {
throw new EngineClosedException(shardId);
}
// we obtain a read lock here, since we don't want a flush to happen while we are refreshing
// since it flushes the index as well (though, in terms of concurrency, we are allowed to do it)
rwl.readLock().lock();
try {
// this engine always acts as if waitForOperations=true
IndexWriter currentWriter = indexWriter;
if (currentWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
}
try {
// maybeRefresh will only allow one refresh to execute, and the rest will "pass through",
// but, we want to make sure not to loose ant refresh calls, if one is taking time
synchronized (refreshMutex) {
if (dirty || refresh.force()) {
dirty = false;
searcherManager.maybeRefresh();
}
}
} catch (AlreadyClosedException e) {
// an index writer got replaced on us, ignore
} catch (OutOfMemoryError e) {
failEngine(e);
throw new RefreshFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new RefreshFailedEngineException(shardId, e);
} catch (Throwable e) {
if (indexWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
} else if (currentWriter != indexWriter) {
// an index writer got replaced on us, ignore
} else {
throw new RefreshFailedEngineException(shardId, e);
}
}
} finally {
rwl.readLock().unlock();
}
}
@Override
public void flush(Flush flush) throws EngineException {
ensureOpen();
if (flush.type() == Flush.Type.NEW_WRITER || flush.type() == Flush.Type.COMMIT_TRANSLOG) {
// check outside the lock as well so we can check without blocking on the write lock
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "recovery is in progress, flush [" + flush.type() + "] is not allowed");
}
}
int currentFlushing = flushing.incrementAndGet();
if (currentFlushing > 1 && !flush.waitIfOngoing()) {
flushing.decrementAndGet();
throw new FlushNotAllowedEngineException(shardId, "already flushing...");
}
flushLock.lock();
try {
if (flush.type() == Flush.Type.NEW_WRITER) {
rwl.writeLock().lock();
try {
ensureOpen();
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "Recovery is in progress, flush is not allowed");
}
// disable refreshing, not dirty
dirty = false;
try {
// that's ok if the index writer failed and is in inconsistent state
// we will get an exception on a dirty operation, and will cause the shard
// to be allocated to a different node
indexWriter.close(false);
indexWriter = createWriter();
// commit on a just opened writer will commit even if there are no changes done to it
// we rely on that for the commit data translog id key
if (flushNeeded || flush.force()) {
flushNeeded = false;
long translogId = translogIdGenerator.incrementAndGet();
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
translog.newTranslog(translogId);
}
SearcherManager current = this.searcherManager;
this.searcherManager = buildSearchManager(indexWriter);
try {
IOUtils.close(current);
} catch (Throwable t) {
logger.warn("Failed to close current SearcherManager", t);
}
refreshVersioningTable(threadPool.estimatedTimeInMillis());
} catch (OutOfMemoryError e) {
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new FlushFailedEngineException(shardId, e);
}
} finally {
rwl.writeLock().unlock();
}
} else if (flush.type() == Flush.Type.COMMIT_TRANSLOG) {
rwl.readLock().lock();
try {
ensureOpen();
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "Recovery is in progress, flush is not allowed");
}
if (flushNeeded || flush.force()) {
flushNeeded = false;
try {
long translogId = translogIdGenerator.incrementAndGet();
translog.newTransientTranslog(translogId);
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
refreshVersioningTable(threadPool.estimatedTimeInMillis());
// we need to move transient to current only after we refresh
// so items added to current will still be around for realtime get
// when tans overrides it
translog.makeTransientCurrent();
} catch (OutOfMemoryError e) {
translog.revertTransient();
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
translog.revertTransient();
throw new FlushFailedEngineException(shardId, e);
}
}
} finally {
rwl.readLock().unlock();
}
} else if (flush.type() == Flush.Type.COMMIT) {
// note, its ok to just commit without cleaning the translog, its perfectly fine to replay a
// translog on an index that was opened on a committed point in time that is "in the future"
// of that translog
rwl.readLock().lock();
try {
ensureOpen();
// we allow to *just* commit if there is an ongoing recovery happening...
// its ok to use this, only a flush will cause a new translogId, and we are locked here from
// other flushes use flushLock
try {
long translogId = translog.currentId();
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
} catch (OutOfMemoryError e) {
translog.revertTransient();
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new FlushFailedEngineException(shardId, e);
}
} finally {
rwl.readLock().unlock();
}
} else {
throw new ElasticSearchIllegalStateException("flush type [" + flush.type() + "] not supported");
}
// reread the last committed segment infos
rwl.readLock().lock();
try {
ensureOpen();
readLastCommittedSegmentsInfo();
} catch (Throwable e) {
if (!closed) {
logger.warn("failed to read latest segment infos on flush", e);
}
} finally {
rwl.readLock().unlock();
}
} finally {
flushLock.unlock();
flushing.decrementAndGet();
}
}
private void ensureOpen() {
if (indexWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
}
}
private void refreshVersioningTable(long time) {
// we need to refresh in order to clear older version values
refresh(new Refresh("version_table").force(true));
for (Map.Entry<HashedBytesRef, VersionValue> entry : versionMap.entrySet()) {
HashedBytesRef uid = entry.getKey();
synchronized (dirtyLock(uid.bytes)) { // can we do it without this lock on each value? maybe batch to a set and get the lock once per set?
VersionValue versionValue = versionMap.get(uid);
if (versionValue == null) {
continue;
}
if (time - versionValue.time() <= 0) {
continue; // its a newer value, from after/during we refreshed, don't clear it
}
if (versionValue.delete()) {
if (enableGcDeletes && (time - versionValue.time()) > gcDeletesInMillis) {
versionMap.remove(uid);
}
} else {
versionMap.remove(uid);
}
}
}
}
@Override
public void maybeMerge() throws EngineException {
if (!possibleMergeNeeded) {
return;
}
possibleMergeNeeded = false;
rwl.readLock().lock();
try {
ensureOpen();
indexWriter.maybeMerge();
} catch (OutOfMemoryError e) {
failEngine(e);
throw new OptimizeFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new OptimizeFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new OptimizeFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void optimize(Optimize optimize) throws EngineException {
if (optimize.flush()) {
flush(new Flush().force(true).waitIfOngoing(true));
}
if (optimizeMutex.compareAndSet(false, true)) {
rwl.readLock().lock();
try {
ensureOpen();
if (optimize.onlyExpungeDeletes()) {
indexWriter.forceMergeDeletes(false);
} else if (optimize.maxNumSegments() <= 0) {
indexWriter.maybeMerge();
possibleMergeNeeded = false;
} else {
indexWriter.forceMerge(optimize.maxNumSegments(), false);
}
} catch (OutOfMemoryError e) {
failEngine(e);
throw new OptimizeFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new OptimizeFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new OptimizeFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
optimizeMutex.set(false);
}
}
// wait for the merges outside of the read lock
if (optimize.waitForMerge()) {
indexWriter.waitForMerges();
}
if (optimize.flush()) {
flush(new Flush().force(true).waitIfOngoing(true));
}
}
@Override
public <T> T snapshot(SnapshotHandler<T> snapshotHandler) throws EngineException {
SnapshotIndexCommit snapshotIndexCommit = null;
Translog.Snapshot traslogSnapshot = null;
rwl.readLock().lock();
try {
snapshotIndexCommit = deletionPolicy.snapshot();
traslogSnapshot = translog.snapshot();
} catch (Throwable e) {
if (snapshotIndexCommit != null) {
snapshotIndexCommit.release();
}
throw new SnapshotFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
try {
return snapshotHandler.snapshot(snapshotIndexCommit, traslogSnapshot);
} finally {
snapshotIndexCommit.release();
traslogSnapshot.release();
}
}
@Override
public SnapshotIndexCommit snapshotIndex() throws EngineException {
rwl.readLock().lock();
try {
flush(new Flush().type(Flush.Type.COMMIT).waitIfOngoing(true));
ensureOpen();
return deletionPolicy.snapshot();
} catch (IOException e) {
throw new SnapshotFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void recover(RecoveryHandler recoveryHandler) throws EngineException {
// take a write lock here so it won't happen while a flush is in progress
// this means that next commits will not be allowed once the lock is released
rwl.writeLock().lock();
try {
if (closed) {
throw new EngineClosedException(shardId);
}
onGoingRecoveries.increment();
} finally {
rwl.writeLock().unlock();
}
SnapshotIndexCommit phase1Snapshot;
try {
phase1Snapshot = deletionPolicy.snapshot();
} catch (Throwable e) {
onGoingRecoveries.decrement();
throw new RecoveryEngineException(shardId, 1, "Snapshot failed", e);
}
try {
recoveryHandler.phase1(phase1Snapshot);
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 1, "Execution failed", e);
}
Translog.Snapshot phase2Snapshot;
try {
phase2Snapshot = translog.snapshot();
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 2, "Snapshot failed", e);
}
try {
recoveryHandler.phase2(phase2Snapshot);
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
phase2Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 2, "Execution failed", e);
}
rwl.writeLock().lock();
Translog.Snapshot phase3Snapshot = null;
try {
phase3Snapshot = translog.snapshot(phase2Snapshot);
recoveryHandler.phase3(phase3Snapshot);
} catch (Throwable e) {
throw new RecoveryEngineException(shardId, 3, "Execution failed", e);
} finally {
onGoingRecoveries.decrement();
rwl.writeLock().unlock();
phase1Snapshot.release();
phase2Snapshot.release();
if (phase3Snapshot != null) {
phase3Snapshot.release();
}
}
}
@Override
public SegmentsStats segmentsStats() {
rwl.readLock().lock();
try {
ensureOpen();
Searcher searcher = acquireSearcher("segments_stats");
try {
SegmentsStats stats = new SegmentsStats();
stats.add(searcher.reader().leaves().size());
return stats;
} finally {
searcher.release();
}
} finally {
rwl.readLock().unlock();
}
}
@Override
public List<Segment> segments() {
rwl.readLock().lock();
try {
ensureOpen();
Map<String, Segment> segments = new HashMap<String, Segment>();
// first, go over and compute the search ones...
Searcher searcher = acquireSearcher("segments");
try {
for (AtomicReaderContext reader : searcher.reader().leaves()) {
assert reader.reader() instanceof SegmentReader;
SegmentCommitInfo info = ((SegmentReader) reader.reader()).getSegmentInfo();
assert !segments.containsKey(info.info.name);
Segment segment = new Segment(info.info.name);
segment.search = true;
segment.docCount = reader.reader().numDocs();
segment.delDocCount = reader.reader().numDeletedDocs();
segment.version = info.info.getVersion();
segment.compound = info.info.getUseCompoundFile();
try {
segment.sizeInBytes = info.sizeInBytes();
} catch (IOException e) {
logger.trace("failed to get size for [{}]", e, info.info.name);
}
segments.put(info.info.name, segment);
}
} finally {
searcher.release();
}
// now, correlate or add the committed ones...
if (lastCommittedSegmentInfos != null) {
SegmentInfos infos = lastCommittedSegmentInfos;
for (SegmentCommitInfo info : infos) {
Segment segment = segments.get(info.info.name);
if (segment == null) {
segment = new Segment(info.info.name);
segment.search = false;
segment.committed = true;
segment.docCount = info.info.getDocCount();
segment.delDocCount = info.getDelCount();
segment.version = info.info.getVersion();
segment.compound = info.info.getUseCompoundFile();
try {
segment.sizeInBytes = info.sizeInBytes();
} catch (IOException e) {
logger.trace("failed to get size for [{}]", e, info.info.name);
}
segments.put(info.info.name, segment);
} else {
segment.committed = true;
}
}
}
Segment[] segmentsArr = segments.values().toArray(new Segment[segments.values().size()]);
Arrays.sort(segmentsArr, new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
return (int) (o1.getGeneration() - o2.getGeneration());
}
});
// fill in the merges flag
Set<OnGoingMerge> onGoingMerges = mergeScheduler.onGoingMerges();
for (OnGoingMerge onGoingMerge : onGoingMerges) {
for (SegmentCommitInfo segmentInfoPerCommit : onGoingMerge.getMergedSegments()) {
for (Segment segment : segmentsArr) {
if (segment.getName().equals(segmentInfoPerCommit.info.name)) {
segment.mergeId = onGoingMerge.getId();
break;
}
}
}
}
return Arrays.asList(segmentsArr);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void close() throws ElasticSearchException {
rwl.writeLock().lock();
try {
innerClose();
} finally {
rwl.writeLock().unlock();
}
try {
// wait for recoveries to join and close all resources / IO streams
int ongoingRecoveries = onGoingRecoveries.awaitNoRecoveries(5000);
if (ongoingRecoveries > 0) {
logger.debug("Waiting for ongoing recoveries timed out on close currently ongoing disoveries: [{}]", ongoingRecoveries);
}
} catch (InterruptedException e) {
// ignore & restore interrupt
Thread.currentThread().interrupt();
}
}
class FailEngineOnMergeFailure implements MergeSchedulerProvider.FailureListener {
@Override
public void onFailedMerge(MergePolicy.MergeException e) {
failEngine(e);
}
}
private void failEngine(Throwable failure) {
synchronized (failedEngineMutex) {
if (failedEngine != null) {
return;
}
logger.warn("failed engine", failure);
failedEngine = failure;
for (FailedEngineListener listener : failedEngineListeners) {
listener.onFailedEngine(shardId, failure);
}
innerClose();
}
}
private void innerClose() {
if (closed) {
return;
}
indexSettingsService.removeListener(applySettings);
closed = true;
this.versionMap.clear();
this.failedEngineListeners.clear();
try {
try {
IOUtils.close(searcherManager);
} catch (Throwable t) {
logger.warn("Failed to close SearcherManager", t);
}
// no need to commit in this case!, we snapshot before we close the shard, so translog and all sync'ed
if (indexWriter != null) {
try {
indexWriter.rollback();
} catch (AlreadyClosedException e) {
// ignore
}
}
} catch (Throwable e) {
logger.debug("failed to rollback writer on close", e);
} finally {
indexWriter = null;
}
}
private HashedBytesRef versionKey(Term uid) {
return new HashedBytesRef(uid.bytes());
}
private Object dirtyLock(BytesRef uid) {
int hash = DjbHashFunction.DJB_HASH(uid.bytes, uid.offset, uid.length);
// abs returns Integer.MIN_VALUE, so we need to protect against it...
if (hash == Integer.MIN_VALUE) {
hash = 0;
}
return dirtyLocks[Math.abs(hash) % dirtyLocks.length];
}
private Object dirtyLock(Term uid) {
return dirtyLock(uid.bytes());
}
private long loadCurrentVersionFromIndex(Term uid) throws IOException {
Searcher searcher = acquireSearcher("load_version");
try {
return Versions.loadVersion(searcher.reader(), uid);
} finally {
searcher.release();
}
}
/**
* Returns whether a leaf reader comes from a merge (versus flush or addIndexes).
*/
private static boolean isMergedSegment(AtomicReader reader) {
// We expect leaves to be segment readers
final Map<String, String> diagnostics = ((SegmentReader) reader).getSegmentInfo().info.getDiagnostics();
final String source = diagnostics.get(IndexWriter.SOURCE);
assert Arrays.asList(IndexWriter.SOURCE_ADDINDEXES_READERS, IndexWriter.SOURCE_FLUSH, IndexWriter.SOURCE_MERGE).contains(source) : "Unknown source " + source;
return IndexWriter.SOURCE_MERGE.equals(source);
}
private IndexWriter createWriter() throws IOException {
try {
// release locks when started
if (IndexWriter.isLocked(store.directory())) {
logger.warn("shard is locked, releasing lock");
IndexWriter.unlock(store.directory());
}
boolean create = !Lucene.indexExists(store.directory());
IndexWriterConfig config = new IndexWriterConfig(Lucene.VERSION, analysisService.defaultIndexAnalyzer());
config.setOpenMode(create ? IndexWriterConfig.OpenMode.CREATE : IndexWriterConfig.OpenMode.APPEND);
config.setIndexDeletionPolicy(deletionPolicy);
config.setMergeScheduler(mergeScheduler.newMergeScheduler());
MergePolicy mergePolicy = mergePolicyProvider.newMergePolicy();
// Give us the opportunity to upgrade old segments while performing
// background merges
mergePolicy = new IndexUpgraderMergePolicy(mergePolicy);
config.setMergePolicy(mergePolicy);
config.setSimilarity(similarityService.similarity());
config.setRAMBufferSizeMB(indexingBufferSize.mbFrac());
config.setTermIndexInterval(termIndexInterval);
config.setReaderTermsIndexDivisor(termIndexDivisor);
config.setMaxThreadStates(indexConcurrency);
config.setCodec(codecService.codec(codecName));
/* We set this timeout to a highish value to work around
* the default poll interval in the Lucene lock that is
* 1000ms by default. We might need to poll multiple times
* here but with 1s poll this is only executed twice at most
* in combination with the default writelock timeout*/
config.setWriteLockTimeout(5000);
config.setUseCompoundFile(this.compoundOnFlush);
// Warm-up hook for newly-merged segments. Warming up segments here is better since it will be performed at the end
// of the merge operation and won't slow down _refresh
config.setMergedSegmentWarmer(new IndexReaderWarmer() {
@Override
public void warm(AtomicReader reader) throws IOException {
try {
assert isMergedSegment(reader);
final Engine.Searcher searcher = new SimpleSearcher("warmer", new IndexSearcher(reader));
final IndicesWarmer.WarmerContext context = new IndicesWarmer.WarmerContext(shardId, searcher);
if (warmer != null) warmer.warm(context);
} catch (Throwable t) {
// Don't fail a merge if the warm-up failed
if (!closed) {
logger.warn("Warm-up failed", t);
}
if (t instanceof Error) {
// assertion/out-of-memory error, don't ignore those
throw (Error) t;
}
}
}
});
return new IndexWriter(store.directory(), config);
} catch (LockObtainFailedException ex) {
boolean isLocked = IndexWriter.isLocked(store.directory());
logger.warn("Could not lock IndexWriter isLocked [{}]", ex, isLocked);
throw ex;
}
}
public static final String INDEX_TERM_INDEX_INTERVAL = "index.term_index_interval";
public static final String INDEX_TERM_INDEX_DIVISOR = "index.term_index_divisor";
public static final String INDEX_INDEX_CONCURRENCY = "index.index_concurrency";
public static final String INDEX_COMPOUND_ON_FLUSH = "index.compound_on_flush";
public static final String INDEX_GC_DELETES = "index.gc_deletes";
public static final String INDEX_FAIL_ON_MERGE_FAILURE = "index.fail_on_merge_failure";
class ApplySettings implements IndexSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
long gcDeletesInMillis = settings.getAsTime(INDEX_GC_DELETES, TimeValue.timeValueMillis(RobinEngine.this.gcDeletesInMillis)).millis();
if (gcDeletesInMillis != RobinEngine.this.gcDeletesInMillis) {
logger.info("updating index.gc_deletes from [{}] to [{}]", TimeValue.timeValueMillis(RobinEngine.this.gcDeletesInMillis), TimeValue.timeValueMillis(gcDeletesInMillis));
RobinEngine.this.gcDeletesInMillis = gcDeletesInMillis;
}
final boolean compoundOnFlush = settings.getAsBoolean(INDEX_COMPOUND_ON_FLUSH, RobinEngine.this.compoundOnFlush);
if (compoundOnFlush != RobinEngine.this.compoundOnFlush) {
logger.info("updating {} from [{}] to [{}]", RobinEngine.INDEX_COMPOUND_ON_FLUSH, RobinEngine.this.compoundOnFlush, compoundOnFlush);
RobinEngine.this.compoundOnFlush = compoundOnFlush;
indexWriter.getConfig().setUseCompoundFile(compoundOnFlush);
}
int termIndexInterval = settings.getAsInt(INDEX_TERM_INDEX_INTERVAL, RobinEngine.this.termIndexInterval);
int termIndexDivisor = settings.getAsInt(INDEX_TERM_INDEX_DIVISOR, RobinEngine.this.termIndexDivisor); // IndexReader#DEFAULT_TERMS_INDEX_DIVISOR
int indexConcurrency = settings.getAsInt(INDEX_INDEX_CONCURRENCY, RobinEngine.this.indexConcurrency);
boolean failOnMergeFailure = settings.getAsBoolean(INDEX_FAIL_ON_MERGE_FAILURE, RobinEngine.this.failOnMergeFailure);
String codecName = settings.get(INDEX_CODEC, RobinEngine.this.codecName);
boolean requiresFlushing = false;
if (termIndexInterval != RobinEngine.this.termIndexInterval || termIndexDivisor != RobinEngine.this.termIndexDivisor || indexConcurrency != RobinEngine.this.indexConcurrency || !codecName.equals(RobinEngine.this.codecName) || failOnMergeFailure != RobinEngine.this.failOnMergeFailure) {
rwl.readLock().lock();
try {
if (termIndexInterval != RobinEngine.this.termIndexInterval) {
logger.info("updating index.term_index_interval from [{}] to [{}]", RobinEngine.this.termIndexInterval, termIndexInterval);
RobinEngine.this.termIndexInterval = termIndexInterval;
indexWriter.getConfig().setTermIndexInterval(termIndexInterval);
}
if (termIndexDivisor != RobinEngine.this.termIndexDivisor) {
logger.info("updating index.term_index_divisor from [{}] to [{}]", RobinEngine.this.termIndexDivisor, termIndexDivisor);
RobinEngine.this.termIndexDivisor = termIndexDivisor;
indexWriter.getConfig().setReaderTermsIndexDivisor(termIndexDivisor);
// we want to apply this right now for readers, even "current" ones
requiresFlushing = true;
}
if (indexConcurrency != RobinEngine.this.indexConcurrency) {
logger.info("updating index.index_concurrency from [{}] to [{}]", RobinEngine.this.indexConcurrency, indexConcurrency);
RobinEngine.this.indexConcurrency = indexConcurrency;
// we have to flush in this case, since it only applies on a new index writer
requiresFlushing = true;
}
if (!codecName.equals(RobinEngine.this.codecName)) {
logger.info("updating index.codec from [{}] to [{}]", RobinEngine.this.codecName, codecName);
RobinEngine.this.codecName = codecName;
// we want to flush in this case, so the new codec will be reflected right away...
requiresFlushing = true;
}
if (failOnMergeFailure != RobinEngine.this.failOnMergeFailure) {
logger.info("updating {} from [{}] to [{}]", RobinEngine.INDEX_FAIL_ON_MERGE_FAILURE, RobinEngine.this.failOnMergeFailure, failOnMergeFailure);
RobinEngine.this.failOnMergeFailure = failOnMergeFailure;
}
} finally {
rwl.readLock().unlock();
}
if (requiresFlushing) {
flush(new Flush().type(Flush.Type.NEW_WRITER));
}
}
}
}
private SearcherManager buildSearchManager(IndexWriter indexWriter) throws IOException {
return new SearcherManager(indexWriter, true, searcherFactory);
}
static class RobinSearcher implements Searcher {
private final String source;
private final IndexSearcher searcher;
private final SearcherManager manager;
private RobinSearcher(String source, IndexSearcher searcher, SearcherManager manager) {
this.source = source;
this.searcher = searcher;
this.manager = manager;
}
@Override
public String source() {
return this.source;
}
@Override
public IndexReader reader() {
return searcher.getIndexReader();
}
@Override
public IndexSearcher searcher() {
return searcher;
}
@Override
public boolean release() throws ElasticSearchException {
try {
manager.release(searcher);
return true;
} catch (IOException e) {
return false;
}
}
}
static class VersionValue {
private final long version;
private final boolean delete;
private final long time;
private final Translog.Location translogLocation;
VersionValue(long version, boolean delete, long time, Translog.Location translogLocation) {
this.version = version;
this.delete = delete;
this.time = time;
this.translogLocation = translogLocation;
}
public long time() {
return this.time;
}
public long version() {
return version;
}
public boolean delete() {
return delete;
}
public Translog.Location translogLocation() {
return this.translogLocation;
}
}
class RobinSearchFactory extends SearcherFactory {
@Override
public IndexSearcher newSearcher(IndexReader reader) throws IOException {
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(similarityService.similarity());
if (warmer != null) {
// we need to pass a custom searcher that does not release anything on Engine.Search Release,
// we will release explicitly
Searcher currentSearcher = null;
IndexSearcher newSearcher = null;
boolean closeNewSearcher = false;
try {
if (searcherManager == null) {
// fresh index writer, just do on all of it
newSearcher = searcher;
} else {
currentSearcher = acquireSearcher("search_factory");
// figure out the newSearcher, with only the new readers that are relevant for us
List<IndexReader> readers = Lists.newArrayList();
for (AtomicReaderContext newReaderContext : searcher.getIndexReader().leaves()) {
if (isMergedSegment(newReaderContext.reader())) {
// merged segments are already handled by IndexWriterConfig.setMergedSegmentWarmer
continue;
}
boolean found = false;
for (AtomicReaderContext currentReaderContext : currentSearcher.reader().leaves()) {
if (currentReaderContext.reader().getCoreCacheKey().equals(newReaderContext.reader().getCoreCacheKey())) {
found = true;
break;
}
}
if (!found) {
readers.add(newReaderContext.reader());
}
}
if (!readers.isEmpty()) {
// we don't want to close the inner readers, just increase ref on them
newSearcher = new IndexSearcher(new MultiReader(readers.toArray(new IndexReader[readers.size()]), false));
closeNewSearcher = true;
}
}
if (newSearcher != null) {
IndicesWarmer.WarmerContext context = new IndicesWarmer.WarmerContext(shardId,
new SimpleSearcher("warmer", newSearcher));
warmer.warm(context);
}
} catch (Throwable e) {
if (!closed) {
logger.warn("failed to prepare/warm", e);
}
} finally {
// no need to release the fullSearcher, nothing really is done...
if (currentSearcher != null) {
currentSearcher.release();
}
if (newSearcher != null && closeNewSearcher) {
IOUtils.closeWhileHandlingException(newSearcher.getIndexReader()); // ignore
}
}
}
return searcher;
}
}
private static final class RecoveryCounter {
private volatile int ongoingRecoveries = 0;
synchronized void increment() {
ongoingRecoveries++;
}
synchronized void decrement() {
ongoingRecoveries--;
if (ongoingRecoveries == 0) {
notifyAll(); // notify waiting threads - we only wait on ongoingRecoveries == 0
}
assert ongoingRecoveries >= 0 : "ongoingRecoveries must be >= 0 but was: " + ongoingRecoveries;
}
int get() {
// volatile read - no sync needed
return ongoingRecoveries;
}
synchronized int awaitNoRecoveries(long timeout) throws InterruptedException {
if (ongoingRecoveries > 0) { // no loop here - we either time out or we are done!
wait(timeout);
}
return ongoingRecoveries;
}
}
}
| true | true | private void innerCreate(Create create, IndexWriter writer) throws IOException {
synchronized (dirtyLock(create.uid())) {
HashedBytesRef versionKey = versionKey(create.uid());
final long currentVersion;
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(create.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
// same logic as index
long updatedVersion;
long expectedVersion = create.version();
if (create.origin() == Operation.Origin.PRIMARY) {
if (create.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, create.type(), create.id(), currentVersion, expectedVersion);
}
updatedVersion = create.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, create.type(), create.id(), currentVersion, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
// if the doc does not exists or it exists but not delete
if (versionValue != null) {
if (!versionValue.delete()) {
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new DocumentAlreadyExistsException(shardId, create.type(), create.id());
}
}
} else if (currentVersion != Versions.NOT_FOUND) {
// its not deleted, its already there
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new DocumentAlreadyExistsException(shardId, create.type(), create.id());
}
}
create.version(updatedVersion);
if (create.docs().size() > 1) {
writer.addDocuments(create.docs(), create.analyzer());
} else {
writer.addDocument(create.docs().get(0), create.analyzer());
}
Translog.Location translogLocation = translog.add(new Translog.Create(create));
versionMap.put(versionKey, new VersionValue(updatedVersion, false, threadPool.estimatedTimeInMillis(), translogLocation));
indexingService.postCreateUnderLock(create);
}
}
@Override
public void index(Index index) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId, failedEngine);
}
innerIndex(index, writer);
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new IndexFailedEngineException(shardId, index, e);
} catch (OutOfMemoryError e) {
failEngine(e);
throw new IndexFailedEngineException(shardId, index, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new IndexFailedEngineException(shardId, index, e);
} finally {
rwl.readLock().unlock();
}
}
private void innerIndex(Index index, IndexWriter writer) throws IOException {
synchronized (dirtyLock(index.uid())) {
HashedBytesRef versionKey = versionKey(index.uid());
final long currentVersion;
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(index.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
long updatedVersion;
long expectedVersion = index.version();
if (index.origin() == Operation.Origin.PRIMARY) {
if (index.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, index.type(), index.id(), currentVersion, expectedVersion);
}
updatedVersion = index.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (index.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, index.type(), index.id(), currentVersion, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
index.version(updatedVersion);
if (currentVersion == Versions.NOT_FOUND) {
// document does not exists, we can optimize for create
index.created(true);
if (index.docs().size() > 1) {
writer.addDocuments(index.docs(), index.analyzer());
} else {
writer.addDocument(index.docs().get(0), index.analyzer());
}
} else {
if (versionValue != null) {
index.created(versionValue.delete()); // we have a delete which is not GC'ed...
}
if (index.docs().size() > 1) {
writer.updateDocuments(index.uid(), index.docs(), index.analyzer());
} else {
writer.updateDocument(index.uid(), index.docs().get(0), index.analyzer());
}
}
Translog.Location translogLocation = translog.add(new Translog.Index(index));
versionMap.put(versionKey, new VersionValue(updatedVersion, false, threadPool.estimatedTimeInMillis(), translogLocation));
indexingService.postIndexUnderLock(index);
}
}
@Override
public void delete(Delete delete) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId, failedEngine);
}
innerDelete(delete, writer);
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new DeleteFailedEngineException(shardId, delete, e);
} catch (OutOfMemoryError e) {
failEngine(e);
throw new DeleteFailedEngineException(shardId, delete, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new DeleteFailedEngineException(shardId, delete, e);
} finally {
rwl.readLock().unlock();
}
}
private void innerDelete(Delete delete, IndexWriter writer) throws IOException {
synchronized (dirtyLock(delete.uid())) {
final long currentVersion;
HashedBytesRef versionKey = versionKey(delete.uid());
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(delete.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
long updatedVersion;
long expectedVersion = delete.version();
if (delete.origin() == Operation.Origin.PRIMARY) {
if (delete.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, delete.type(), delete.id(), currentVersion, expectedVersion);
}
updatedVersion = delete.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (delete.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, delete.type(), delete.id(), currentVersion - 1, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
if (currentVersion == Versions.NOT_FOUND) {
// doc does not exists and no prior deletes
delete.version(updatedVersion).notFound(true);
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
} else if (versionValue != null && versionValue.delete()) {
// a "delete on delete", in this case, we still increment the version, log it, and return that version
delete.version(updatedVersion).notFound(true);
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
} else {
delete.version(updatedVersion);
writer.deleteDocuments(delete.uid());
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
}
indexingService.postDeleteUnderLock(delete);
}
}
@Override
public void delete(DeleteByQuery delete) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId);
}
Query query;
if (delete.nested() && delete.aliasFilter() != null) {
query = new IncludeNestedDocsQuery(new XFilteredQuery(delete.query(), delete.aliasFilter()), delete.parentFilter());
} else if (delete.nested()) {
query = new IncludeNestedDocsQuery(delete.query(), delete.parentFilter());
} else if (delete.aliasFilter() != null) {
query = new XFilteredQuery(delete.query(), delete.aliasFilter());
} else {
query = delete.query();
}
writer.deleteDocuments(query);
translog.add(new Translog.DeleteByQuery(delete));
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new DeleteByQueryFailedEngineException(shardId, delete, e);
} finally {
rwl.readLock().unlock();
}
//TODO: This is heavy, since we refresh, but we really have to...
refreshVersioningTable(System.currentTimeMillis());
}
@Override
public final Searcher acquireSearcher(String source) throws EngineException {
SearcherManager manager = this.searcherManager;
if (manager == null) {
throw new EngineClosedException(shardId);
}
try {
IndexSearcher searcher = manager.acquire();
return newSearcher(source, searcher, manager);
} catch (IOException ex) {
logger.error("failed to acquire searcher, source {}", ex, source);
throw new EngineException(shardId, ex.getMessage());
}
}
protected Searcher newSearcher(String source, IndexSearcher searcher, SearcherManager manager) {
return new RobinSearcher(source, searcher, manager);
}
@Override
public boolean refreshNeeded() {
return dirty;
}
@Override
public boolean possibleMergeNeeded() {
return this.possibleMergeNeeded;
}
@Override
public void refresh(Refresh refresh) throws EngineException {
if (indexWriter == null) {
throw new EngineClosedException(shardId);
}
// we obtain a read lock here, since we don't want a flush to happen while we are refreshing
// since it flushes the index as well (though, in terms of concurrency, we are allowed to do it)
rwl.readLock().lock();
try {
// this engine always acts as if waitForOperations=true
IndexWriter currentWriter = indexWriter;
if (currentWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
}
try {
// maybeRefresh will only allow one refresh to execute, and the rest will "pass through",
// but, we want to make sure not to loose ant refresh calls, if one is taking time
synchronized (refreshMutex) {
if (dirty || refresh.force()) {
dirty = false;
searcherManager.maybeRefresh();
}
}
} catch (AlreadyClosedException e) {
// an index writer got replaced on us, ignore
} catch (OutOfMemoryError e) {
failEngine(e);
throw new RefreshFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new RefreshFailedEngineException(shardId, e);
} catch (Throwable e) {
if (indexWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
} else if (currentWriter != indexWriter) {
// an index writer got replaced on us, ignore
} else {
throw new RefreshFailedEngineException(shardId, e);
}
}
} finally {
rwl.readLock().unlock();
}
}
@Override
public void flush(Flush flush) throws EngineException {
ensureOpen();
if (flush.type() == Flush.Type.NEW_WRITER || flush.type() == Flush.Type.COMMIT_TRANSLOG) {
// check outside the lock as well so we can check without blocking on the write lock
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "recovery is in progress, flush [" + flush.type() + "] is not allowed");
}
}
int currentFlushing = flushing.incrementAndGet();
if (currentFlushing > 1 && !flush.waitIfOngoing()) {
flushing.decrementAndGet();
throw new FlushNotAllowedEngineException(shardId, "already flushing...");
}
flushLock.lock();
try {
if (flush.type() == Flush.Type.NEW_WRITER) {
rwl.writeLock().lock();
try {
ensureOpen();
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "Recovery is in progress, flush is not allowed");
}
// disable refreshing, not dirty
dirty = false;
try {
// that's ok if the index writer failed and is in inconsistent state
// we will get an exception on a dirty operation, and will cause the shard
// to be allocated to a different node
indexWriter.close(false);
indexWriter = createWriter();
// commit on a just opened writer will commit even if there are no changes done to it
// we rely on that for the commit data translog id key
if (flushNeeded || flush.force()) {
flushNeeded = false;
long translogId = translogIdGenerator.incrementAndGet();
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
translog.newTranslog(translogId);
}
SearcherManager current = this.searcherManager;
this.searcherManager = buildSearchManager(indexWriter);
try {
IOUtils.close(current);
} catch (Throwable t) {
logger.warn("Failed to close current SearcherManager", t);
}
refreshVersioningTable(threadPool.estimatedTimeInMillis());
} catch (OutOfMemoryError e) {
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new FlushFailedEngineException(shardId, e);
}
} finally {
rwl.writeLock().unlock();
}
} else if (flush.type() == Flush.Type.COMMIT_TRANSLOG) {
rwl.readLock().lock();
try {
ensureOpen();
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "Recovery is in progress, flush is not allowed");
}
if (flushNeeded || flush.force()) {
flushNeeded = false;
try {
long translogId = translogIdGenerator.incrementAndGet();
translog.newTransientTranslog(translogId);
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
refreshVersioningTable(threadPool.estimatedTimeInMillis());
// we need to move transient to current only after we refresh
// so items added to current will still be around for realtime get
// when tans overrides it
translog.makeTransientCurrent();
} catch (OutOfMemoryError e) {
translog.revertTransient();
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
translog.revertTransient();
throw new FlushFailedEngineException(shardId, e);
}
}
} finally {
rwl.readLock().unlock();
}
} else if (flush.type() == Flush.Type.COMMIT) {
// note, its ok to just commit without cleaning the translog, its perfectly fine to replay a
// translog on an index that was opened on a committed point in time that is "in the future"
// of that translog
rwl.readLock().lock();
try {
ensureOpen();
// we allow to *just* commit if there is an ongoing recovery happening...
// its ok to use this, only a flush will cause a new translogId, and we are locked here from
// other flushes use flushLock
try {
long translogId = translog.currentId();
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
} catch (OutOfMemoryError e) {
translog.revertTransient();
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new FlushFailedEngineException(shardId, e);
}
} finally {
rwl.readLock().unlock();
}
} else {
throw new ElasticSearchIllegalStateException("flush type [" + flush.type() + "] not supported");
}
// reread the last committed segment infos
rwl.readLock().lock();
try {
ensureOpen();
readLastCommittedSegmentsInfo();
} catch (Throwable e) {
if (!closed) {
logger.warn("failed to read latest segment infos on flush", e);
}
} finally {
rwl.readLock().unlock();
}
} finally {
flushLock.unlock();
flushing.decrementAndGet();
}
}
private void ensureOpen() {
if (indexWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
}
}
private void refreshVersioningTable(long time) {
// we need to refresh in order to clear older version values
refresh(new Refresh("version_table").force(true));
for (Map.Entry<HashedBytesRef, VersionValue> entry : versionMap.entrySet()) {
HashedBytesRef uid = entry.getKey();
synchronized (dirtyLock(uid.bytes)) { // can we do it without this lock on each value? maybe batch to a set and get the lock once per set?
VersionValue versionValue = versionMap.get(uid);
if (versionValue == null) {
continue;
}
if (time - versionValue.time() <= 0) {
continue; // its a newer value, from after/during we refreshed, don't clear it
}
if (versionValue.delete()) {
if (enableGcDeletes && (time - versionValue.time()) > gcDeletesInMillis) {
versionMap.remove(uid);
}
} else {
versionMap.remove(uid);
}
}
}
}
@Override
public void maybeMerge() throws EngineException {
if (!possibleMergeNeeded) {
return;
}
possibleMergeNeeded = false;
rwl.readLock().lock();
try {
ensureOpen();
indexWriter.maybeMerge();
} catch (OutOfMemoryError e) {
failEngine(e);
throw new OptimizeFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new OptimizeFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new OptimizeFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void optimize(Optimize optimize) throws EngineException {
if (optimize.flush()) {
flush(new Flush().force(true).waitIfOngoing(true));
}
if (optimizeMutex.compareAndSet(false, true)) {
rwl.readLock().lock();
try {
ensureOpen();
if (optimize.onlyExpungeDeletes()) {
indexWriter.forceMergeDeletes(false);
} else if (optimize.maxNumSegments() <= 0) {
indexWriter.maybeMerge();
possibleMergeNeeded = false;
} else {
indexWriter.forceMerge(optimize.maxNumSegments(), false);
}
} catch (OutOfMemoryError e) {
failEngine(e);
throw new OptimizeFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new OptimizeFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new OptimizeFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
optimizeMutex.set(false);
}
}
// wait for the merges outside of the read lock
if (optimize.waitForMerge()) {
indexWriter.waitForMerges();
}
if (optimize.flush()) {
flush(new Flush().force(true).waitIfOngoing(true));
}
}
@Override
public <T> T snapshot(SnapshotHandler<T> snapshotHandler) throws EngineException {
SnapshotIndexCommit snapshotIndexCommit = null;
Translog.Snapshot traslogSnapshot = null;
rwl.readLock().lock();
try {
snapshotIndexCommit = deletionPolicy.snapshot();
traslogSnapshot = translog.snapshot();
} catch (Throwable e) {
if (snapshotIndexCommit != null) {
snapshotIndexCommit.release();
}
throw new SnapshotFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
try {
return snapshotHandler.snapshot(snapshotIndexCommit, traslogSnapshot);
} finally {
snapshotIndexCommit.release();
traslogSnapshot.release();
}
}
@Override
public SnapshotIndexCommit snapshotIndex() throws EngineException {
rwl.readLock().lock();
try {
flush(new Flush().type(Flush.Type.COMMIT).waitIfOngoing(true));
ensureOpen();
return deletionPolicy.snapshot();
} catch (IOException e) {
throw new SnapshotFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void recover(RecoveryHandler recoveryHandler) throws EngineException {
// take a write lock here so it won't happen while a flush is in progress
// this means that next commits will not be allowed once the lock is released
rwl.writeLock().lock();
try {
if (closed) {
throw new EngineClosedException(shardId);
}
onGoingRecoveries.increment();
} finally {
rwl.writeLock().unlock();
}
SnapshotIndexCommit phase1Snapshot;
try {
phase1Snapshot = deletionPolicy.snapshot();
} catch (Throwable e) {
onGoingRecoveries.decrement();
throw new RecoveryEngineException(shardId, 1, "Snapshot failed", e);
}
try {
recoveryHandler.phase1(phase1Snapshot);
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 1, "Execution failed", e);
}
Translog.Snapshot phase2Snapshot;
try {
phase2Snapshot = translog.snapshot();
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 2, "Snapshot failed", e);
}
try {
recoveryHandler.phase2(phase2Snapshot);
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
phase2Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 2, "Execution failed", e);
}
rwl.writeLock().lock();
Translog.Snapshot phase3Snapshot = null;
try {
phase3Snapshot = translog.snapshot(phase2Snapshot);
recoveryHandler.phase3(phase3Snapshot);
} catch (Throwable e) {
throw new RecoveryEngineException(shardId, 3, "Execution failed", e);
} finally {
onGoingRecoveries.decrement();
rwl.writeLock().unlock();
phase1Snapshot.release();
phase2Snapshot.release();
if (phase3Snapshot != null) {
phase3Snapshot.release();
}
}
}
@Override
public SegmentsStats segmentsStats() {
rwl.readLock().lock();
try {
ensureOpen();
Searcher searcher = acquireSearcher("segments_stats");
try {
SegmentsStats stats = new SegmentsStats();
stats.add(searcher.reader().leaves().size());
return stats;
} finally {
searcher.release();
}
} finally {
rwl.readLock().unlock();
}
}
@Override
public List<Segment> segments() {
rwl.readLock().lock();
try {
ensureOpen();
Map<String, Segment> segments = new HashMap<String, Segment>();
// first, go over and compute the search ones...
Searcher searcher = acquireSearcher("segments");
try {
for (AtomicReaderContext reader : searcher.reader().leaves()) {
assert reader.reader() instanceof SegmentReader;
SegmentCommitInfo info = ((SegmentReader) reader.reader()).getSegmentInfo();
assert !segments.containsKey(info.info.name);
Segment segment = new Segment(info.info.name);
segment.search = true;
segment.docCount = reader.reader().numDocs();
segment.delDocCount = reader.reader().numDeletedDocs();
segment.version = info.info.getVersion();
segment.compound = info.info.getUseCompoundFile();
try {
segment.sizeInBytes = info.sizeInBytes();
} catch (IOException e) {
logger.trace("failed to get size for [{}]", e, info.info.name);
}
segments.put(info.info.name, segment);
}
} finally {
searcher.release();
}
// now, correlate or add the committed ones...
if (lastCommittedSegmentInfos != null) {
SegmentInfos infos = lastCommittedSegmentInfos;
for (SegmentCommitInfo info : infos) {
Segment segment = segments.get(info.info.name);
if (segment == null) {
segment = new Segment(info.info.name);
segment.search = false;
segment.committed = true;
segment.docCount = info.info.getDocCount();
segment.delDocCount = info.getDelCount();
segment.version = info.info.getVersion();
segment.compound = info.info.getUseCompoundFile();
try {
segment.sizeInBytes = info.sizeInBytes();
} catch (IOException e) {
logger.trace("failed to get size for [{}]", e, info.info.name);
}
segments.put(info.info.name, segment);
} else {
segment.committed = true;
}
}
}
Segment[] segmentsArr = segments.values().toArray(new Segment[segments.values().size()]);
Arrays.sort(segmentsArr, new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
return (int) (o1.getGeneration() - o2.getGeneration());
}
});
// fill in the merges flag
Set<OnGoingMerge> onGoingMerges = mergeScheduler.onGoingMerges();
for (OnGoingMerge onGoingMerge : onGoingMerges) {
for (SegmentCommitInfo segmentInfoPerCommit : onGoingMerge.getMergedSegments()) {
for (Segment segment : segmentsArr) {
if (segment.getName().equals(segmentInfoPerCommit.info.name)) {
segment.mergeId = onGoingMerge.getId();
break;
}
}
}
}
return Arrays.asList(segmentsArr);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void close() throws ElasticSearchException {
rwl.writeLock().lock();
try {
innerClose();
} finally {
rwl.writeLock().unlock();
}
try {
// wait for recoveries to join and close all resources / IO streams
int ongoingRecoveries = onGoingRecoveries.awaitNoRecoveries(5000);
if (ongoingRecoveries > 0) {
logger.debug("Waiting for ongoing recoveries timed out on close currently ongoing disoveries: [{}]", ongoingRecoveries);
}
} catch (InterruptedException e) {
// ignore & restore interrupt
Thread.currentThread().interrupt();
}
}
class FailEngineOnMergeFailure implements MergeSchedulerProvider.FailureListener {
@Override
public void onFailedMerge(MergePolicy.MergeException e) {
failEngine(e);
}
}
private void failEngine(Throwable failure) {
synchronized (failedEngineMutex) {
if (failedEngine != null) {
return;
}
logger.warn("failed engine", failure);
failedEngine = failure;
for (FailedEngineListener listener : failedEngineListeners) {
listener.onFailedEngine(shardId, failure);
}
innerClose();
}
}
private void innerClose() {
if (closed) {
return;
}
indexSettingsService.removeListener(applySettings);
closed = true;
this.versionMap.clear();
this.failedEngineListeners.clear();
try {
try {
IOUtils.close(searcherManager);
} catch (Throwable t) {
logger.warn("Failed to close SearcherManager", t);
}
// no need to commit in this case!, we snapshot before we close the shard, so translog and all sync'ed
if (indexWriter != null) {
try {
indexWriter.rollback();
} catch (AlreadyClosedException e) {
// ignore
}
}
} catch (Throwable e) {
logger.debug("failed to rollback writer on close", e);
} finally {
indexWriter = null;
}
}
private HashedBytesRef versionKey(Term uid) {
return new HashedBytesRef(uid.bytes());
}
private Object dirtyLock(BytesRef uid) {
int hash = DjbHashFunction.DJB_HASH(uid.bytes, uid.offset, uid.length);
// abs returns Integer.MIN_VALUE, so we need to protect against it...
if (hash == Integer.MIN_VALUE) {
hash = 0;
}
return dirtyLocks[Math.abs(hash) % dirtyLocks.length];
}
private Object dirtyLock(Term uid) {
return dirtyLock(uid.bytes());
}
private long loadCurrentVersionFromIndex(Term uid) throws IOException {
Searcher searcher = acquireSearcher("load_version");
try {
return Versions.loadVersion(searcher.reader(), uid);
} finally {
searcher.release();
}
}
/**
* Returns whether a leaf reader comes from a merge (versus flush or addIndexes).
*/
private static boolean isMergedSegment(AtomicReader reader) {
// We expect leaves to be segment readers
final Map<String, String> diagnostics = ((SegmentReader) reader).getSegmentInfo().info.getDiagnostics();
final String source = diagnostics.get(IndexWriter.SOURCE);
assert Arrays.asList(IndexWriter.SOURCE_ADDINDEXES_READERS, IndexWriter.SOURCE_FLUSH, IndexWriter.SOURCE_MERGE).contains(source) : "Unknown source " + source;
return IndexWriter.SOURCE_MERGE.equals(source);
}
private IndexWriter createWriter() throws IOException {
try {
// release locks when started
if (IndexWriter.isLocked(store.directory())) {
logger.warn("shard is locked, releasing lock");
IndexWriter.unlock(store.directory());
}
boolean create = !Lucene.indexExists(store.directory());
IndexWriterConfig config = new IndexWriterConfig(Lucene.VERSION, analysisService.defaultIndexAnalyzer());
config.setOpenMode(create ? IndexWriterConfig.OpenMode.CREATE : IndexWriterConfig.OpenMode.APPEND);
config.setIndexDeletionPolicy(deletionPolicy);
config.setMergeScheduler(mergeScheduler.newMergeScheduler());
MergePolicy mergePolicy = mergePolicyProvider.newMergePolicy();
// Give us the opportunity to upgrade old segments while performing
// background merges
mergePolicy = new IndexUpgraderMergePolicy(mergePolicy);
config.setMergePolicy(mergePolicy);
config.setSimilarity(similarityService.similarity());
config.setRAMBufferSizeMB(indexingBufferSize.mbFrac());
config.setTermIndexInterval(termIndexInterval);
config.setReaderTermsIndexDivisor(termIndexDivisor);
config.setMaxThreadStates(indexConcurrency);
config.setCodec(codecService.codec(codecName));
/* We set this timeout to a highish value to work around
* the default poll interval in the Lucene lock that is
* 1000ms by default. We might need to poll multiple times
* here but with 1s poll this is only executed twice at most
* in combination with the default writelock timeout*/
config.setWriteLockTimeout(5000);
config.setUseCompoundFile(this.compoundOnFlush);
// Warm-up hook for newly-merged segments. Warming up segments here is better since it will be performed at the end
// of the merge operation and won't slow down _refresh
config.setMergedSegmentWarmer(new IndexReaderWarmer() {
@Override
public void warm(AtomicReader reader) throws IOException {
try {
assert isMergedSegment(reader);
final Engine.Searcher searcher = new SimpleSearcher("warmer", new IndexSearcher(reader));
final IndicesWarmer.WarmerContext context = new IndicesWarmer.WarmerContext(shardId, searcher);
if (warmer != null) warmer.warm(context);
} catch (Throwable t) {
// Don't fail a merge if the warm-up failed
if (!closed) {
logger.warn("Warm-up failed", t);
}
if (t instanceof Error) {
// assertion/out-of-memory error, don't ignore those
throw (Error) t;
}
}
}
});
return new IndexWriter(store.directory(), config);
} catch (LockObtainFailedException ex) {
boolean isLocked = IndexWriter.isLocked(store.directory());
logger.warn("Could not lock IndexWriter isLocked [{}]", ex, isLocked);
throw ex;
}
}
public static final String INDEX_TERM_INDEX_INTERVAL = "index.term_index_interval";
public static final String INDEX_TERM_INDEX_DIVISOR = "index.term_index_divisor";
public static final String INDEX_INDEX_CONCURRENCY = "index.index_concurrency";
public static final String INDEX_COMPOUND_ON_FLUSH = "index.compound_on_flush";
public static final String INDEX_GC_DELETES = "index.gc_deletes";
public static final String INDEX_FAIL_ON_MERGE_FAILURE = "index.fail_on_merge_failure";
class ApplySettings implements IndexSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
long gcDeletesInMillis = settings.getAsTime(INDEX_GC_DELETES, TimeValue.timeValueMillis(RobinEngine.this.gcDeletesInMillis)).millis();
if (gcDeletesInMillis != RobinEngine.this.gcDeletesInMillis) {
logger.info("updating index.gc_deletes from [{}] to [{}]", TimeValue.timeValueMillis(RobinEngine.this.gcDeletesInMillis), TimeValue.timeValueMillis(gcDeletesInMillis));
RobinEngine.this.gcDeletesInMillis = gcDeletesInMillis;
}
final boolean compoundOnFlush = settings.getAsBoolean(INDEX_COMPOUND_ON_FLUSH, RobinEngine.this.compoundOnFlush);
if (compoundOnFlush != RobinEngine.this.compoundOnFlush) {
logger.info("updating {} from [{}] to [{}]", RobinEngine.INDEX_COMPOUND_ON_FLUSH, RobinEngine.this.compoundOnFlush, compoundOnFlush);
RobinEngine.this.compoundOnFlush = compoundOnFlush;
indexWriter.getConfig().setUseCompoundFile(compoundOnFlush);
}
int termIndexInterval = settings.getAsInt(INDEX_TERM_INDEX_INTERVAL, RobinEngine.this.termIndexInterval);
int termIndexDivisor = settings.getAsInt(INDEX_TERM_INDEX_DIVISOR, RobinEngine.this.termIndexDivisor); // IndexReader#DEFAULT_TERMS_INDEX_DIVISOR
int indexConcurrency = settings.getAsInt(INDEX_INDEX_CONCURRENCY, RobinEngine.this.indexConcurrency);
boolean failOnMergeFailure = settings.getAsBoolean(INDEX_FAIL_ON_MERGE_FAILURE, RobinEngine.this.failOnMergeFailure);
String codecName = settings.get(INDEX_CODEC, RobinEngine.this.codecName);
boolean requiresFlushing = false;
if (termIndexInterval != RobinEngine.this.termIndexInterval || termIndexDivisor != RobinEngine.this.termIndexDivisor || indexConcurrency != RobinEngine.this.indexConcurrency || !codecName.equals(RobinEngine.this.codecName) || failOnMergeFailure != RobinEngine.this.failOnMergeFailure) {
rwl.readLock().lock();
try {
if (termIndexInterval != RobinEngine.this.termIndexInterval) {
logger.info("updating index.term_index_interval from [{}] to [{}]", RobinEngine.this.termIndexInterval, termIndexInterval);
RobinEngine.this.termIndexInterval = termIndexInterval;
indexWriter.getConfig().setTermIndexInterval(termIndexInterval);
}
if (termIndexDivisor != RobinEngine.this.termIndexDivisor) {
logger.info("updating index.term_index_divisor from [{}] to [{}]", RobinEngine.this.termIndexDivisor, termIndexDivisor);
RobinEngine.this.termIndexDivisor = termIndexDivisor;
indexWriter.getConfig().setReaderTermsIndexDivisor(termIndexDivisor);
// we want to apply this right now for readers, even "current" ones
requiresFlushing = true;
}
if (indexConcurrency != RobinEngine.this.indexConcurrency) {
logger.info("updating index.index_concurrency from [{}] to [{}]", RobinEngine.this.indexConcurrency, indexConcurrency);
RobinEngine.this.indexConcurrency = indexConcurrency;
// we have to flush in this case, since it only applies on a new index writer
requiresFlushing = true;
}
if (!codecName.equals(RobinEngine.this.codecName)) {
logger.info("updating index.codec from [{}] to [{}]", RobinEngine.this.codecName, codecName);
RobinEngine.this.codecName = codecName;
// we want to flush in this case, so the new codec will be reflected right away...
requiresFlushing = true;
}
if (failOnMergeFailure != RobinEngine.this.failOnMergeFailure) {
logger.info("updating {} from [{}] to [{}]", RobinEngine.INDEX_FAIL_ON_MERGE_FAILURE, RobinEngine.this.failOnMergeFailure, failOnMergeFailure);
RobinEngine.this.failOnMergeFailure = failOnMergeFailure;
}
} finally {
rwl.readLock().unlock();
}
if (requiresFlushing) {
flush(new Flush().type(Flush.Type.NEW_WRITER));
}
}
}
}
private SearcherManager buildSearchManager(IndexWriter indexWriter) throws IOException {
return new SearcherManager(indexWriter, true, searcherFactory);
}
static class RobinSearcher implements Searcher {
private final String source;
private final IndexSearcher searcher;
private final SearcherManager manager;
private RobinSearcher(String source, IndexSearcher searcher, SearcherManager manager) {
this.source = source;
this.searcher = searcher;
this.manager = manager;
}
@Override
public String source() {
return this.source;
}
@Override
public IndexReader reader() {
return searcher.getIndexReader();
}
@Override
public IndexSearcher searcher() {
return searcher;
}
@Override
public boolean release() throws ElasticSearchException {
try {
manager.release(searcher);
return true;
} catch (IOException e) {
return false;
}
}
}
static class VersionValue {
private final long version;
private final boolean delete;
private final long time;
private final Translog.Location translogLocation;
VersionValue(long version, boolean delete, long time, Translog.Location translogLocation) {
this.version = version;
this.delete = delete;
this.time = time;
this.translogLocation = translogLocation;
}
public long time() {
return this.time;
}
public long version() {
return version;
}
public boolean delete() {
return delete;
}
public Translog.Location translogLocation() {
return this.translogLocation;
}
}
class RobinSearchFactory extends SearcherFactory {
@Override
public IndexSearcher newSearcher(IndexReader reader) throws IOException {
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(similarityService.similarity());
if (warmer != null) {
// we need to pass a custom searcher that does not release anything on Engine.Search Release,
// we will release explicitly
Searcher currentSearcher = null;
IndexSearcher newSearcher = null;
boolean closeNewSearcher = false;
try {
if (searcherManager == null) {
// fresh index writer, just do on all of it
newSearcher = searcher;
} else {
currentSearcher = acquireSearcher("search_factory");
// figure out the newSearcher, with only the new readers that are relevant for us
List<IndexReader> readers = Lists.newArrayList();
for (AtomicReaderContext newReaderContext : searcher.getIndexReader().leaves()) {
if (isMergedSegment(newReaderContext.reader())) {
// merged segments are already handled by IndexWriterConfig.setMergedSegmentWarmer
continue;
}
boolean found = false;
for (AtomicReaderContext currentReaderContext : currentSearcher.reader().leaves()) {
if (currentReaderContext.reader().getCoreCacheKey().equals(newReaderContext.reader().getCoreCacheKey())) {
found = true;
break;
}
}
if (!found) {
readers.add(newReaderContext.reader());
}
}
if (!readers.isEmpty()) {
// we don't want to close the inner readers, just increase ref on them
newSearcher = new IndexSearcher(new MultiReader(readers.toArray(new IndexReader[readers.size()]), false));
closeNewSearcher = true;
}
}
if (newSearcher != null) {
IndicesWarmer.WarmerContext context = new IndicesWarmer.WarmerContext(shardId,
new SimpleSearcher("warmer", newSearcher));
warmer.warm(context);
}
} catch (Throwable e) {
if (!closed) {
logger.warn("failed to prepare/warm", e);
}
} finally {
// no need to release the fullSearcher, nothing really is done...
if (currentSearcher != null) {
currentSearcher.release();
}
if (newSearcher != null && closeNewSearcher) {
IOUtils.closeWhileHandlingException(newSearcher.getIndexReader()); // ignore
}
}
}
return searcher;
}
}
private static final class RecoveryCounter {
private volatile int ongoingRecoveries = 0;
synchronized void increment() {
ongoingRecoveries++;
}
synchronized void decrement() {
ongoingRecoveries--;
if (ongoingRecoveries == 0) {
notifyAll(); // notify waiting threads - we only wait on ongoingRecoveries == 0
}
assert ongoingRecoveries >= 0 : "ongoingRecoveries must be >= 0 but was: " + ongoingRecoveries;
}
int get() {
// volatile read - no sync needed
return ongoingRecoveries;
}
synchronized int awaitNoRecoveries(long timeout) throws InterruptedException {
if (ongoingRecoveries > 0) { // no loop here - we either time out or we are done!
wait(timeout);
}
return ongoingRecoveries;
}
}
}
| private void innerCreate(Create create, IndexWriter writer) throws IOException {
synchronized (dirtyLock(create.uid())) {
HashedBytesRef versionKey = versionKey(create.uid());
final long currentVersion;
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(create.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
// same logic as index
long updatedVersion;
long expectedVersion = create.version();
if (create.origin() == Operation.Origin.PRIMARY) {
if (create.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, create.type(), create.id(), currentVersion, expectedVersion);
}
updatedVersion = create.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, create.type(), create.id(), currentVersion, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
// if the doc does not exists or it exists but not delete
if (versionValue != null) {
if (!versionValue.delete()) {
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new DocumentAlreadyExistsException(shardId, create.type(), create.id());
}
}
} else if (currentVersion != Versions.NOT_FOUND) {
// its not deleted, its already there
if (create.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new DocumentAlreadyExistsException(shardId, create.type(), create.id());
}
}
create.version(updatedVersion);
if (create.docs().size() > 1) {
writer.addDocuments(create.docs(), create.analyzer());
} else {
writer.addDocument(create.docs().get(0), create.analyzer());
}
Translog.Location translogLocation = translog.add(new Translog.Create(create));
versionMap.put(versionKey, new VersionValue(updatedVersion, false, threadPool.estimatedTimeInMillis(), translogLocation));
indexingService.postCreateUnderLock(create);
}
}
@Override
public void index(Index index) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId, failedEngine);
}
innerIndex(index, writer);
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new IndexFailedEngineException(shardId, index, e);
} catch (OutOfMemoryError e) {
failEngine(e);
throw new IndexFailedEngineException(shardId, index, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new IndexFailedEngineException(shardId, index, e);
} finally {
rwl.readLock().unlock();
}
}
private void innerIndex(Index index, IndexWriter writer) throws IOException {
synchronized (dirtyLock(index.uid())) {
HashedBytesRef versionKey = versionKey(index.uid());
final long currentVersion;
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(index.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
long updatedVersion;
long expectedVersion = index.version();
if (index.origin() == Operation.Origin.PRIMARY) {
if (index.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, index.type(), index.id(), currentVersion, expectedVersion);
}
updatedVersion = index.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (index.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, index.type(), index.id(), currentVersion, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
index.version(updatedVersion);
if (currentVersion == Versions.NOT_FOUND) {
// document does not exists, we can optimize for create
index.created(true);
if (index.docs().size() > 1) {
writer.addDocuments(index.docs(), index.analyzer());
} else {
writer.addDocument(index.docs().get(0), index.analyzer());
}
} else {
if (versionValue != null) {
index.created(versionValue.delete()); // we have a delete which is not GC'ed...
}
if (index.docs().size() > 1) {
writer.updateDocuments(index.uid(), index.docs(), index.analyzer());
} else {
writer.updateDocument(index.uid(), index.docs().get(0), index.analyzer());
}
}
Translog.Location translogLocation = translog.add(new Translog.Index(index));
versionMap.put(versionKey, new VersionValue(updatedVersion, false, threadPool.estimatedTimeInMillis(), translogLocation));
indexingService.postIndexUnderLock(index);
}
}
@Override
public void delete(Delete delete) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId, failedEngine);
}
innerDelete(delete, writer);
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new DeleteFailedEngineException(shardId, delete, e);
} catch (OutOfMemoryError e) {
failEngine(e);
throw new DeleteFailedEngineException(shardId, delete, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new DeleteFailedEngineException(shardId, delete, e);
} finally {
rwl.readLock().unlock();
}
}
private void innerDelete(Delete delete, IndexWriter writer) throws IOException {
synchronized (dirtyLock(delete.uid())) {
final long currentVersion;
HashedBytesRef versionKey = versionKey(delete.uid());
VersionValue versionValue = versionMap.get(versionKey);
if (versionValue == null) {
currentVersion = loadCurrentVersionFromIndex(delete.uid());
} else {
if (enableGcDeletes && versionValue.delete() && (threadPool.estimatedTimeInMillis() - versionValue.time()) > gcDeletesInMillis) {
currentVersion = Versions.NOT_FOUND; // deleted, and GC
} else {
currentVersion = versionValue.version();
}
}
long updatedVersion;
long expectedVersion = delete.version();
if (delete.origin() == Operation.Origin.PRIMARY) {
if (delete.versionType().isVersionConflict(currentVersion, expectedVersion)) {
throw new VersionConflictEngineException(shardId, delete.type(), delete.id(), currentVersion, expectedVersion);
}
updatedVersion = delete.versionType().updateVersion(currentVersion, expectedVersion);
} else { // if (index.origin() == Operation.Origin.REPLICA || index.origin() == Operation.Origin.RECOVERY) {
// replicas treat the version as "external" as it comes from the primary ->
// only exploding if the version they got is lower or equal to what they know.
if (VersionType.EXTERNAL.isVersionConflict(currentVersion, expectedVersion)) {
if (delete.origin() == Operation.Origin.RECOVERY) {
return;
} else {
throw new VersionConflictEngineException(shardId, delete.type(), delete.id(), currentVersion - 1, expectedVersion);
}
}
updatedVersion = VersionType.EXTERNAL.updateVersion(currentVersion, expectedVersion);
}
if (currentVersion == Versions.NOT_FOUND) {
// doc does not exists and no prior deletes
delete.version(updatedVersion).notFound(true);
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
} else if (versionValue != null && versionValue.delete()) {
// a "delete on delete", in this case, we still increment the version, log it, and return that version
delete.version(updatedVersion).notFound(true);
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
} else {
delete.version(updatedVersion);
writer.deleteDocuments(delete.uid());
Translog.Location translogLocation = translog.add(new Translog.Delete(delete));
versionMap.put(versionKey, new VersionValue(updatedVersion, true, threadPool.estimatedTimeInMillis(), translogLocation));
}
indexingService.postDeleteUnderLock(delete);
}
}
@Override
public void delete(DeleteByQuery delete) throws EngineException {
rwl.readLock().lock();
try {
IndexWriter writer = this.indexWriter;
if (writer == null) {
throw new EngineClosedException(shardId);
}
Query query;
if (delete.nested() && delete.aliasFilter() != null) {
query = new IncludeNestedDocsQuery(new XFilteredQuery(delete.query(), delete.aliasFilter()), delete.parentFilter());
} else if (delete.nested()) {
query = new IncludeNestedDocsQuery(delete.query(), delete.parentFilter());
} else if (delete.aliasFilter() != null) {
query = new XFilteredQuery(delete.query(), delete.aliasFilter());
} else {
query = delete.query();
}
writer.deleteDocuments(query);
translog.add(new Translog.DeleteByQuery(delete));
dirty = true;
possibleMergeNeeded = true;
flushNeeded = true;
} catch (IOException e) {
throw new DeleteByQueryFailedEngineException(shardId, delete, e);
} finally {
rwl.readLock().unlock();
}
//TODO: This is heavy, since we refresh, but we really have to...
refreshVersioningTable(System.currentTimeMillis());
}
@Override
public final Searcher acquireSearcher(String source) throws EngineException {
SearcherManager manager = this.searcherManager;
if (manager == null) {
throw new EngineClosedException(shardId);
}
try {
IndexSearcher searcher = manager.acquire();
return newSearcher(source, searcher, manager);
} catch (Throwable ex) {
logger.error("failed to acquire searcher, source {}", ex, source);
throw new EngineException(shardId, ex.getMessage());
}
}
protected Searcher newSearcher(String source, IndexSearcher searcher, SearcherManager manager) {
return new RobinSearcher(source, searcher, manager);
}
@Override
public boolean refreshNeeded() {
return dirty;
}
@Override
public boolean possibleMergeNeeded() {
return this.possibleMergeNeeded;
}
@Override
public void refresh(Refresh refresh) throws EngineException {
if (indexWriter == null) {
throw new EngineClosedException(shardId);
}
// we obtain a read lock here, since we don't want a flush to happen while we are refreshing
// since it flushes the index as well (though, in terms of concurrency, we are allowed to do it)
rwl.readLock().lock();
try {
// this engine always acts as if waitForOperations=true
IndexWriter currentWriter = indexWriter;
if (currentWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
}
try {
// maybeRefresh will only allow one refresh to execute, and the rest will "pass through",
// but, we want to make sure not to loose ant refresh calls, if one is taking time
synchronized (refreshMutex) {
if (dirty || refresh.force()) {
dirty = false;
searcherManager.maybeRefresh();
}
}
} catch (AlreadyClosedException e) {
// an index writer got replaced on us, ignore
} catch (OutOfMemoryError e) {
failEngine(e);
throw new RefreshFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new RefreshFailedEngineException(shardId, e);
} catch (Throwable e) {
if (indexWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
} else if (currentWriter != indexWriter) {
// an index writer got replaced on us, ignore
} else {
throw new RefreshFailedEngineException(shardId, e);
}
}
} finally {
rwl.readLock().unlock();
}
}
@Override
public void flush(Flush flush) throws EngineException {
ensureOpen();
if (flush.type() == Flush.Type.NEW_WRITER || flush.type() == Flush.Type.COMMIT_TRANSLOG) {
// check outside the lock as well so we can check without blocking on the write lock
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "recovery is in progress, flush [" + flush.type() + "] is not allowed");
}
}
int currentFlushing = flushing.incrementAndGet();
if (currentFlushing > 1 && !flush.waitIfOngoing()) {
flushing.decrementAndGet();
throw new FlushNotAllowedEngineException(shardId, "already flushing...");
}
flushLock.lock();
try {
if (flush.type() == Flush.Type.NEW_WRITER) {
rwl.writeLock().lock();
try {
ensureOpen();
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "Recovery is in progress, flush is not allowed");
}
// disable refreshing, not dirty
dirty = false;
try {
// that's ok if the index writer failed and is in inconsistent state
// we will get an exception on a dirty operation, and will cause the shard
// to be allocated to a different node
indexWriter.close(false);
indexWriter = createWriter();
// commit on a just opened writer will commit even if there are no changes done to it
// we rely on that for the commit data translog id key
if (flushNeeded || flush.force()) {
flushNeeded = false;
long translogId = translogIdGenerator.incrementAndGet();
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
translog.newTranslog(translogId);
}
SearcherManager current = this.searcherManager;
this.searcherManager = buildSearchManager(indexWriter);
try {
IOUtils.close(current);
} catch (Throwable t) {
logger.warn("Failed to close current SearcherManager", t);
}
refreshVersioningTable(threadPool.estimatedTimeInMillis());
} catch (OutOfMemoryError e) {
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new FlushFailedEngineException(shardId, e);
}
} finally {
rwl.writeLock().unlock();
}
} else if (flush.type() == Flush.Type.COMMIT_TRANSLOG) {
rwl.readLock().lock();
try {
ensureOpen();
if (onGoingRecoveries.get() > 0) {
throw new FlushNotAllowedEngineException(shardId, "Recovery is in progress, flush is not allowed");
}
if (flushNeeded || flush.force()) {
flushNeeded = false;
try {
long translogId = translogIdGenerator.incrementAndGet();
translog.newTransientTranslog(translogId);
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
refreshVersioningTable(threadPool.estimatedTimeInMillis());
// we need to move transient to current only after we refresh
// so items added to current will still be around for realtime get
// when tans overrides it
translog.makeTransientCurrent();
} catch (OutOfMemoryError e) {
translog.revertTransient();
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
translog.revertTransient();
throw new FlushFailedEngineException(shardId, e);
}
}
} finally {
rwl.readLock().unlock();
}
} else if (flush.type() == Flush.Type.COMMIT) {
// note, its ok to just commit without cleaning the translog, its perfectly fine to replay a
// translog on an index that was opened on a committed point in time that is "in the future"
// of that translog
rwl.readLock().lock();
try {
ensureOpen();
// we allow to *just* commit if there is an ongoing recovery happening...
// its ok to use this, only a flush will cause a new translogId, and we are locked here from
// other flushes use flushLock
try {
long translogId = translog.currentId();
indexWriter.setCommitData(MapBuilder.<String, String>newMapBuilder().put(Translog.TRANSLOG_ID_KEY, Long.toString(translogId)).map());
indexWriter.commit();
} catch (OutOfMemoryError e) {
translog.revertTransient();
failEngine(e);
throw new FlushFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new FlushFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new FlushFailedEngineException(shardId, e);
}
} finally {
rwl.readLock().unlock();
}
} else {
throw new ElasticSearchIllegalStateException("flush type [" + flush.type() + "] not supported");
}
// reread the last committed segment infos
rwl.readLock().lock();
try {
ensureOpen();
readLastCommittedSegmentsInfo();
} catch (Throwable e) {
if (!closed) {
logger.warn("failed to read latest segment infos on flush", e);
}
} finally {
rwl.readLock().unlock();
}
} finally {
flushLock.unlock();
flushing.decrementAndGet();
}
}
private void ensureOpen() {
if (indexWriter == null) {
throw new EngineClosedException(shardId, failedEngine);
}
}
private void refreshVersioningTable(long time) {
// we need to refresh in order to clear older version values
refresh(new Refresh("version_table").force(true));
for (Map.Entry<HashedBytesRef, VersionValue> entry : versionMap.entrySet()) {
HashedBytesRef uid = entry.getKey();
synchronized (dirtyLock(uid.bytes)) { // can we do it without this lock on each value? maybe batch to a set and get the lock once per set?
VersionValue versionValue = versionMap.get(uid);
if (versionValue == null) {
continue;
}
if (time - versionValue.time() <= 0) {
continue; // its a newer value, from after/during we refreshed, don't clear it
}
if (versionValue.delete()) {
if (enableGcDeletes && (time - versionValue.time()) > gcDeletesInMillis) {
versionMap.remove(uid);
}
} else {
versionMap.remove(uid);
}
}
}
}
@Override
public void maybeMerge() throws EngineException {
if (!possibleMergeNeeded) {
return;
}
possibleMergeNeeded = false;
rwl.readLock().lock();
try {
ensureOpen();
indexWriter.maybeMerge();
} catch (OutOfMemoryError e) {
failEngine(e);
throw new OptimizeFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new OptimizeFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new OptimizeFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void optimize(Optimize optimize) throws EngineException {
if (optimize.flush()) {
flush(new Flush().force(true).waitIfOngoing(true));
}
if (optimizeMutex.compareAndSet(false, true)) {
rwl.readLock().lock();
try {
ensureOpen();
if (optimize.onlyExpungeDeletes()) {
indexWriter.forceMergeDeletes(false);
} else if (optimize.maxNumSegments() <= 0) {
indexWriter.maybeMerge();
possibleMergeNeeded = false;
} else {
indexWriter.forceMerge(optimize.maxNumSegments(), false);
}
} catch (OutOfMemoryError e) {
failEngine(e);
throw new OptimizeFailedEngineException(shardId, e);
} catch (IllegalStateException e) {
if (e.getMessage().contains("OutOfMemoryError")) {
failEngine(e);
}
throw new OptimizeFailedEngineException(shardId, e);
} catch (Throwable e) {
throw new OptimizeFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
optimizeMutex.set(false);
}
}
// wait for the merges outside of the read lock
if (optimize.waitForMerge()) {
indexWriter.waitForMerges();
}
if (optimize.flush()) {
flush(new Flush().force(true).waitIfOngoing(true));
}
}
@Override
public <T> T snapshot(SnapshotHandler<T> snapshotHandler) throws EngineException {
SnapshotIndexCommit snapshotIndexCommit = null;
Translog.Snapshot traslogSnapshot = null;
rwl.readLock().lock();
try {
snapshotIndexCommit = deletionPolicy.snapshot();
traslogSnapshot = translog.snapshot();
} catch (Throwable e) {
if (snapshotIndexCommit != null) {
snapshotIndexCommit.release();
}
throw new SnapshotFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
try {
return snapshotHandler.snapshot(snapshotIndexCommit, traslogSnapshot);
} finally {
snapshotIndexCommit.release();
traslogSnapshot.release();
}
}
@Override
public SnapshotIndexCommit snapshotIndex() throws EngineException {
rwl.readLock().lock();
try {
flush(new Flush().type(Flush.Type.COMMIT).waitIfOngoing(true));
ensureOpen();
return deletionPolicy.snapshot();
} catch (IOException e) {
throw new SnapshotFailedEngineException(shardId, e);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void recover(RecoveryHandler recoveryHandler) throws EngineException {
// take a write lock here so it won't happen while a flush is in progress
// this means that next commits will not be allowed once the lock is released
rwl.writeLock().lock();
try {
if (closed) {
throw new EngineClosedException(shardId);
}
onGoingRecoveries.increment();
} finally {
rwl.writeLock().unlock();
}
SnapshotIndexCommit phase1Snapshot;
try {
phase1Snapshot = deletionPolicy.snapshot();
} catch (Throwable e) {
onGoingRecoveries.decrement();
throw new RecoveryEngineException(shardId, 1, "Snapshot failed", e);
}
try {
recoveryHandler.phase1(phase1Snapshot);
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 1, "Execution failed", e);
}
Translog.Snapshot phase2Snapshot;
try {
phase2Snapshot = translog.snapshot();
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 2, "Snapshot failed", e);
}
try {
recoveryHandler.phase2(phase2Snapshot);
} catch (Throwable e) {
onGoingRecoveries.decrement();
phase1Snapshot.release();
phase2Snapshot.release();
if (closed) {
e = new EngineClosedException(shardId, e);
}
throw new RecoveryEngineException(shardId, 2, "Execution failed", e);
}
rwl.writeLock().lock();
Translog.Snapshot phase3Snapshot = null;
try {
phase3Snapshot = translog.snapshot(phase2Snapshot);
recoveryHandler.phase3(phase3Snapshot);
} catch (Throwable e) {
throw new RecoveryEngineException(shardId, 3, "Execution failed", e);
} finally {
onGoingRecoveries.decrement();
rwl.writeLock().unlock();
phase1Snapshot.release();
phase2Snapshot.release();
if (phase3Snapshot != null) {
phase3Snapshot.release();
}
}
}
@Override
public SegmentsStats segmentsStats() {
rwl.readLock().lock();
try {
ensureOpen();
Searcher searcher = acquireSearcher("segments_stats");
try {
SegmentsStats stats = new SegmentsStats();
stats.add(searcher.reader().leaves().size());
return stats;
} finally {
searcher.release();
}
} finally {
rwl.readLock().unlock();
}
}
@Override
public List<Segment> segments() {
rwl.readLock().lock();
try {
ensureOpen();
Map<String, Segment> segments = new HashMap<String, Segment>();
// first, go over and compute the search ones...
Searcher searcher = acquireSearcher("segments");
try {
for (AtomicReaderContext reader : searcher.reader().leaves()) {
assert reader.reader() instanceof SegmentReader;
SegmentCommitInfo info = ((SegmentReader) reader.reader()).getSegmentInfo();
assert !segments.containsKey(info.info.name);
Segment segment = new Segment(info.info.name);
segment.search = true;
segment.docCount = reader.reader().numDocs();
segment.delDocCount = reader.reader().numDeletedDocs();
segment.version = info.info.getVersion();
segment.compound = info.info.getUseCompoundFile();
try {
segment.sizeInBytes = info.sizeInBytes();
} catch (IOException e) {
logger.trace("failed to get size for [{}]", e, info.info.name);
}
segments.put(info.info.name, segment);
}
} finally {
searcher.release();
}
// now, correlate or add the committed ones...
if (lastCommittedSegmentInfos != null) {
SegmentInfos infos = lastCommittedSegmentInfos;
for (SegmentCommitInfo info : infos) {
Segment segment = segments.get(info.info.name);
if (segment == null) {
segment = new Segment(info.info.name);
segment.search = false;
segment.committed = true;
segment.docCount = info.info.getDocCount();
segment.delDocCount = info.getDelCount();
segment.version = info.info.getVersion();
segment.compound = info.info.getUseCompoundFile();
try {
segment.sizeInBytes = info.sizeInBytes();
} catch (IOException e) {
logger.trace("failed to get size for [{}]", e, info.info.name);
}
segments.put(info.info.name, segment);
} else {
segment.committed = true;
}
}
}
Segment[] segmentsArr = segments.values().toArray(new Segment[segments.values().size()]);
Arrays.sort(segmentsArr, new Comparator<Segment>() {
@Override
public int compare(Segment o1, Segment o2) {
return (int) (o1.getGeneration() - o2.getGeneration());
}
});
// fill in the merges flag
Set<OnGoingMerge> onGoingMerges = mergeScheduler.onGoingMerges();
for (OnGoingMerge onGoingMerge : onGoingMerges) {
for (SegmentCommitInfo segmentInfoPerCommit : onGoingMerge.getMergedSegments()) {
for (Segment segment : segmentsArr) {
if (segment.getName().equals(segmentInfoPerCommit.info.name)) {
segment.mergeId = onGoingMerge.getId();
break;
}
}
}
}
return Arrays.asList(segmentsArr);
} finally {
rwl.readLock().unlock();
}
}
@Override
public void close() throws ElasticSearchException {
rwl.writeLock().lock();
try {
innerClose();
} finally {
rwl.writeLock().unlock();
}
try {
// wait for recoveries to join and close all resources / IO streams
int ongoingRecoveries = onGoingRecoveries.awaitNoRecoveries(5000);
if (ongoingRecoveries > 0) {
logger.debug("Waiting for ongoing recoveries timed out on close currently ongoing disoveries: [{}]", ongoingRecoveries);
}
} catch (InterruptedException e) {
// ignore & restore interrupt
Thread.currentThread().interrupt();
}
}
class FailEngineOnMergeFailure implements MergeSchedulerProvider.FailureListener {
@Override
public void onFailedMerge(MergePolicy.MergeException e) {
failEngine(e);
}
}
private void failEngine(Throwable failure) {
synchronized (failedEngineMutex) {
if (failedEngine != null) {
return;
}
logger.warn("failed engine", failure);
failedEngine = failure;
for (FailedEngineListener listener : failedEngineListeners) {
listener.onFailedEngine(shardId, failure);
}
innerClose();
}
}
private void innerClose() {
if (closed) {
return;
}
indexSettingsService.removeListener(applySettings);
closed = true;
this.versionMap.clear();
this.failedEngineListeners.clear();
try {
try {
IOUtils.close(searcherManager);
} catch (Throwable t) {
logger.warn("Failed to close SearcherManager", t);
}
// no need to commit in this case!, we snapshot before we close the shard, so translog and all sync'ed
if (indexWriter != null) {
try {
indexWriter.rollback();
} catch (AlreadyClosedException e) {
// ignore
}
}
} catch (Throwable e) {
logger.debug("failed to rollback writer on close", e);
} finally {
indexWriter = null;
}
}
private HashedBytesRef versionKey(Term uid) {
return new HashedBytesRef(uid.bytes());
}
private Object dirtyLock(BytesRef uid) {
int hash = DjbHashFunction.DJB_HASH(uid.bytes, uid.offset, uid.length);
// abs returns Integer.MIN_VALUE, so we need to protect against it...
if (hash == Integer.MIN_VALUE) {
hash = 0;
}
return dirtyLocks[Math.abs(hash) % dirtyLocks.length];
}
private Object dirtyLock(Term uid) {
return dirtyLock(uid.bytes());
}
private long loadCurrentVersionFromIndex(Term uid) throws IOException {
Searcher searcher = acquireSearcher("load_version");
try {
return Versions.loadVersion(searcher.reader(), uid);
} finally {
searcher.release();
}
}
/**
* Returns whether a leaf reader comes from a merge (versus flush or addIndexes).
*/
private static boolean isMergedSegment(AtomicReader reader) {
// We expect leaves to be segment readers
final Map<String, String> diagnostics = ((SegmentReader) reader).getSegmentInfo().info.getDiagnostics();
final String source = diagnostics.get(IndexWriter.SOURCE);
assert Arrays.asList(IndexWriter.SOURCE_ADDINDEXES_READERS, IndexWriter.SOURCE_FLUSH, IndexWriter.SOURCE_MERGE).contains(source) : "Unknown source " + source;
return IndexWriter.SOURCE_MERGE.equals(source);
}
private IndexWriter createWriter() throws IOException {
try {
// release locks when started
if (IndexWriter.isLocked(store.directory())) {
logger.warn("shard is locked, releasing lock");
IndexWriter.unlock(store.directory());
}
boolean create = !Lucene.indexExists(store.directory());
IndexWriterConfig config = new IndexWriterConfig(Lucene.VERSION, analysisService.defaultIndexAnalyzer());
config.setOpenMode(create ? IndexWriterConfig.OpenMode.CREATE : IndexWriterConfig.OpenMode.APPEND);
config.setIndexDeletionPolicy(deletionPolicy);
config.setMergeScheduler(mergeScheduler.newMergeScheduler());
MergePolicy mergePolicy = mergePolicyProvider.newMergePolicy();
// Give us the opportunity to upgrade old segments while performing
// background merges
mergePolicy = new IndexUpgraderMergePolicy(mergePolicy);
config.setMergePolicy(mergePolicy);
config.setSimilarity(similarityService.similarity());
config.setRAMBufferSizeMB(indexingBufferSize.mbFrac());
config.setTermIndexInterval(termIndexInterval);
config.setReaderTermsIndexDivisor(termIndexDivisor);
config.setMaxThreadStates(indexConcurrency);
config.setCodec(codecService.codec(codecName));
/* We set this timeout to a highish value to work around
* the default poll interval in the Lucene lock that is
* 1000ms by default. We might need to poll multiple times
* here but with 1s poll this is only executed twice at most
* in combination with the default writelock timeout*/
config.setWriteLockTimeout(5000);
config.setUseCompoundFile(this.compoundOnFlush);
// Warm-up hook for newly-merged segments. Warming up segments here is better since it will be performed at the end
// of the merge operation and won't slow down _refresh
config.setMergedSegmentWarmer(new IndexReaderWarmer() {
@Override
public void warm(AtomicReader reader) throws IOException {
try {
assert isMergedSegment(reader);
final Engine.Searcher searcher = new SimpleSearcher("warmer", new IndexSearcher(reader));
final IndicesWarmer.WarmerContext context = new IndicesWarmer.WarmerContext(shardId, searcher);
if (warmer != null) warmer.warm(context);
} catch (Throwable t) {
// Don't fail a merge if the warm-up failed
if (!closed) {
logger.warn("Warm-up failed", t);
}
if (t instanceof Error) {
// assertion/out-of-memory error, don't ignore those
throw (Error) t;
}
}
}
});
return new IndexWriter(store.directory(), config);
} catch (LockObtainFailedException ex) {
boolean isLocked = IndexWriter.isLocked(store.directory());
logger.warn("Could not lock IndexWriter isLocked [{}]", ex, isLocked);
throw ex;
}
}
public static final String INDEX_TERM_INDEX_INTERVAL = "index.term_index_interval";
public static final String INDEX_TERM_INDEX_DIVISOR = "index.term_index_divisor";
public static final String INDEX_INDEX_CONCURRENCY = "index.index_concurrency";
public static final String INDEX_COMPOUND_ON_FLUSH = "index.compound_on_flush";
public static final String INDEX_GC_DELETES = "index.gc_deletes";
public static final String INDEX_FAIL_ON_MERGE_FAILURE = "index.fail_on_merge_failure";
class ApplySettings implements IndexSettingsService.Listener {
@Override
public void onRefreshSettings(Settings settings) {
long gcDeletesInMillis = settings.getAsTime(INDEX_GC_DELETES, TimeValue.timeValueMillis(RobinEngine.this.gcDeletesInMillis)).millis();
if (gcDeletesInMillis != RobinEngine.this.gcDeletesInMillis) {
logger.info("updating index.gc_deletes from [{}] to [{}]", TimeValue.timeValueMillis(RobinEngine.this.gcDeletesInMillis), TimeValue.timeValueMillis(gcDeletesInMillis));
RobinEngine.this.gcDeletesInMillis = gcDeletesInMillis;
}
final boolean compoundOnFlush = settings.getAsBoolean(INDEX_COMPOUND_ON_FLUSH, RobinEngine.this.compoundOnFlush);
if (compoundOnFlush != RobinEngine.this.compoundOnFlush) {
logger.info("updating {} from [{}] to [{}]", RobinEngine.INDEX_COMPOUND_ON_FLUSH, RobinEngine.this.compoundOnFlush, compoundOnFlush);
RobinEngine.this.compoundOnFlush = compoundOnFlush;
indexWriter.getConfig().setUseCompoundFile(compoundOnFlush);
}
int termIndexInterval = settings.getAsInt(INDEX_TERM_INDEX_INTERVAL, RobinEngine.this.termIndexInterval);
int termIndexDivisor = settings.getAsInt(INDEX_TERM_INDEX_DIVISOR, RobinEngine.this.termIndexDivisor); // IndexReader#DEFAULT_TERMS_INDEX_DIVISOR
int indexConcurrency = settings.getAsInt(INDEX_INDEX_CONCURRENCY, RobinEngine.this.indexConcurrency);
boolean failOnMergeFailure = settings.getAsBoolean(INDEX_FAIL_ON_MERGE_FAILURE, RobinEngine.this.failOnMergeFailure);
String codecName = settings.get(INDEX_CODEC, RobinEngine.this.codecName);
boolean requiresFlushing = false;
if (termIndexInterval != RobinEngine.this.termIndexInterval || termIndexDivisor != RobinEngine.this.termIndexDivisor || indexConcurrency != RobinEngine.this.indexConcurrency || !codecName.equals(RobinEngine.this.codecName) || failOnMergeFailure != RobinEngine.this.failOnMergeFailure) {
rwl.readLock().lock();
try {
if (termIndexInterval != RobinEngine.this.termIndexInterval) {
logger.info("updating index.term_index_interval from [{}] to [{}]", RobinEngine.this.termIndexInterval, termIndexInterval);
RobinEngine.this.termIndexInterval = termIndexInterval;
indexWriter.getConfig().setTermIndexInterval(termIndexInterval);
}
if (termIndexDivisor != RobinEngine.this.termIndexDivisor) {
logger.info("updating index.term_index_divisor from [{}] to [{}]", RobinEngine.this.termIndexDivisor, termIndexDivisor);
RobinEngine.this.termIndexDivisor = termIndexDivisor;
indexWriter.getConfig().setReaderTermsIndexDivisor(termIndexDivisor);
// we want to apply this right now for readers, even "current" ones
requiresFlushing = true;
}
if (indexConcurrency != RobinEngine.this.indexConcurrency) {
logger.info("updating index.index_concurrency from [{}] to [{}]", RobinEngine.this.indexConcurrency, indexConcurrency);
RobinEngine.this.indexConcurrency = indexConcurrency;
// we have to flush in this case, since it only applies on a new index writer
requiresFlushing = true;
}
if (!codecName.equals(RobinEngine.this.codecName)) {
logger.info("updating index.codec from [{}] to [{}]", RobinEngine.this.codecName, codecName);
RobinEngine.this.codecName = codecName;
// we want to flush in this case, so the new codec will be reflected right away...
requiresFlushing = true;
}
if (failOnMergeFailure != RobinEngine.this.failOnMergeFailure) {
logger.info("updating {} from [{}] to [{}]", RobinEngine.INDEX_FAIL_ON_MERGE_FAILURE, RobinEngine.this.failOnMergeFailure, failOnMergeFailure);
RobinEngine.this.failOnMergeFailure = failOnMergeFailure;
}
} finally {
rwl.readLock().unlock();
}
if (requiresFlushing) {
flush(new Flush().type(Flush.Type.NEW_WRITER));
}
}
}
}
private SearcherManager buildSearchManager(IndexWriter indexWriter) throws IOException {
return new SearcherManager(indexWriter, true, searcherFactory);
}
static class RobinSearcher implements Searcher {
private final String source;
private final IndexSearcher searcher;
private final SearcherManager manager;
private RobinSearcher(String source, IndexSearcher searcher, SearcherManager manager) {
this.source = source;
this.searcher = searcher;
this.manager = manager;
}
@Override
public String source() {
return this.source;
}
@Override
public IndexReader reader() {
return searcher.getIndexReader();
}
@Override
public IndexSearcher searcher() {
return searcher;
}
@Override
public boolean release() throws ElasticSearchException {
try {
manager.release(searcher);
return true;
} catch (IOException e) {
return false;
}
}
}
static class VersionValue {
private final long version;
private final boolean delete;
private final long time;
private final Translog.Location translogLocation;
VersionValue(long version, boolean delete, long time, Translog.Location translogLocation) {
this.version = version;
this.delete = delete;
this.time = time;
this.translogLocation = translogLocation;
}
public long time() {
return this.time;
}
public long version() {
return version;
}
public boolean delete() {
return delete;
}
public Translog.Location translogLocation() {
return this.translogLocation;
}
}
class RobinSearchFactory extends SearcherFactory {
@Override
public IndexSearcher newSearcher(IndexReader reader) throws IOException {
IndexSearcher searcher = new IndexSearcher(reader);
searcher.setSimilarity(similarityService.similarity());
if (warmer != null) {
// we need to pass a custom searcher that does not release anything on Engine.Search Release,
// we will release explicitly
Searcher currentSearcher = null;
IndexSearcher newSearcher = null;
boolean closeNewSearcher = false;
try {
if (searcherManager == null) {
// fresh index writer, just do on all of it
newSearcher = searcher;
} else {
currentSearcher = acquireSearcher("search_factory");
// figure out the newSearcher, with only the new readers that are relevant for us
List<IndexReader> readers = Lists.newArrayList();
for (AtomicReaderContext newReaderContext : searcher.getIndexReader().leaves()) {
if (isMergedSegment(newReaderContext.reader())) {
// merged segments are already handled by IndexWriterConfig.setMergedSegmentWarmer
continue;
}
boolean found = false;
for (AtomicReaderContext currentReaderContext : currentSearcher.reader().leaves()) {
if (currentReaderContext.reader().getCoreCacheKey().equals(newReaderContext.reader().getCoreCacheKey())) {
found = true;
break;
}
}
if (!found) {
readers.add(newReaderContext.reader());
}
}
if (!readers.isEmpty()) {
// we don't want to close the inner readers, just increase ref on them
newSearcher = new IndexSearcher(new MultiReader(readers.toArray(new IndexReader[readers.size()]), false));
closeNewSearcher = true;
}
}
if (newSearcher != null) {
IndicesWarmer.WarmerContext context = new IndicesWarmer.WarmerContext(shardId,
new SimpleSearcher("warmer", newSearcher));
warmer.warm(context);
}
} catch (Throwable e) {
if (!closed) {
logger.warn("failed to prepare/warm", e);
}
} finally {
// no need to release the fullSearcher, nothing really is done...
if (currentSearcher != null) {
currentSearcher.release();
}
if (newSearcher != null && closeNewSearcher) {
IOUtils.closeWhileHandlingException(newSearcher.getIndexReader()); // ignore
}
}
}
return searcher;
}
}
private static final class RecoveryCounter {
private volatile int ongoingRecoveries = 0;
synchronized void increment() {
ongoingRecoveries++;
}
synchronized void decrement() {
ongoingRecoveries--;
if (ongoingRecoveries == 0) {
notifyAll(); // notify waiting threads - we only wait on ongoingRecoveries == 0
}
assert ongoingRecoveries >= 0 : "ongoingRecoveries must be >= 0 but was: " + ongoingRecoveries;
}
int get() {
// volatile read - no sync needed
return ongoingRecoveries;
}
synchronized int awaitNoRecoveries(long timeout) throws InterruptedException {
if (ongoingRecoveries > 0) { // no loop here - we either time out or we are done!
wait(timeout);
}
return ongoingRecoveries;
}
}
}
|
diff --git a/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/product/BambooProductHandler.java b/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/product/BambooProductHandler.java
index d12da512..4453b256 100644
--- a/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/product/BambooProductHandler.java
+++ b/maven-amps-plugin/src/main/java/com/atlassian/maven/plugins/amps/product/BambooProductHandler.java
@@ -1,99 +1,100 @@
package com.atlassian.maven.plugins.amps.product;
import com.atlassian.maven.plugins.amps.MavenGoals;
import com.atlassian.maven.plugins.amps.Product;
import com.atlassian.maven.plugins.amps.ProductArtifact;
import com.atlassian.maven.plugins.amps.util.ConfigFileUtils;
import org.apache.maven.plugin.MojoExecutionException;
import org.apache.maven.project.MavenProject;
import java.io.File;
import java.util.*;
public class BambooProductHandler extends AbstractWebappProductHandler
{
public BambooProductHandler(MavenProject project, MavenGoals goals)
{
super(project, goals, new BambooPluginProvider());
}
public String getId()
{
return "bamboo";
}
public ProductArtifact getArtifact()
{
return new ProductArtifact("com.atlassian.bamboo", "atlassian-bamboo-web-app", "RELEASE");
}
protected Collection<ProductArtifact> getSalArtifacts(String salVersion)
{
return Arrays.asList(
new ProductArtifact("com.atlassian.sal", "sal-api", salVersion),
new ProductArtifact("com.atlassian.sal", "sal-bamboo-plugin", salVersion));
}
public ProductArtifact getTestResourcesArtifact()
{
return new ProductArtifact("com.atlassian.bamboo.plugins", "bamboo-plugin-test-resources", "LATEST");
}
public int getDefaultHttpPort()
{
return 6990;
}
public Map<String, String> getSystemProperties(Product ctx)
{
return Collections.singletonMap("bamboo.home", getHomeDirectory(ctx).getPath());
}
@Override
public File getUserInstalledPluginsDirectory(final File webappDir, final File homeDir)
{
return new File(homeDir, "plugins");
}
public List<ProductArtifact> getExtraContainerDependencies()
{
return Collections.emptyList();
}
public String getBundledPluginPath(Product ctx)
{
return "WEB-INF/classes/atlassian-bundled-plugins.zip";
}
public void processHomeDirectory(final Product ctx, final File homeDir) throws MojoExecutionException
{
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "@project-dir@", homeDir.getParent());
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "/bamboo-home/", "/home/");
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "${bambooHome}", homeDir.getAbsolutePath());
+ // The regex in the following search text is used to match IPv4 ([^:]+) or IPv6 (\[.+]) addresses.
ConfigFileUtils.replaceAll(new File(homeDir, "/xml-data/configuration/administration.xml"),
- "http://(?:[^:]|\\[.+])+:8085", "http://" + ctx.getServer() + ":" + ctx.getHttpPort() + "/" + ctx.getContextPath().replaceAll("^/|/$", ""));
+ "http://(?:[^:]+|\\[.+]):8085", "http://" + ctx.getServer() + ":" + ctx.getHttpPort() + "/" + ctx.getContextPath().replaceAll("^/|/$", ""));
}
public List<ProductArtifact> getDefaultLibPlugins()
{
return Collections.emptyList();
}
public List<ProductArtifact> getDefaultBundledPlugins()
{
return Collections.emptyList();
}
private static class BambooPluginProvider extends AbstractPluginProvider
{
@Override
protected Collection<ProductArtifact> getSalArtifacts(String salVersion)
{
return Arrays.asList(
new ProductArtifact("com.atlassian.sal", "sal-api", salVersion),
new ProductArtifact("com.atlassian.sal", "sal-bamboo-plugin", salVersion));
}
}
}
| false | true | public void processHomeDirectory(final Product ctx, final File homeDir) throws MojoExecutionException
{
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "@project-dir@", homeDir.getParent());
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "/bamboo-home/", "/home/");
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "${bambooHome}", homeDir.getAbsolutePath());
ConfigFileUtils.replaceAll(new File(homeDir, "/xml-data/configuration/administration.xml"),
"http://(?:[^:]|\\[.+])+:8085", "http://" + ctx.getServer() + ":" + ctx.getHttpPort() + "/" + ctx.getContextPath().replaceAll("^/|/$", ""));
}
| public void processHomeDirectory(final Product ctx, final File homeDir) throws MojoExecutionException
{
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "@project-dir@", homeDir.getParent());
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "/bamboo-home/", "/home/");
ConfigFileUtils.replace(new File(homeDir, "bamboo.cfg.xml"), "${bambooHome}", homeDir.getAbsolutePath());
// The regex in the following search text is used to match IPv4 ([^:]+) or IPv6 (\[.+]) addresses.
ConfigFileUtils.replaceAll(new File(homeDir, "/xml-data/configuration/administration.xml"),
"http://(?:[^:]+|\\[.+]):8085", "http://" + ctx.getServer() + ":" + ctx.getHttpPort() + "/" + ctx.getContextPath().replaceAll("^/|/$", ""));
}
|
diff --git a/src/main/java/com/celements/invoice/service/InvoiceService.java b/src/main/java/com/celements/invoice/service/InvoiceService.java
index adac25b..6faf5a0 100644
--- a/src/main/java/com/celements/invoice/service/InvoiceService.java
+++ b/src/main/java/com/celements/invoice/service/InvoiceService.java
@@ -1,90 +1,90 @@
/*
* See the NOTICE file distributed with this work for additional
* information regarding copyright ownership.
*
* This is free software; you can redistribute it and/or modify it
* under the terms of the GNU Lesser General Public License as
* published by the Free Software Foundation; either version 2.1 of
* the License, or (at your option) any later version.
*
* This software is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
* Lesser General Public License for more details.
*
* You should have received a copy of the GNU Lesser General Public
* License along with this software; if not, write to the Free
* Software Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA
* 02110-1301 USA, or see the FSF site: http://www.fsf.org.
*/
package com.celements.invoice.service;
import groovy.lang.Singleton;
import java.util.List;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.xwiki.component.annotation.Component;
import org.xwiki.component.annotation.Requirement;
import org.xwiki.context.Execution;
import org.xwiki.query.Query;
import org.xwiki.query.QueryException;
import org.xwiki.query.QueryManager;
import com.celements.invoice.InvoiceClassCollection;
import com.xpn.xwiki.XWikiContext;
@Component
@Singleton
public class InvoiceService implements IInvoiceServiceRole {
private static Log LOGGER = LogFactory.getFactory().getInstance(InvoiceService.class);
@Requirement
QueryManager query;
@Requirement
Execution execution;
private XWikiContext getContext() {
return (XWikiContext)execution.getContext().getProperty("xwikicontext");
}
synchronized public String getNewInvoiceNumber() {
int latestInvoiceNumber = getLatestInvoiceNumber() + 1;
return Integer.toString(latestInvoiceNumber);
}
private int getLatestInvoiceNumber() {
Integer latestInvoiceNumberFromDb = getLatestInvoiceNumberFromDb();
int minInvoiceNumberFromConfig = getContext().getWiki().getXWikiPreferenceAsInt(
"minInvoiceNumber", "com.celements.invoice.minInvoiceNumber", 1, getContext());
if ((latestInvoiceNumberFromDb == null)
|| (latestInvoiceNumberFromDb < minInvoiceNumberFromConfig)) {
return minInvoiceNumberFromConfig;
} else {
return latestInvoiceNumberFromDb;
}
}
private String getLatestInvoiceNumberXWQL() {
return "select max(invoice.invoiceNumber) from "
+ InvoiceClassCollection.INVOICE_CLASSES_SPACE + "."
+ InvoiceClassCollection.INVOICE_CLASS_DOC;
}
private Integer getLatestInvoiceNumberFromDb() {
try {
- List<Integer> result = query.createQuery(getLatestInvoiceNumberXWQL(), Query.XWQL
+ List<String> result = query.createQuery(getLatestInvoiceNumberXWQL(), Query.XWQL
).execute();
if (!result.isEmpty()) {
- return result.get(0);
+ return Integer.parseInt(result.get(0));
}
} catch (QueryException exp) {
LOGGER.error("Failed to get latest invoice number from db.", exp);
}
return null;
}
}
| false | true | private Integer getLatestInvoiceNumberFromDb() {
try {
List<Integer> result = query.createQuery(getLatestInvoiceNumberXWQL(), Query.XWQL
).execute();
if (!result.isEmpty()) {
return result.get(0);
}
} catch (QueryException exp) {
LOGGER.error("Failed to get latest invoice number from db.", exp);
}
return null;
}
| private Integer getLatestInvoiceNumberFromDb() {
try {
List<String> result = query.createQuery(getLatestInvoiceNumberXWQL(), Query.XWQL
).execute();
if (!result.isEmpty()) {
return Integer.parseInt(result.get(0));
}
} catch (QueryException exp) {
LOGGER.error("Failed to get latest invoice number from db.", exp);
}
return null;
}
|
diff --git a/src/org/newdawn/slick/Animation.java b/src/org/newdawn/slick/Animation.java
index 892d323..a52ce30 100644
--- a/src/org/newdawn/slick/Animation.java
+++ b/src/org/newdawn/slick/Animation.java
@@ -1,240 +1,243 @@
package org.newdawn.slick;
import java.util.ArrayList;
import org.lwjgl.Sys;
/**
* A utility to hold and render animations
*
* @author kevin
* @author DeX (speed updates)
*/
public class Animation {
/** The list of frames to render in this animation */
private ArrayList frames = new ArrayList();
/** The frame currently being displayed */
private int currentFrame = -1;
/** The time the next frame change should take place */
private long nextChange;
/** True if the animation is stopped */
private boolean stopped = false;
/** The time left til the next frame */
private long timeLeft;
/** The current speed of the animation */
private float speed = 1.0f;
/**
* Create an empty animation
*/
public Animation() {
nextFrame();
}
/**
* Create a new animation from a set of images
*
* @param frames The images for the animation frames
* @param duration The duration to show each frame
*/
public Animation(Image[] frames, int duration) {
for (int i=0;i<frames.length;i++) {
addFrame(frames[i], duration);
}
nextFrame();
}
/**
* Create a new animation from a set of images
*
* @param frames The images for the animation frames
* @param durations The duration to show each frame
*/
public Animation(Image[] frames, int[] durations) {
if (frames.length != durations.length) {
throw new RuntimeException("There must be one duration per frame");
}
for (int i=0;i<frames.length;i++) {
addFrame(frames[i], durations[i]);
}
nextFrame();
}
/**
* Adjust the overall speed of the animation.
*
* @param spd The speed to run the animation. Default: 1.0
*/
public void setSpeed(float spd) {
if (speed >= 0) speed = spd;
}
/**
* Returns the current speed of the animation.
*
* @return The speed this animation is being played back at
*/
public float getSpeed() {
return speed;
}
/**
* Stop the animation
*/
public void stop() {
if (frames.size() == 0) {
return;
}
timeLeft = nextChange - getTime();
stopped = true;
}
/**
* Start the animation playing again
*/
public void start() {
if (!stopped) {
return;
}
if (frames.size() == 0) {
return;
}
stopped = false;
nextChange = getTime() + timeLeft;
}
/**
* Restart the animation from the beginning
*/
public void restart() {
if (!stopped) {
return;
}
if (frames.size() == 0) {
return;
}
stopped = false;
currentFrame = -1;
nextFrame();
}
/**
* Add animation frame to the animation
*
* @param frame The image to display for the frame
* @param duration The duration to display the animation for
*/
public void addFrame(Image frame, int duration) {
frames.add(new Frame(frame, duration));
if (frames.size() == 1) {
nextFrame();
}
}
/**
* Draw the animation to the screen
*/
public void draw() {
draw(0,0);
}
/**
* Draw the animation at a specific location
*
* @param x The x position to draw the animation at
* @param y The y position to draw the animation at
*/
public void draw(int x,int y) {
draw(x,y,((Frame) frames.get(currentFrame)).image.getWidth(),
((Frame) frames.get(currentFrame)).image.getHeight());
}
/**
* Draw the animation
*
* @param x The x position to draw the animation at
* @param y The y position to draw the animation at
* @param width The width to draw the animation at
* @param height The height to draw the animation at
*/
public void draw(int x,int y,int width,int height) {
if (frames.size() == 0) {
return;
}
nextFrame();
Frame frame = (Frame) frames.get(currentFrame);
frame.image.draw(x,y,width,height);
}
/**
* Update the animation cycle without draw the image, useful
* for keeping two animations in sync
*/
public void updateNoDraw() {
nextFrame();
}
/**
* Get the index of the current frame
*
* @return The index of the current frame
*/
public int getFrame() {
return currentFrame;
}
/**
* Check if we need to move to the next frame
*/
private void nextFrame() {
if (stopped) {
return;
}
if (frames.size() == 0) {
return;
}
long now = getTime();
+ if (currentFrame == -1) {
+ nextChange = now;
+ }
while ((now > nextChange) || (currentFrame == -1)) {
currentFrame = (currentFrame + 1) % frames.size();
nextChange = (long) (nextChange + (((Frame) frames.get(currentFrame)).duration / speed));
}
}
/**
* Get the accurate system time
*
* @return The system time in milliseconds
*/
private long getTime() {
return (Sys.getTime() * 1000) / Sys.getTimerResolution();
}
/**
* A single frame within the animation
*
* @author kevin
*/
private class Frame {
/** The image to display for this frame */
public Image image;
/** The duration to display the image fro */
public int duration;
/**
* Create a new animation frame
*
* @param image The image to display for the frame
* @param duration The duration in millisecond to display the image for
*/
public Frame(Image image, int duration) {
this.image = image;
this.duration = duration;
}
}
}
| true | true | private void nextFrame() {
if (stopped) {
return;
}
if (frames.size() == 0) {
return;
}
long now = getTime();
while ((now > nextChange) || (currentFrame == -1)) {
currentFrame = (currentFrame + 1) % frames.size();
nextChange = (long) (nextChange + (((Frame) frames.get(currentFrame)).duration / speed));
}
}
| private void nextFrame() {
if (stopped) {
return;
}
if (frames.size() == 0) {
return;
}
long now = getTime();
if (currentFrame == -1) {
nextChange = now;
}
while ((now > nextChange) || (currentFrame == -1)) {
currentFrame = (currentFrame + 1) % frames.size();
nextChange = (long) (nextChange + (((Frame) frames.get(currentFrame)).duration / speed));
}
}
|
diff --git a/woodcock/WCConservation.java b/woodcock/WCConservation.java
index 552195e..59e108d 100644
--- a/woodcock/WCConservation.java
+++ b/woodcock/WCConservation.java
@@ -1,188 +1,191 @@
/*
* To change this template, choose Tools | Templates
* and open the template in the editor.
*/
package woodcock;
import java.io.*;
import java.util.*;
import org.neos.gams.*;
/**
*
* @author Z98
*/
public class WCConservation {
/*
* This class handles searching for candidate
* habitats where woodcock can live and finding
* candidates for cutting to create these habitats.
*/
boolean hasGams = false;
private PriorityQueue<Patch> habitatCandidates;
public HashMap<List<Integer>, Patch> candidateMap;
int requiredHabitats;
public WCConservation(int forestPatchSize) {
Comparator<Patch> comparator = new PatchLumberComparator();
habitatCandidates = new PriorityQueue<>(forestPatchSize, comparator);
candidateMap = new HashMap<>();
String pathEnv = System.getenv("PATH");
hasGams = pathEnv.contains("GAMS");
if (hasGams == false) {
hasGams = pathEnv.contains("gams");
}
}
// get the suitable patch for woodcock habitat
// still have to check against water patch and forest area
public void queueDevelopedPatch(RTree developedArea, RTree waterArea, int x, int y, Patch p) {
int rangeDevelop = 1000;
while (rangeDevelop > 100) {
if (LumberCompany.rangeQuery(developedArea, x, y, rangeDevelop) == null) {
if (LumberCompany.rangeQuery(waterArea, x, y, 1) != null) {
p.developDistance = rangeDevelop / 100;
habitatCandidates.add(p);
List<Integer> key = Arrays.asList(p.x, p.y);
candidateMap.put(key, p);
}
}
rangeDevelop -= 100;
}
}
public boolean isCandidate(Patch p) {
List<Integer> key = Arrays.asList(p.x, p.y);
Patch patch = candidateMap.get(key);
if (patch == null) {
return false;
}
return true;
}
public PriorityQueue<Patch> getPQueue() {
return habitatCandidates;
}
public LinkedList<Patch> optimizeCuts() {
LinkedList<Patch> selectedPatches = new LinkedList<>();
String results = new String();
HashMap<Integer, Integer> xValues = new HashMap<>();
HashMap<Integer, Integer> yValues = new HashMap<>();
PriorityQueue<Integer> xOrdered = new PriorityQueue<>();
PriorityQueue<Integer> yOrdered = new PriorityQueue<>();
ArrayList<PriorityQueue<Integer> > orderedSet = new ArrayList<>();
orderedSet.add(xOrdered);
orderedSet.add(yOrdered);
ArrayList<org.neos.gams.Set> gSets = new ArrayList<>();
final ArrayList<PriorityQueue<Integer> > fOrderedSet = orderedSet;
try {
if (hasGams) {
org.neos.gams.Set xSet = new org.neos.gams.Set("x", "X coordinates");
org.neos.gams.Set ySet = new org.neos.gams.Set("y", "X coordinates");
gSets.add(xSet);
gSets.add(ySet);
Parameter value = new Parameter("patchValue(x,y)", "Patch values");
Parameter isCandidate = new Parameter("isCandidate(x,y)", "Is a candidate");
Scalar minVal =
new Scalar(
"minVal",
"Minimally acceptable value",
String.valueOf(LumberCompany.MIN_VALUE));
Scalar required =
new Scalar(
"requiredPatches",
"Required number of patches to cut",
String.valueOf(requiredHabitats));
for(Patch candidate : habitatCandidates)
{
value.add(candidate.x + "." + candidate.y, String.valueOf(candidate.calcValue()));
isCandidate.add(candidate.x + "." + candidate.y, "1");
if(xValues.get(candidate.x) == null)
{
xValues.put(candidate.x, candidate.x);
xOrdered.add(candidate.x);
}
- if(xValues.get(candidate.y) == null)
+ if(yValues.get(candidate.y) == null)
{
- xValues.put(candidate.y, candidate.y);
- xOrdered.add(candidate.y);
+ yValues.put(candidate.y, candidate.y);
+ yOrdered.add(candidate.y);
}
}
final ArrayList<org.neos.gams.Set> fSets = gSets;
+ /*
+ * Add set members in parallel.
+ */
Parallel.withIndex(0, 1, new Parallel.Each() {
@Override
public void run(int i) {
PriorityQueue<Integer> xO = fOrderedSet.get(i);
for (Integer itgr : xO) {
fSets.get(i).addValue(String.valueOf(itgr));
}
}
});
StringBuilder modelContent = new StringBuilder();
try (Scanner scanner = new Scanner(new FileInputStream(Calculation.inputTemplatePath),
"ANSI")) {
while (scanner.hasNextLine()) {
modelContent.append(scanner.nextLine()).append("\n");
}
}
FileWriter modelFile =
new FileWriter(Calculation.outputModelPath);
modelFile.write(xSet.toString() + "\n");
modelFile.write(ySet.toString() + "\n");
modelFile.write(value.toString() + "\n");
modelFile.write(isCandidate.toString() + "\n");
modelFile.write(minVal.toString() + "\n");
modelFile.write(required.toString());
modelFile.write("\n");
modelFile.write(modelContent.toString());
ProcessBuilder pBuilder = new ProcessBuilder("gams");
pBuilder.redirectOutput();
Process gamsProcess = pBuilder.start();
BufferedReader gamsReader =
new BufferedReader(new InputStreamReader(gamsProcess.getInputStream()));
String line;
while((line = gamsReader.readLine()) != null)
{
results.concat(line + "\n");
if (gamsProcess.exitValue() == 0) {
}
}
}
} catch(IOException ex) {
System.err.println("Error: running GAMS locally failed: " + ex.getMessage());
}
SolutionParser parser = new SolutionParser(results);
SolutionData bCut = new SolutionData();
parser.getSymbol("cut", SolutionData.VAR, habitatCandidates.size());
for(SolutionRow sRow : bCut.getRows())
{
int level = sRow.getLevel().intValue();
if(level == 1)
{
int xCoord = Integer.valueOf(sRow.getIndex(0));
int yCoord = Integer.valueOf(sRow.getIndex(1));
List<Integer> key = Arrays.asList(xCoord, yCoord);
Patch cutPatch = candidateMap.get(key);
selectedPatches.add(cutPatch);
}
}
return selectedPatches;
}
}
| false | true | public LinkedList<Patch> optimizeCuts() {
LinkedList<Patch> selectedPatches = new LinkedList<>();
String results = new String();
HashMap<Integer, Integer> xValues = new HashMap<>();
HashMap<Integer, Integer> yValues = new HashMap<>();
PriorityQueue<Integer> xOrdered = new PriorityQueue<>();
PriorityQueue<Integer> yOrdered = new PriorityQueue<>();
ArrayList<PriorityQueue<Integer> > orderedSet = new ArrayList<>();
orderedSet.add(xOrdered);
orderedSet.add(yOrdered);
ArrayList<org.neos.gams.Set> gSets = new ArrayList<>();
final ArrayList<PriorityQueue<Integer> > fOrderedSet = orderedSet;
try {
if (hasGams) {
org.neos.gams.Set xSet = new org.neos.gams.Set("x", "X coordinates");
org.neos.gams.Set ySet = new org.neos.gams.Set("y", "X coordinates");
gSets.add(xSet);
gSets.add(ySet);
Parameter value = new Parameter("patchValue(x,y)", "Patch values");
Parameter isCandidate = new Parameter("isCandidate(x,y)", "Is a candidate");
Scalar minVal =
new Scalar(
"minVal",
"Minimally acceptable value",
String.valueOf(LumberCompany.MIN_VALUE));
Scalar required =
new Scalar(
"requiredPatches",
"Required number of patches to cut",
String.valueOf(requiredHabitats));
for(Patch candidate : habitatCandidates)
{
value.add(candidate.x + "." + candidate.y, String.valueOf(candidate.calcValue()));
isCandidate.add(candidate.x + "." + candidate.y, "1");
if(xValues.get(candidate.x) == null)
{
xValues.put(candidate.x, candidate.x);
xOrdered.add(candidate.x);
}
if(xValues.get(candidate.y) == null)
{
xValues.put(candidate.y, candidate.y);
xOrdered.add(candidate.y);
}
}
final ArrayList<org.neos.gams.Set> fSets = gSets;
Parallel.withIndex(0, 1, new Parallel.Each() {
@Override
public void run(int i) {
PriorityQueue<Integer> xO = fOrderedSet.get(i);
for (Integer itgr : xO) {
fSets.get(i).addValue(String.valueOf(itgr));
}
}
});
StringBuilder modelContent = new StringBuilder();
try (Scanner scanner = new Scanner(new FileInputStream(Calculation.inputTemplatePath),
"ANSI")) {
while (scanner.hasNextLine()) {
modelContent.append(scanner.nextLine()).append("\n");
}
}
FileWriter modelFile =
new FileWriter(Calculation.outputModelPath);
modelFile.write(xSet.toString() + "\n");
modelFile.write(ySet.toString() + "\n");
modelFile.write(value.toString() + "\n");
modelFile.write(isCandidate.toString() + "\n");
modelFile.write(minVal.toString() + "\n");
modelFile.write(required.toString());
modelFile.write("\n");
modelFile.write(modelContent.toString());
ProcessBuilder pBuilder = new ProcessBuilder("gams");
pBuilder.redirectOutput();
Process gamsProcess = pBuilder.start();
BufferedReader gamsReader =
new BufferedReader(new InputStreamReader(gamsProcess.getInputStream()));
String line;
while((line = gamsReader.readLine()) != null)
{
results.concat(line + "\n");
if (gamsProcess.exitValue() == 0) {
}
}
}
} catch(IOException ex) {
System.err.println("Error: running GAMS locally failed: " + ex.getMessage());
}
SolutionParser parser = new SolutionParser(results);
SolutionData bCut = new SolutionData();
parser.getSymbol("cut", SolutionData.VAR, habitatCandidates.size());
for(SolutionRow sRow : bCut.getRows())
{
int level = sRow.getLevel().intValue();
if(level == 1)
{
int xCoord = Integer.valueOf(sRow.getIndex(0));
int yCoord = Integer.valueOf(sRow.getIndex(1));
List<Integer> key = Arrays.asList(xCoord, yCoord);
Patch cutPatch = candidateMap.get(key);
selectedPatches.add(cutPatch);
}
}
return selectedPatches;
}
| public LinkedList<Patch> optimizeCuts() {
LinkedList<Patch> selectedPatches = new LinkedList<>();
String results = new String();
HashMap<Integer, Integer> xValues = new HashMap<>();
HashMap<Integer, Integer> yValues = new HashMap<>();
PriorityQueue<Integer> xOrdered = new PriorityQueue<>();
PriorityQueue<Integer> yOrdered = new PriorityQueue<>();
ArrayList<PriorityQueue<Integer> > orderedSet = new ArrayList<>();
orderedSet.add(xOrdered);
orderedSet.add(yOrdered);
ArrayList<org.neos.gams.Set> gSets = new ArrayList<>();
final ArrayList<PriorityQueue<Integer> > fOrderedSet = orderedSet;
try {
if (hasGams) {
org.neos.gams.Set xSet = new org.neos.gams.Set("x", "X coordinates");
org.neos.gams.Set ySet = new org.neos.gams.Set("y", "X coordinates");
gSets.add(xSet);
gSets.add(ySet);
Parameter value = new Parameter("patchValue(x,y)", "Patch values");
Parameter isCandidate = new Parameter("isCandidate(x,y)", "Is a candidate");
Scalar minVal =
new Scalar(
"minVal",
"Minimally acceptable value",
String.valueOf(LumberCompany.MIN_VALUE));
Scalar required =
new Scalar(
"requiredPatches",
"Required number of patches to cut",
String.valueOf(requiredHabitats));
for(Patch candidate : habitatCandidates)
{
value.add(candidate.x + "." + candidate.y, String.valueOf(candidate.calcValue()));
isCandidate.add(candidate.x + "." + candidate.y, "1");
if(xValues.get(candidate.x) == null)
{
xValues.put(candidate.x, candidate.x);
xOrdered.add(candidate.x);
}
if(yValues.get(candidate.y) == null)
{
yValues.put(candidate.y, candidate.y);
yOrdered.add(candidate.y);
}
}
final ArrayList<org.neos.gams.Set> fSets = gSets;
/*
* Add set members in parallel.
*/
Parallel.withIndex(0, 1, new Parallel.Each() {
@Override
public void run(int i) {
PriorityQueue<Integer> xO = fOrderedSet.get(i);
for (Integer itgr : xO) {
fSets.get(i).addValue(String.valueOf(itgr));
}
}
});
StringBuilder modelContent = new StringBuilder();
try (Scanner scanner = new Scanner(new FileInputStream(Calculation.inputTemplatePath),
"ANSI")) {
while (scanner.hasNextLine()) {
modelContent.append(scanner.nextLine()).append("\n");
}
}
FileWriter modelFile =
new FileWriter(Calculation.outputModelPath);
modelFile.write(xSet.toString() + "\n");
modelFile.write(ySet.toString() + "\n");
modelFile.write(value.toString() + "\n");
modelFile.write(isCandidate.toString() + "\n");
modelFile.write(minVal.toString() + "\n");
modelFile.write(required.toString());
modelFile.write("\n");
modelFile.write(modelContent.toString());
ProcessBuilder pBuilder = new ProcessBuilder("gams");
pBuilder.redirectOutput();
Process gamsProcess = pBuilder.start();
BufferedReader gamsReader =
new BufferedReader(new InputStreamReader(gamsProcess.getInputStream()));
String line;
while((line = gamsReader.readLine()) != null)
{
results.concat(line + "\n");
if (gamsProcess.exitValue() == 0) {
}
}
}
} catch(IOException ex) {
System.err.println("Error: running GAMS locally failed: " + ex.getMessage());
}
SolutionParser parser = new SolutionParser(results);
SolutionData bCut = new SolutionData();
parser.getSymbol("cut", SolutionData.VAR, habitatCandidates.size());
for(SolutionRow sRow : bCut.getRows())
{
int level = sRow.getLevel().intValue();
if(level == 1)
{
int xCoord = Integer.valueOf(sRow.getIndex(0));
int yCoord = Integer.valueOf(sRow.getIndex(1));
List<Integer> key = Arrays.asList(xCoord, yCoord);
Patch cutPatch = candidateMap.get(key);
selectedPatches.add(cutPatch);
}
}
return selectedPatches;
}
|
diff --git a/src/main/java/me/chaseoes/tf2/capturepoints/CapturePoint.java b/src/main/java/me/chaseoes/tf2/capturepoints/CapturePoint.java
index abd6e2e..861103c 100644
--- a/src/main/java/me/chaseoes/tf2/capturepoints/CapturePoint.java
+++ b/src/main/java/me/chaseoes/tf2/capturepoints/CapturePoint.java
@@ -1,137 +1,135 @@
package me.chaseoes.tf2.capturepoints;
import me.chaseoes.tf2.Game;
import me.chaseoes.tf2.GamePlayer;
import me.chaseoes.tf2.TF2;
import me.chaseoes.tf2.Team;
import me.chaseoes.tf2.utilities.Localizer;
import org.bukkit.Bukkit;
import org.bukkit.Location;
import org.bukkit.Sound;
public class CapturePoint implements Comparable<CapturePoint> {
String map;
Integer id;
Location location;
Integer task = 0;
Integer ptask = 0;
CaptureStatus status;
public GamePlayer capturing;
public CapturePoint(String map, Integer i, Location loc) {
capturing = null;
setStatus(CaptureStatus.UNCAPTURED);
id = i;
this.map = map;
location = loc;
}
public Integer getId() {
return id;
}
public Location getLocation() {
return location;
}
public CaptureStatus getStatus() {
return status;
}
public void setStatus(CaptureStatus s) {
status = s;
}
public void startCapturing(final GamePlayer player) {
capturing = player;
setStatus(CaptureStatus.CAPTURING);
Game game = capturing.getGame();
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("CP-BEING-CAPTURED").replace("%id", id.toString()));
task = CapturePointUtilities.getUtilities().plugin.getServer().getScheduler().scheduleSyncRepeatingTask(CapturePointUtilities.getUtilities().plugin, new Runnable() {
Integer timeRemaining = CapturePointUtilities.getUtilities().plugin.getConfig().getInt("capture-timer");
Integer timeTotal = CapturePointUtilities.getUtilities().plugin.getConfig().getInt("capture-timer");
Game game = capturing.getGame();
double diff = 1.0d / (timeTotal * 20);
int currentTick = 0;
@Override
public void run() {
game.setExpOfPlayers(diff * currentTick);
if (timeRemaining != 0 && currentTick % 20 == 0) {
- // player.sendMessage(ChatColor.YELLOW + "[TF2] " +
- // ChatColor.BOLD + ChatColor.DARK_RED + timeRemaining + " "
- // + ChatColor.RESET + ChatColor.RED +
- // "seconds remaining!");
- player.getPlayer().getWorld().strikeLightningEffect(player.getPlayer().getLocation());
+ if (TF2.getInstance().getConfig().getBoolean("lightning-while-capturing")) {
+ player.getPlayer().getWorld().strikeLightningEffect(player.getPlayer().getLocation());
+ }
}
if (timeRemaining == 0 && currentTick % 20 == 0) {
for (final GamePlayer gp : game.playersInGame.values()) {
TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() {
@Override
public void run() {
gp.getPlayer().playSound(gp.getPlayer().getLocation(), Sound.ANVIL_LAND, 1, 1);
}
}, 1L);
}
stopCapturing();
setStatus(CaptureStatus.CAPTURED);
player.setPointsCaptured(-1);
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("CP-CAPTURED").replace("%id", id.toString()).replace("%player", player.getName()));
game.setExpOfPlayers(0);
if (TF2.getInstance().getMap(map).allCaptured()) {
game.winMatch(Team.RED);
return;
}
}
currentTick++;
if (currentTick % 20 == 0) {
timeRemaining--;
timeTotal++;
}
}
}, 0L, 1L);
ptask = CapturePointUtilities.getUtilities().plugin.getServer().getScheduler().scheduleSyncRepeatingTask(CapturePointUtilities.getUtilities().plugin, new Runnable() {
@Override
public void run() {
GamePlayer p = capturing;
if (p == null) {
stopCapturing();
return;
}
if (!CapturePointUtilities.getUtilities().locationIsCapturePoint(player.getPlayer().getLocation())) {
stopCapturing();
return;
}
}
}, 0L, 1L);
}
public void stopCapturing() {
if (ptask != 0) {
Bukkit.getScheduler().cancelTask(ptask);
ptask = 0;
}
if (task != 0) {
Bukkit.getScheduler().cancelTask(task);
task = 0;
}
if (capturing != null && capturing.getGame() != null) {
capturing.getGame().setExpOfPlayers(0d);
capturing = null;
}
setStatus(CaptureStatus.UNCAPTURED);
}
@Override
public int compareTo(CapturePoint o) {
return this.getId() - o.getId();
}
}
| true | true | public void startCapturing(final GamePlayer player) {
capturing = player;
setStatus(CaptureStatus.CAPTURING);
Game game = capturing.getGame();
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("CP-BEING-CAPTURED").replace("%id", id.toString()));
task = CapturePointUtilities.getUtilities().plugin.getServer().getScheduler().scheduleSyncRepeatingTask(CapturePointUtilities.getUtilities().plugin, new Runnable() {
Integer timeRemaining = CapturePointUtilities.getUtilities().plugin.getConfig().getInt("capture-timer");
Integer timeTotal = CapturePointUtilities.getUtilities().plugin.getConfig().getInt("capture-timer");
Game game = capturing.getGame();
double diff = 1.0d / (timeTotal * 20);
int currentTick = 0;
@Override
public void run() {
game.setExpOfPlayers(diff * currentTick);
if (timeRemaining != 0 && currentTick % 20 == 0) {
// player.sendMessage(ChatColor.YELLOW + "[TF2] " +
// ChatColor.BOLD + ChatColor.DARK_RED + timeRemaining + " "
// + ChatColor.RESET + ChatColor.RED +
// "seconds remaining!");
player.getPlayer().getWorld().strikeLightningEffect(player.getPlayer().getLocation());
}
if (timeRemaining == 0 && currentTick % 20 == 0) {
for (final GamePlayer gp : game.playersInGame.values()) {
TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() {
@Override
public void run() {
gp.getPlayer().playSound(gp.getPlayer().getLocation(), Sound.ANVIL_LAND, 1, 1);
}
}, 1L);
}
stopCapturing();
setStatus(CaptureStatus.CAPTURED);
player.setPointsCaptured(-1);
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("CP-CAPTURED").replace("%id", id.toString()).replace("%player", player.getName()));
game.setExpOfPlayers(0);
if (TF2.getInstance().getMap(map).allCaptured()) {
game.winMatch(Team.RED);
return;
}
}
currentTick++;
if (currentTick % 20 == 0) {
timeRemaining--;
timeTotal++;
}
}
}, 0L, 1L);
ptask = CapturePointUtilities.getUtilities().plugin.getServer().getScheduler().scheduleSyncRepeatingTask(CapturePointUtilities.getUtilities().plugin, new Runnable() {
@Override
public void run() {
GamePlayer p = capturing;
if (p == null) {
stopCapturing();
return;
}
if (!CapturePointUtilities.getUtilities().locationIsCapturePoint(player.getPlayer().getLocation())) {
stopCapturing();
return;
}
}
}, 0L, 1L);
}
| public void startCapturing(final GamePlayer player) {
capturing = player;
setStatus(CaptureStatus.CAPTURING);
Game game = capturing.getGame();
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("CP-BEING-CAPTURED").replace("%id", id.toString()));
task = CapturePointUtilities.getUtilities().plugin.getServer().getScheduler().scheduleSyncRepeatingTask(CapturePointUtilities.getUtilities().plugin, new Runnable() {
Integer timeRemaining = CapturePointUtilities.getUtilities().plugin.getConfig().getInt("capture-timer");
Integer timeTotal = CapturePointUtilities.getUtilities().plugin.getConfig().getInt("capture-timer");
Game game = capturing.getGame();
double diff = 1.0d / (timeTotal * 20);
int currentTick = 0;
@Override
public void run() {
game.setExpOfPlayers(diff * currentTick);
if (timeRemaining != 0 && currentTick % 20 == 0) {
if (TF2.getInstance().getConfig().getBoolean("lightning-while-capturing")) {
player.getPlayer().getWorld().strikeLightningEffect(player.getPlayer().getLocation());
}
}
if (timeRemaining == 0 && currentTick % 20 == 0) {
for (final GamePlayer gp : game.playersInGame.values()) {
TF2.getInstance().getServer().getScheduler().scheduleSyncDelayedTask(TF2.getInstance(), new Runnable() {
@Override
public void run() {
gp.getPlayer().playSound(gp.getPlayer().getLocation(), Sound.ANVIL_LAND, 1, 1);
}
}, 1L);
}
stopCapturing();
setStatus(CaptureStatus.CAPTURED);
player.setPointsCaptured(-1);
game.broadcast(Localizer.getLocalizer().loadPrefixedMessage("CP-CAPTURED").replace("%id", id.toString()).replace("%player", player.getName()));
game.setExpOfPlayers(0);
if (TF2.getInstance().getMap(map).allCaptured()) {
game.winMatch(Team.RED);
return;
}
}
currentTick++;
if (currentTick % 20 == 0) {
timeRemaining--;
timeTotal++;
}
}
}, 0L, 1L);
ptask = CapturePointUtilities.getUtilities().plugin.getServer().getScheduler().scheduleSyncRepeatingTask(CapturePointUtilities.getUtilities().plugin, new Runnable() {
@Override
public void run() {
GamePlayer p = capturing;
if (p == null) {
stopCapturing();
return;
}
if (!CapturePointUtilities.getUtilities().locationIsCapturePoint(player.getPlayer().getLocation())) {
stopCapturing();
return;
}
}
}, 0L, 1L);
}
|
diff --git a/src/org/python/core/PyString.java b/src/org/python/core/PyString.java
index a9361f01..4f73a076 100644
--- a/src/org/python/core/PyString.java
+++ b/src/org/python/core/PyString.java
@@ -1,3007 +1,3012 @@
/// Copyright (c) Corporation for National Research Initiatives
package org.python.core;
import java.math.BigInteger;
import org.python.core.util.ExtraMath;
import org.python.core.util.StringUtil;
import org.python.expose.ExposedMethod;
import org.python.expose.ExposedNew;
import org.python.expose.ExposedType;
import org.python.expose.MethodType;
/**
* A builtin python string.
*/
@ExposedType(name = "str")
public class PyString extends PyBaseString
{
public static final PyType TYPE = PyType.fromClass(PyString.class);
protected String string;
private transient int cached_hashcode=0;
protected transient boolean interned=false;
// for PyJavaClass.init()
public PyString() {
this(TYPE, "");
}
public PyString(PyType subType, String string) {
super(subType);
if (string == null) {
throw new IllegalArgumentException(
"Cannot create PyString from null!");
}
this.string = string;
}
public PyString(String string) {
this(TYPE, string);
}
public PyString(char c) {
this(TYPE,String.valueOf(c));
}
PyString(StringBuilder buffer) {
this(TYPE, new String(buffer));
}
/**
* Creates a PyString from an already interned String. Just means it won't
* be reinterned if used in a place that requires interned Strings.
*/
public static PyString fromInterned(String interned) {
PyString str = new PyString(TYPE, interned);
str.interned = true;
return str;
}
@ExposedNew
final static PyObject str_new(PyNewWrapper new_, boolean init, PyType subtype,
PyObject[] args, String[] keywords) {
ArgParser ap = new ArgParser("str", args, keywords, new String[] { "object" }, 0);
PyObject S = ap.getPyObject(0, null);
if(new_.for_type == subtype) {
if(S == null) {
return new PyString("");
}
return new PyString(S.__str__().toString());
} else {
if (S == null) {
return new PyStringDerived(subtype, "");
}
return new PyStringDerived(subtype, S.__str__().toString());
}
}
public int[] toCodePoints() {
int n = string.length();
int[] codePoints = new int[n];
for (int i = 0; i < n; i++) {
codePoints[i] = string.charAt(i);
}
return codePoints;
}
public String substring(int start, int end) {
return string.substring(start, end);
}
public PyString __str__() {
return str___str__();
}
@ExposedMethod
final PyString str___str__() {
if (getClass() == PyString.class) {
return this;
}
return new PyString(string);
}
public PyUnicode __unicode__() {
return str___unicode__();
}
@ExposedMethod
final PyUnicode str___unicode__() {
return new PyUnicode(this);
}
public int __len__() {
return str___len__();
}
@ExposedMethod
final int str___len__() {
return string.length();
}
public String toString() {
return string;
}
public String internedString() {
if (interned)
return string;
else {
string = string.intern();
interned = true;
return string;
}
}
public PyString __repr__() {
return str___repr__();
}
@ExposedMethod
final PyString str___repr__() {
return new PyString(encode_UnicodeEscape(string, true));
}
private static char[] hexdigit = "0123456789abcdef".toCharArray();
public static String encode_UnicodeEscape(String str,
boolean use_quotes)
{
int size = str.length();
StringBuilder v = new StringBuilder(str.length());
char quote = 0;
if (use_quotes) {
quote = str.indexOf('\'') >= 0 &&
str.indexOf('"') == -1 ? '"' : '\'';
v.append(quote);
}
for (int i = 0; size-- > 0; ) {
int ch = str.charAt(i++);
/* Escape quotes */
if (use_quotes && (ch == quote || ch == '\\')) {
v.append('\\');
v.append((char) ch);
continue;
}
/* Map UTF-16 surrogate pairs to Unicode \UXXXXXXXX escapes */
else if (ch >= 0xD800 && ch < 0xDC00) {
char ch2 = str.charAt(i++);
size--;
if (ch2 >= 0xDC00 && ch2 <= 0xDFFF) {
int ucs = (((ch & 0x03FF) << 10) | (ch2 & 0x03FF)) + 0x00010000;
v.append('\\');
v.append('U');
v.append(hexdigit[(ucs >> 28) & 0xf]);
v.append(hexdigit[(ucs >> 24) & 0xf]);
v.append(hexdigit[(ucs >> 20) & 0xf]);
v.append(hexdigit[(ucs >> 16) & 0xf]);
v.append(hexdigit[(ucs >> 12) & 0xf]);
v.append(hexdigit[(ucs >> 8) & 0xf]);
v.append(hexdigit[(ucs >> 4) & 0xf]);
v.append(hexdigit[ucs & 0xf]);
continue;
}
/* Fall through: isolated surrogates are copied as-is */
i--;
size++;
}
/* Map 16-bit characters to '\\uxxxx' */
if (ch >= 256) {
v.append('\\');
v.append('u');
v.append(hexdigit[(ch >> 12) & 0xf]);
v.append(hexdigit[(ch >> 8) & 0xf]);
v.append(hexdigit[(ch >> 4) & 0xf]);
v.append(hexdigit[ch & 15]);
}
/* Map special whitespace to '\t', \n', '\r' */
else if (ch == '\t') v.append("\\t");
else if (ch == '\n') v.append("\\n");
else if (ch == '\r') v.append("\\r");
/* Map non-printable US ASCII to '\ooo' */
else if (ch < ' ' || ch >= 127) {
v.append('\\');
v.append('x');
v.append(hexdigit[(ch >> 4) & 0xf]);
v.append(hexdigit[ch & 0xf]);
}
/* Copy everything else as-is */
else
v.append((char) ch);
}
if (use_quotes)
v.append(quote);
return v.toString();
}
private static ucnhashAPI pucnHash = null;
public static String decode_UnicodeEscape(String str,
int start,
int end,
String errors,
boolean unicode) {
StringBuilder v = new StringBuilder(end - start);
for(int s = start; s < end;) {
char ch = str.charAt(s);
/* Non-escape characters are interpreted as Unicode ordinals */
if(ch != '\\') {
v.append(ch);
s++;
continue;
}
int loopStart = s;
/* \ - Escapes */
s++;
if(s == end) {
s = codecs.insertReplacementAndGetResume(v,
errors,
"unicodeescape",
str,
loopStart,
s + 1,
"\\ at end of string");
continue;
}
ch = str.charAt(s++);
switch(ch){
/* \x escapes */
case '\n':
break;
case '\\':
v.append('\\');
break;
case '\'':
v.append('\'');
break;
case '\"':
v.append('\"');
break;
case 'b':
v.append('\b');
break;
case 'f':
v.append('\014');
break; /* FF */
case 't':
v.append('\t');
break;
case 'n':
v.append('\n');
break;
case 'r':
v.append('\r');
break;
case 'v':
v.append('\013');
break; /* VT */
case 'a':
v.append('\007');
break; /* BEL, not classic C */
/* \OOO (octal) escapes */
case '0':
case '1':
case '2':
case '3':
case '4':
case '5':
case '6':
case '7':
int x = Character.digit(ch, 8);
for(int j = 0; j < 2 && s < end; j++, s++) {
ch = str.charAt(s);
if(ch < '0' || ch > '7')
break;
x = (x << 3) + Character.digit(ch, 8);
}
v.append((char)x);
break;
case 'x':
s = hexescape(v, errors, 2, s, str, end, "truncated \\xXX");
break;
case 'u':
if(!unicode) {
v.append('\\');
v.append('u');
break;
}
s = hexescape(v,
errors,
4,
s,
str,
end,
"truncated \\uXXXX");
break;
case 'U':
if(!unicode) {
v.append('\\');
v.append('U');
break;
}
s = hexescape(v,
errors,
8,
s,
str,
end,
"truncated \\UXXXXXXXX");
break;
case 'N':
if(!unicode) {
v.append('\\');
v.append('N');
break;
}
/*
* Ok, we need to deal with Unicode Character Names now,
* make sure we've imported the hash table data...
*/
if(pucnHash == null) {
PyObject mod = imp.importName("ucnhash", true);
mod = mod.__call__();
pucnHash = (ucnhashAPI)mod.__tojava__(Object.class);
if(pucnHash.getCchMax() < 0)
throw Py.UnicodeError("Unicode names not loaded");
}
if(str.charAt(s) == '{') {
int startName = s + 1;
int endBrace = startName;
/*
* look for either the closing brace, or we exceed the
* maximum length of the unicode character names
*/
int maxLen = pucnHash.getCchMax();
while(endBrace < end && str.charAt(endBrace) != '}'
&& (endBrace - startName) <= maxLen) {
endBrace++;
}
if(endBrace != end && str.charAt(endBrace) == '}') {
int value = pucnHash.getValue(str,
startName,
endBrace);
if(storeUnicodeCharacter(value, v)) {
s = endBrace + 1;
} else {
s = codecs.insertReplacementAndGetResume(v,
errors,
"unicodeescape",
str,
loopStart,
endBrace + 1,
"illegal Unicode character");
}
} else {
s = codecs.insertReplacementAndGetResume(v,
errors,
"unicodeescape",
str,
loopStart,
endBrace,
"malformed \\N character escape");
}
break;
} else {
s = codecs.insertReplacementAndGetResume(v,
errors,
"unicodeescape",
str,
loopStart,
s + 1,
"malformed \\N character escape");
}
break;
default:
v.append('\\');
v.append(str.charAt(s - 1));
break;
}
}
return v.toString();
}
private static int hexescape(StringBuilder partialDecode,
String errors,
int digits,
int hexDigitStart,
String str,
int size,
String errorMessage) {
if(hexDigitStart + digits > size) {
return codecs.insertReplacementAndGetResume(partialDecode,
errors,
"unicodeescape",
str,
hexDigitStart - 2,
size,
errorMessage);
}
int i = 0;
int x = 0;
for(; i < digits; ++i) {
char c = str.charAt(hexDigitStart + i);
int d = Character.digit(c, 16);
if(d == -1) {
return codecs.insertReplacementAndGetResume(partialDecode,
errors,
"unicodeescape",
str,
hexDigitStart - 2,
hexDigitStart + i + 1,
errorMessage);
}
x = (x << 4) & ~0xF;
if(c >= '0' && c <= '9')
x += c - '0';
else if(c >= 'a' && c <= 'f')
x += 10 + c - 'a';
else
x += 10 + c - 'A';
}
if(storeUnicodeCharacter(x, partialDecode)) {
return hexDigitStart + i;
} else {
return codecs.insertReplacementAndGetResume(partialDecode,
errors,
"unicodeescape",
str,
hexDigitStart - 2,
hexDigitStart + i + 1,
"illegal Unicode character");
}
}
/*pass in an int since this can be a UCS-4 character */
private static boolean storeUnicodeCharacter(int value,
StringBuilder partialDecode) {
if (value < 0 || (value >= 0xD800 && value <= 0xDFFF)) {
return false;
} else if (value <= PySystemState.maxunicode) {
partialDecode.appendCodePoint(value);
return true;
}
return false;
}
@ExposedMethod
final PyObject str___getitem__(PyObject index) {
return seq___finditem__(index);
}
@ExposedMethod(defaults = "null")
final PyObject str___getslice__(PyObject start, PyObject stop, PyObject step) {
return seq___getslice__(start, stop, step);
}
public int __cmp__(PyObject other) {
return str___cmp__(other);
}
@ExposedMethod(type = MethodType.CMP)
final int str___cmp__(PyObject other) {
if (!(other instanceof PyString))
return -2;
int c = string.compareTo(((PyString)other).string);
return c < 0 ? -1 : c > 0 ? 1 : 0;
}
public PyObject __eq__(PyObject other) {
return str___eq__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___eq__(PyObject other) {
String s = coerce(other);
if (s == null)
return null;
return string.equals(s) ? Py.True : Py.False;
}
public PyObject __ne__(PyObject other) {
return str___ne__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___ne__(PyObject other) {
String s = coerce(other);
if (s == null)
return null;
return string.equals(s) ? Py.False : Py.True;
}
public PyObject __lt__(PyObject other) {
return str___lt__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___lt__(PyObject other){
String s = coerce(other);
if (s == null)
return null;
return string.compareTo(s) < 0 ? Py.True : Py.False;
}
public PyObject __le__(PyObject other) {
return str___le__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___le__(PyObject other){
String s = coerce(other);
if (s == null)
return null;
return string.compareTo(s) <= 0 ? Py.True : Py.False;
}
public PyObject __gt__(PyObject other) {
return str___gt__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___gt__(PyObject other){
String s = coerce(other);
if (s == null)
return null;
return string.compareTo(s) > 0 ? Py.True : Py.False;
}
public PyObject __ge__(PyObject other) {
return str___ge__(other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___ge__(PyObject other){
String s = coerce(other);
if (s == null)
return null;
return string.compareTo(s) >= 0 ? Py.True : Py.False;
}
private static String coerce(PyObject o) {
if (o instanceof PyString)
return o.toString();
return null;
}
public int hashCode() {
return str___hash__();
}
@ExposedMethod
final int str___hash__() {
if (cached_hashcode == 0)
cached_hashcode = string.hashCode();
return cached_hashcode;
}
/**
* @return a byte array with one byte for each char in this object's
* underlying String. Each byte contains the low-order bits of its
* corresponding char.
*/
public byte[] toBytes() {
return StringUtil.toBytes(string);
}
public Object __tojava__(Class c) {
if (c.isAssignableFrom(String.class)) {
return string;
}
if (c == Character.TYPE || c == Character.class)
if (string.length() == 1)
return new Character(string.charAt(0));
if (c.isArray()) {
if (c.getComponentType() == Byte.TYPE)
return toBytes();
if (c.getComponentType() == Character.TYPE)
return string.toCharArray();
}
if (c.isInstance(this))
return this;
return Py.NoConversion;
}
protected PyObject pyget(int i) {
return Py.newString(string.charAt(i));
}
protected PyObject getslice(int start, int stop, int step) {
if (step > 0 && stop < start)
stop = start;
if (step == 1)
return fromSubstring(start, stop);
else {
int n = sliceLength(start, stop, step);
char new_chars[] = new char[n];
int j = 0;
for (int i=start; j<n; i+=step)
new_chars[j++] = string.charAt(i);
return createInstance(new String(new_chars), true);
}
}
public PyString createInstance(String str) {
return new PyString(str);
}
protected PyString createInstance(String str, boolean isBasic) {
// ignore isBasic, doesn't apply to PyString, just PyUnicode
return new PyString(str);
}
public boolean __contains__(PyObject o) {
return str___contains__(o);
}
@ExposedMethod
final boolean str___contains__(PyObject o) {
if (!(o instanceof PyString))
throw Py.TypeError("'in <string>' requires string as left operand");
PyString other = (PyString) o;
return string.indexOf(other.string) >= 0;
}
protected PyObject repeat(int count) {
if(count < 0) {
count = 0;
}
int s = string.length();
if((long)s * count > Integer.MAX_VALUE) {
// Since Strings store their data in an array, we can't make one
// longer than Integer.MAX_VALUE. Without this check we get
// NegativeArraySize exceptions when we create the array on the
// line with a wrapped int.
throw Py.OverflowError("max str len is " + Integer.MAX_VALUE);
}
char new_chars[] = new char[s * count];
for(int i = 0; i < count; i++) {
string.getChars(0, s, new_chars, i * s);
}
return createInstance(new String(new_chars), true);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___mul__(PyObject o) {
if (!(o instanceof PyInteger || o instanceof PyLong))
return null;
int count = ((PyInteger)o.__int__()).getValue();
return repeat(count);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___rmul__(PyObject o) {
if (!(o instanceof PyInteger || o instanceof PyLong))
return null;
int count = ((PyInteger)o.__int__()).getValue();
return repeat(count);
}
public PyObject __add__(PyObject generic_other) {
return str___add__(generic_other);
}
@ExposedMethod(type = MethodType.BINARY)
final PyObject str___add__(PyObject generic_other) {
if (generic_other instanceof PyString) {
PyString other = (PyString)generic_other;
String result = string.concat(other.string);
if (generic_other instanceof PyUnicode) {
return new PyUnicode(result);
}
return createInstance(result, true);
}
else return null;
}
@ExposedMethod
final PyTuple str___getnewargs__() {
return new PyTuple(new PyString(this.string));
}
public PyTuple __getnewargs__() {
return str___getnewargs__();
}
public PyObject __mod__(PyObject other) {
return str___mod__(other);
}
@ExposedMethod
public PyObject str___mod__(PyObject other){
StringFormatter fmt = new StringFormatter(string, false);
return fmt.format(other);
}
public PyObject __int__() {
try
{
return Py.newInteger(atoi(10));
} catch (PyException e) {
if (Py.matchException(e, Py.OverflowError)) {
return atol(10);
}
throw e;
}
}
public PyObject __long__() {
return atol(10);
}
public PyFloat __float__() {
return new PyFloat(atof());
}
public PyObject __pos__() {
throw Py.TypeError("bad operand type for unary +");
}
public PyObject __neg__() {
throw Py.TypeError("bad operand type for unary -");
}
public PyObject __invert__() {
throw Py.TypeError("bad operand type for unary ~");
}
public PyComplex __complex__() {
boolean got_re = false;
boolean got_im = false;
boolean done = false;
boolean sw_error = false;
int s = 0;
int n = string.length();
while (s < n && Character.isSpaceChar(string.charAt(s)))
s++;
if (s == n) {
throw Py.ValueError("empty string for complex()");
}
double z = -1.0;
double x = 0.0;
double y = 0.0;
int sign = 1;
do {
char c = string.charAt(s);
switch (c) {
case '-':
sign = -1;
/* Fallthrough */
case '+':
if (done || s+1 == n) {
sw_error = true;
break;
}
// a character is guaranteed, but it better be a digit
// or J or j
c = string.charAt(++s); // eat the sign character
// and check the next
if (!Character.isDigit(c) && c!='J' && c!='j')
sw_error = true;
break;
case 'J':
case 'j':
if (got_im || done) {
sw_error = true;
break;
}
if (z < 0.0) {
y = sign;
} else {
y = sign * z;
}
got_im = true;
done = got_re;
sign = 1;
s++; // eat the J or j
break;
case ' ':
while (s < n && Character.isSpaceChar(string.charAt(s)))
s++;
if (s != n)
sw_error = true;
break;
default:
boolean digit_or_dot = (c == '.' || Character.isDigit(c));
if (!digit_or_dot) {
sw_error = true;
break;
}
int end = endDouble(string, s);
z = Double.valueOf(string.substring(s, end)).doubleValue();
if (z == Double.POSITIVE_INFINITY) {
throw Py.ValueError(String.format("float() out of range: %.150s", string));
}
s=end;
if (s < n) {
c = string.charAt(s);
if (c == 'J' || c == 'j') {
break;
}
}
if (got_re) {
sw_error = true;
break;
}
/* accept a real part */
x = sign * z;
got_re = true;
done = got_im;
z = -1.0;
sign = 1;
break;
} /* end of switch */
} while (s < n && !sw_error);
if (sw_error) {
throw Py.ValueError("malformed string for complex() " +
string.substring(s));
}
return new PyComplex(x,y);
}
private int endDouble(String string, int s) {
int n = string.length();
while (s < n) {
char c = string.charAt(s++);
if (Character.isDigit(c))
continue;
if (c == '.')
continue;
if (c == 'e' || c == 'E') {
if (s < n) {
c = string.charAt(s);
if (c == '+' || c == '-')
s++;
continue;
}
}
return s-1;
}
return s;
}
// Add in methods from string module
public String lower() {
return str_lower();
}
@ExposedMethod
final String str_lower() {
return string.toLowerCase();
}
public String upper() {
return str_upper();
}
@ExposedMethod
final String str_upper() {
return string.toUpperCase();
}
public String title() {
return str_title();
}
@ExposedMethod
final String str_title() {
char[] chars = string.toCharArray();
int n = chars.length;
boolean previous_is_cased = false;
for (int i = 0; i < n; i++) {
char ch = chars[i];
if (previous_is_cased)
chars[i] = Character.toLowerCase(ch);
else
chars[i] = Character.toTitleCase(ch);
if (Character.isLowerCase(ch) ||
Character.isUpperCase(ch) ||
Character.isTitleCase(ch))
previous_is_cased = true;
else
previous_is_cased = false;
}
return new String(chars);
}
public String swapcase() {
return str_swapcase();
}
@ExposedMethod
final String str_swapcase() {
char[] chars = string.toCharArray();
int n=chars.length;
for (int i=0; i<n; i++) {
char c = chars[i];
if (Character.isUpperCase(c)) {
chars[i] = Character.toLowerCase(c);
}
else if (Character.isLowerCase(c)) {
chars[i] = Character.toUpperCase(c);
}
}
return new String(chars);
}
public String strip() {
return str_strip(null);
}
public String strip(String sep) {
return str_strip(sep);
}
@ExposedMethod(defaults = "null")
final String str_strip(String sep) {
char[] chars = string.toCharArray();
int n=chars.length;
int start=0;
if (sep == null)
while (start < n && Character.isWhitespace(chars[start]))
start++;
else
while (start < n && sep.indexOf(chars[start]) >= 0)
start++;
int end=n-1;
if (sep == null)
while (end >= 0 && Character.isWhitespace(chars[end]))
end--;
else
while (end >= 0 && sep.indexOf(chars[end]) >= 0)
end--;
if (end >= start) {
return (end < n-1 || start > 0)
? string.substring(start, end+1) : string;
} else {
return "";
}
}
public String lstrip() {
return str_lstrip(null);
}
public String lstrip(String sep) {
return str_lstrip(sep);
}
@ExposedMethod(defaults = "null")
final String str_lstrip(String sep) {
char[] chars = string.toCharArray();
int n=chars.length;
int start=0;
if (sep == null)
while (start < n && Character.isWhitespace(chars[start]))
start++;
else
while (start < n && sep.indexOf(chars[start]) >= 0)
start++;
return (start > 0) ? string.substring(start, n) : string;
}
public String rstrip(String sep) {
return str_rstrip(sep);
}
@ExposedMethod(defaults = "null")
final String str_rstrip(String sep) {
char[] chars = string.toCharArray();
int n=chars.length;
int end=n-1;
if (sep == null)
while (end >= 0 && Character.isWhitespace(chars[end]))
end--;
else
while (end >= 0 && sep.indexOf(chars[end]) >= 0)
end--;
return (end < n-1) ? string.substring(0, end+1) : string;
}
public PyList split() {
return str_split(null, -1);
}
public PyList split(String sep) {
return str_split(sep, -1);
}
public PyList split(String sep, int maxsplit) {
return str_split(sep, maxsplit);
}
@ExposedMethod(defaults = {"null", "-1"})
final PyList str_split(String sep, int maxsplit) {
if (sep != null) {
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
return splitfields(sep, maxsplit);
}
PyList list = new PyList();
char[] chars = string.toCharArray();
int n=chars.length;
if (maxsplit < 0)
maxsplit = n;
int splits=0;
int index=0;
while (index < n && splits < maxsplit) {
while (index < n && Character.isWhitespace(chars[index]))
index++;
if (index == n)
break;
int start = index;
while (index < n && !Character.isWhitespace(chars[index]))
index++;
list.append(fromSubstring(start, index));
splits++;
}
while (index < n && Character.isWhitespace(chars[index]))
index++;
if (index < n) {
list.append(fromSubstring(index, n));
}
return list;
}
public PyList rsplit() {
return str_rsplit(null, -1);
}
public PyList rsplit(String sep) {
return str_rsplit(sep, -1);
}
public PyList rsplit(String sep, int maxsplit) {
return str_rsplit(sep, maxsplit);
}
@ExposedMethod(defaults = {"null", "-1"})
final PyList str_rsplit(String sep, int maxsplit) {
if (sep != null) {
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
PyList list = rsplitfields(sep, maxsplit);
list.reverse();
return list;
}
PyList list = new PyList();
char[] chars = string.toCharArray();
if (maxsplit < 0) {
maxsplit = chars.length;
}
int splits = 0;
int i = chars.length - 1;
while (i > -1 && Character.isWhitespace(chars[i])) {
i--;
}
if (i == -1) {
return list;
}
while (splits < maxsplit) {
while (i > -1 && Character.isWhitespace(chars[i])) {
i--;
}
if (i == -1) {
break;
}
int nextWsChar = i;
while (nextWsChar > -1 && !Character.isWhitespace(chars[nextWsChar])) {
nextWsChar--;
}
if (nextWsChar == -1) {
break;
}
splits++;
list.add(fromSubstring(nextWsChar + 1, i + 1));
i = nextWsChar;
}
while (i > -1 && Character.isWhitespace(chars[i])) {
i--;
}
if (i > -1) {
list.add(fromSubstring(0,i+1));
}
list.reverse();
return list;
}
public PyTuple partition(PyObject sepObj) {
return str_partition(sepObj);
}
@ExposedMethod
final PyTuple str_partition(PyObject sepObj) {
String sep;
if (sepObj instanceof PyUnicode) {
return unicodePartition(sepObj);
} else if (sepObj instanceof PyString) {
sep = ((PyString)sepObj).string;
} else {
throw Py.TypeError("expected a character buffer object");
}
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
int index = string.indexOf(sep);
if (index != -1) {
return new PyTuple(fromSubstring(0, index), sepObj,
fromSubstring(index + sep.length(), string.length()));
} else {
return new PyTuple(this, Py.EmptyString, Py.EmptyString);
}
}
final PyTuple unicodePartition(PyObject sepObj) {
PyUnicode strObj = __unicode__();
String str = strObj.string;
// Will throw a TypeError if not a basestring
String sep = sepObj.asString();
sepObj = sepObj.__unicode__();
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
int index = str.indexOf(sep);
if (index != -1) {
return new PyTuple(strObj.fromSubstring(0, index), sepObj,
strObj.fromSubstring(index + sep.length(), str.length()));
} else {
PyUnicode emptyUnicode = Py.newUnicode("");
return new PyTuple(this, emptyUnicode, emptyUnicode);
}
}
public PyTuple rpartition(PyObject sepObj) {
return str_rpartition(sepObj);
}
@ExposedMethod
final PyTuple str_rpartition(PyObject sepObj) {
String sep;
if (sepObj instanceof PyUnicode) {
return unicodePartition(sepObj);
} else if (sepObj instanceof PyString) {
sep = ((PyString)sepObj).string;
} else {
throw Py.TypeError("expected a character buffer object");
}
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
int index = string.lastIndexOf(sep);
if (index != -1) {
return new PyTuple(fromSubstring(0, index), sepObj,
fromSubstring(index + sep.length(), string.length()));
} else {
return new PyTuple(Py.EmptyString, Py.EmptyString, this);
}
}
final PyTuple unicodeRpartition(PyObject sepObj) {
PyUnicode strObj = __unicode__();
String str = strObj.string;
// Will throw a TypeError if not a basestring
String sep = sepObj.asString();
sepObj = sepObj.__unicode__();
if (sep.length() == 0) {
throw Py.ValueError("empty separator");
}
int index = str.lastIndexOf(sep);
if (index != -1) {
return new PyTuple(strObj.fromSubstring(0, index), sepObj,
strObj.fromSubstring(index + sep.length(), str.length()));
} else {
PyUnicode emptyUnicode = Py.newUnicode("");
return new PyTuple(emptyUnicode, emptyUnicode, this);
}
}
private PyList splitfields(String sep, int maxsplit) {
PyList list = new PyList();
int length = string.length();
if (maxsplit < 0)
maxsplit = length + 1;
int lastbreak = 0;
int splits = 0;
int sepLength = sep.length();
int index;
if((sep.length() == 0) && (maxsplit != 0)) {
index = string.indexOf(sep, lastbreak);
list.append(fromSubstring(lastbreak, index));
splits++;
}
while (splits < maxsplit) {
index = string.indexOf(sep, lastbreak);
if (index == -1)
break;
if(sep.length() == 0)
index++;
splits += 1;
list.append(fromSubstring(lastbreak, index));
lastbreak = index + sepLength;
}
if (lastbreak <= length) {
list.append(fromSubstring(lastbreak, length));
}
return list;
}
private PyList rsplitfields(String sep, int maxsplit) {
PyList list = new PyList();
int length = string.length();
if (maxsplit < 0) {
maxsplit = length + 1;
}
int lastbreak = length;
int splits = 0;
int index = length;
int sepLength = sep.length();
while (index > 0 && splits < maxsplit) {
int i = string.lastIndexOf(sep, index - sepLength);
if (i == index) {
i -= sepLength;
}
if (i < 0) {
break;
}
splits++;
list.append(fromSubstring(i + sepLength, lastbreak));
lastbreak = i;
index = i;
}
list.append(fromSubstring(0, lastbreak));
return list;
}
public PyList splitlines() {
return str_splitlines(false);
}
public PyList splitlines(boolean keepends) {
return str_splitlines(keepends);
}
@ExposedMethod(defaults = "false")
final PyList str_splitlines(boolean keepends) {
PyList list = new PyList();
char[] chars = string.toCharArray();
int n=chars.length;
int j = 0;
for (int i = 0; i < n; ) {
/* Find a line and append it */
while (i < n && chars[i] != '\n' && chars[i] != '\r' &&
Character.getType(chars[i]) != Character.LINE_SEPARATOR)
i++;
/* Skip the line break reading CRLF as one line break */
int eol = i;
if (i < n) {
if (chars[i] == '\r' && i + 1 < n && chars[i+1] == '\n')
i += 2;
else
i++;
if (keepends)
eol = i;
}
list.append(fromSubstring(j, eol));
j = i;
}
if (j < n) {
list.append(fromSubstring(j, n));
}
return list;
}
protected PyString fromSubstring(int begin, int end) {
return createInstance(string.substring(begin, end), true);
}
public int index(String sub) {
return str_index(sub, 0, null);
}
public int index(String sub, int start) {
return str_index(sub, start, null);
}
public int index(String sub, int start, int end) {
return str_index(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"})
final int str_index(String sub, int start, PyObject end) {
int index = str_find(sub, start, end);
if (index == -1)
throw Py.ValueError("substring not found in string.index");
return index;
}
public int rindex(String sub) {
return str_rindex(sub, 0, null);
}
public int rindex(String sub, int start) {
return str_rindex(sub, start, null);
}
public int rindex(String sub, int start, int end) {
return str_rindex(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"})
final int str_rindex(String sub, int start, PyObject end) {
int index = str_rfind(sub, start, end);
if(index == -1)
throw Py.ValueError("substring not found in string.rindex");
return index;
}
public int count(String sub) {
return str_count(sub, 0, null);
}
public int count(String sub, int start) {
return str_count(sub, start, null);
}
public int count(String sub, int start, int end) {
return str_count(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"})
final int str_count(String sub, int start, PyObject end) {
int[] indices = translateIndices(start, end);
int n = sub.length();
if(n == 0) {
if (start > string.length()) {
return 0;
}
return indices[1] - indices[0] + 1;
}
int count = 0;
while(true){
int index = string.indexOf(sub, indices[0]);
indices[0] = index + n;
if(indices[0] > indices[1] || index == -1) {
break;
}
count++;
}
return count;
}
public int find(String sub) {
return str_find(sub, 0, null);
}
public int find(String sub, int start) {
return str_find(sub, start, null);
}
public int find(String sub, int start, int end) {
return str_find(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"})
final int str_find(String sub, int start, PyObject end) {
int[] indices = translateIndices(start, end);
int index = string.indexOf(sub, indices[0]);
if (index < start || index > indices[1]) {
return -1;
}
return index;
}
public int rfind(String sub) {
return str_rfind(sub, 0, null);
}
public int rfind(String sub, int start) {
return str_rfind(sub, start, null);
}
public int rfind(String sub, int start, int end) {
return str_rfind(sub, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"})
final int str_rfind(String sub, int start, PyObject end) {
int[] indices = translateIndices(start, end);
int index = string.lastIndexOf(sub, indices[1] - sub.length());
if (index < start) {
return -1;
}
return index;
}
public double atof() {
StringBuilder s = null;
int n = string.length();
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (ch == '\u0000') {
throw Py.ValueError("null byte in argument for float()");
}
if (Character.isDigit(ch)) {
if (s == null)
s = new StringBuilder(string);
int val = Character.digit(ch, 10);
s.setCharAt(i, Character.forDigit(val, 10));
}
}
String sval = string;
if (s != null)
sval = s.toString();
try {
// Double.valueOf allows format specifier ("d" or "f") at the end
String lowSval = sval.toLowerCase();
if (lowSval.endsWith("d") || lowSval.endsWith("f")) {
throw new NumberFormatException("format specifiers not allowed");
}
return Double.valueOf(sval).doubleValue();
}
catch (NumberFormatException exc) {
throw Py.ValueError("invalid literal for __float__: "+string);
}
}
public int atoi() {
return atoi(10);
}
public int atoi(int base) {
if ((base != 0 && base < 2) || (base > 36)) {
throw Py.ValueError("invalid base for atoi()");
}
int b = 0;
int e = string.length();
while (b < e && Character.isWhitespace(string.charAt(b)))
b++;
while (e > b && Character.isWhitespace(string.charAt(e-1)))
e--;
char sign = 0;
if (b < e) {
sign = string.charAt(b);
if (sign == '-' || sign == '+') {
b++;
while (b < e && Character.isWhitespace(string.charAt(b))) b++;
}
if (base == 0 || base == 16) {
if (string.charAt(b) == '0') {
if (b < e-1 &&
Character.toUpperCase(string.charAt(b+1)) == 'X') {
base = 16;
b += 2;
} else {
if (base == 0)
base = 8;
}
}
}
}
if (base == 0)
base = 10;
String s = string;
if (b > 0 || e < string.length())
s = string.substring(b, e);
try {
BigInteger bi;
if (sign == '-') {
bi = new BigInteger("-" + s, base);
} else
bi = new BigInteger(s, base);
if (bi.compareTo(PyInteger.maxInt) > 0 || bi.compareTo(PyInteger.minInt) < 0) {
throw Py.OverflowError("long int too large to convert to int");
}
return bi.intValue();
} catch (NumberFormatException exc) {
throw Py.ValueError("invalid literal for int() with base " + base + ": " + string);
} catch (StringIndexOutOfBoundsException exc) {
throw Py.ValueError("invalid literal for int() with base " + base + ": " + string);
}
}
public PyLong atol() {
return atol(10);
}
public PyLong atol(int base) {
String str = string;
int b = 0;
int e = str.length();
while (b < e && Character.isWhitespace(str.charAt(b)))
b++;
while (e > b && Character.isWhitespace(str.charAt(e-1)))
e--;
char sign = 0;
if (b < e) {
sign = string.charAt(b);
if (sign == '-' || sign == '+') {
b++;
while (b < e && Character.isWhitespace(str.charAt(b))) b++;
}
if (base == 0 || base == 16) {
if (string.charAt(b) == '0') {
if (b < e-1 &&
Character.toUpperCase(string.charAt(b+1)) == 'X') {
base = 16;
b += 2;
} else {
if (base == 0)
base = 8;
}
}
}
}
if (base == 0)
base = 10;
if (base < 2 || base > 36)
throw Py.ValueError("invalid base for long literal:" + base);
// if the base >= 22, then an 'l' or 'L' is a digit!
if (base < 22 && e > b && (str.charAt(e-1) == 'L' || str.charAt(e-1) == 'l'))
e--;
if (b > 0 || e < str.length())
str = str.substring(b, e);
try {
java.math.BigInteger bi = null;
if (sign == '-')
bi = new java.math.BigInteger("-" + str, base);
else
bi = new java.math.BigInteger(str, base);
return new PyLong(bi);
} catch (NumberFormatException exc) {
if (this instanceof PyUnicode) {
// TODO: here's a basic issue: do we use the BigInteger constructor
// above, or add an equivalent to CPython's PyUnicode_EncodeDecimal;
// we should note that the current error string does not quite match
// CPython regardless of the codec, that's going to require some more work
throw Py.UnicodeEncodeError("decimal", "codec can't encode character",
0,0, "invalid decimal Unicode string");
}
else {
throw Py.ValueError("invalid literal for long() with base " + base + ": " + string);
}
} catch (StringIndexOutOfBoundsException exc) {
throw Py.ValueError("invalid literal for long() with base " + base + ": " + string);
}
}
private static String padding(int n, char pad) {
char[] chars = new char[n];
for (int i=0; i<n; i++)
chars[i] = pad;
return new String(chars);
}
private static char parse_fillchar(String function, String fillchar) {
if (fillchar == null) { return ' '; }
if (fillchar.length() != 1) {
throw Py.TypeError(function + "() argument 2 must be char, not str");
}
return fillchar.charAt(0);
}
public String ljust(int width) {
return str_ljust(width, null);
}
public String ljust(int width, String padding) {
return str_ljust(width, padding);
}
@ExposedMethod(defaults="null")
final String str_ljust(int width, String fillchar) {
char pad = parse_fillchar("ljust", fillchar);
int n = width-string.length();
if (n <= 0)
return string;
return string+padding(n, pad);
}
public String rjust(int width) {
return str_rjust(width, null);
}
@ExposedMethod(defaults="null")
final String str_rjust(int width, String fillchar) {
char pad = parse_fillchar("rjust", fillchar);
int n = width-string.length();
if (n <= 0)
return string;
return padding(n, pad)+string;
}
public String center(int width) {
return str_center(width, null);
}
@ExposedMethod(defaults="null")
final String str_center(int width, String fillchar) {
char pad = parse_fillchar("center", fillchar);
int n = width-string.length();
if (n <= 0)
return string;
int half = n/2;
if (n%2 > 0 && width%2 > 0)
half += 1;
return padding(half, pad)+string+padding(n-half, pad);
}
public String zfill(int width) {
return str_zfill(width);
}
@ExposedMethod
final String str_zfill(int width) {
String s = string;
int n = s.length();
if (n >= width)
return s;
char[] chars = new char[width];
int nzeros = width-n;
int i=0;
int sStart=0;
if (n > 0) {
char start = s.charAt(0);
if (start == '+' || start == '-') {
chars[0] = start;
i += 1;
nzeros++;
sStart=1;
}
}
for(;i<nzeros; i++) {
chars[i] = '0';
}
s.getChars(sStart, s.length(), chars, i);
return new String(chars);
}
public String expandtabs() {
return str_expandtabs(8);
}
public String expandtabs(int tabsize) {
return str_expandtabs(tabsize);
}
@ExposedMethod(defaults = "8")
final String str_expandtabs(int tabsize) {
String s = string;
StringBuilder buf = new StringBuilder((int)(s.length()*1.5));
char[] chars = s.toCharArray();
int n = chars.length;
int position = 0;
for(int i=0; i<n; i++) {
char c = chars[i];
if (c == '\t') {
int spaces = tabsize-position%tabsize;
position += spaces;
while (spaces-- > 0) {
buf.append(' ');
}
continue;
}
if (c == '\n' || c == '\r') {
position = -1;
}
buf.append(c);
position++;
}
return buf.toString();
}
public String capitalize() {
return str_capitalize();
}
@ExposedMethod
final String str_capitalize() {
if (string.length() == 0)
return string;
String first = string.substring(0,1).toUpperCase();
return first.concat(string.substring(1).toLowerCase());
}
@ExposedMethod(defaults = "null")
final PyString str_replace(PyObject oldPiece, PyObject newPiece, PyObject maxsplit) {
if(!(oldPiece instanceof PyString) || !(newPiece instanceof PyString)) {
throw Py.TypeError("str or unicode required for replace");
}
return replace((PyString)oldPiece, (PyString)newPiece, maxsplit == null ? -1 : maxsplit.asInt());
}
protected PyString replace(PyString oldPiece, PyString newPiece, int maxsplit) {
int len = string.length();
int old_len = oldPiece.string.length();
if (len == 0) {
if (maxsplit == -1 && old_len == 0) {
return createInstance(newPiece.string, true);
}
return createInstance(string, true);
}
if (old_len == 0 && newPiece.string.length() != 0 && maxsplit !=0) {
// old="" and new != "", interleave new piece with each char in original, taking in effect maxsplit
StringBuilder buffer = new StringBuilder();
int i = 0;
buffer.append(newPiece.string);
for (; i < len && (i < maxsplit-1 || maxsplit == -1); i++) {
buffer.append(string.charAt(i));
buffer.append(newPiece.string);
}
buffer.append(string.substring(i));
return createInstance(buffer.toString(), true);
}
if(maxsplit == -1) {
if(old_len == 0) {
maxsplit = len + 1;
} else {
maxsplit = len;
}
}
return newPiece.str_join(splitfields(oldPiece.string, maxsplit));
}
public String join(PyObject seq) {
return str_join(seq).string;
}
@ExposedMethod
final PyString str_join(PyObject obj) {
// Similar to CPython's abstract::PySequence_Fast
PySequence seq;
if (obj instanceof PySequence) {
seq = (PySequence)obj;
} else {
seq = new PyList(obj.__iter__());
}
PyObject item;
int seqlen = seq.__len__();
if (seqlen == 0) {
return createInstance("", true);
}
if (seqlen == 1) {
item = seq.pyget(0);
if (item.getType() == PyUnicode.TYPE ||
(item.getType() == PyString.TYPE && getType() == PyString.TYPE)) {
return (PyString)item;
}
}
boolean needsUnicode = false;
long joinedSize = 0;
StringBuilder buf = new StringBuilder();
for (int i = 0; i < seqlen; i++) {
item = seq.pyget(i);
if (!(item instanceof PyString)) {
throw Py.TypeError(String.format("sequence item %d: expected string, %.80s found",
i, item.getType().fastGetName()));
}
if (item instanceof PyUnicode) {
needsUnicode = true;
}
if (i > 0) {
buf.append(string);
joinedSize += string.length();
}
String itemString = ((PyString)item).string;
buf.append(itemString);
joinedSize += itemString.length();
if (joinedSize > Integer.MAX_VALUE) {
throw Py.OverflowError("join() result is too long for a Python string");
}
}
if (needsUnicode){
return new PyUnicode(buf.toString());
}
return createInstance(buf.toString(), true);
}
public boolean startswith(PyObject prefix) {
return str_startswith(prefix, 0, null);
}
public boolean startswith(PyObject prefix, int offset) {
return str_startswith(prefix, offset, null);
}
public boolean startswith(PyObject prefix, int start, int end) {
return str_startswith(prefix, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"})
final boolean str_startswith(PyObject prefix, int start, PyObject end) {
int[] indices = translateIndices(start, end);
if (prefix instanceof PyString) {
String strPrefix = ((PyString)prefix).string;
if (indices[1] - indices[0] < strPrefix.length())
return false;
return string.startsWith(strPrefix, indices[0]);
} else if (prefix instanceof PyTuple) {
PyObject[] prefixes = ((PyTuple)prefix).getArray();
for (int i = 0 ; i < prefixes.length ; i++) {
if (!(prefixes[i] instanceof PyString))
throw Py.TypeError("expected a character buffer object");
String strPrefix = ((PyString)prefixes[i]).string;
if (indices[1] - indices[0] < strPrefix.length())
continue;
if (string.startsWith(strPrefix, indices[0]))
return true;
}
return false;
} else {
throw Py.TypeError("expected a character buffer object or tuple");
}
}
public boolean endswith(PyObject suffix) {
return str_endswith(suffix, 0, null);
}
public boolean endswith(PyObject suffix, int start) {
return str_endswith(suffix, start, null);
}
public boolean endswith(PyObject suffix, int start, int end) {
return str_endswith(suffix, start, Py.newInteger(end));
}
@ExposedMethod(defaults = {"0", "null"})
final boolean str_endswith(PyObject suffix, int start, PyObject end) {
int[] indices = translateIndices(start, end);
String substr = string.substring(indices[0], indices[1]);
if (suffix instanceof PyString) {
return substr.endsWith(((PyString)suffix).string);
} else if (suffix instanceof PyTuple) {
PyObject[] suffixes = ((PyTuple)suffix).getArray();
for (int i = 0 ; i < suffixes.length ; i++) {
if (!(suffixes[i] instanceof PyString))
throw Py.TypeError("expected a character buffer object");
if (substr.endsWith(((PyString)suffixes[i]).string))
return true;
}
return false;
} else {
throw Py.TypeError("expected a character buffer object or tuple");
}
}
/**
* Turns the possibly negative Python slice start and end into valid indices
* into this string.
*
* @return a 2 element array of indices into this string describing a
* substring from [0] to [1]. [0] <= [1], [0] >= 0 and [1] <=
* string.length()
*
*/
protected int[] translateIndices(int start, PyObject end) {
int iEnd;
if(end == null) {
iEnd = string.length();
} else {
iEnd = end.asInt();
}
int n = string.length();
if(iEnd < 0) {
iEnd = n + iEnd;
if(iEnd < 0) {
iEnd = 0;
}
} else if(iEnd > n) {
iEnd = n;
}
if(start < 0) {
start = n + start;
if(start < 0) {
start = 0;
}
}
if(start > iEnd) {
start = iEnd;
}
return new int[] {start, iEnd};
}
public String translate(String table) {
return str_translate(table, null);
}
public String translate(String table, String deletechars) {
return str_translate(table, deletechars);
}
@ExposedMethod(defaults = "null")
final String str_translate(String table, String deletechars) {
if (table.length() != 256)
throw Py.ValueError(
"translation table must be 256 characters long");
StringBuilder buf = new StringBuilder(string.length());
for (int i=0; i < string.length(); i++) {
char c = string.charAt(i);
if (deletechars != null && deletechars.indexOf(c) >= 0)
continue;
try {
buf.append(table.charAt(c));
}
catch (IndexOutOfBoundsException e) {
throw Py.TypeError(
"translate() only works for 8-bit character strings");
}
}
return buf.toString();
}
//XXX: is this needed?
public String translate(PyObject table) {
StringBuilder v = new StringBuilder(string.length());
for (int i=0; i < string.length(); i++) {
char ch = string.charAt(i);
PyObject w = Py.newInteger(ch);
PyObject x = table.__finditem__(w);
if (x == null) {
/* No mapping found: default to 1-1 mapping */
v.append(ch);
continue;
}
/* Apply mapping */
if (x instanceof PyInteger) {
int value = ((PyInteger) x).getValue();
v.append((char) value);
} else if (x == Py.None) {
;
} else if (x instanceof PyString) {
if (x.__len__() != 1) {
/* 1-n mapping */
throw new PyException(Py.NotImplementedError,
"1-n mappings are currently not implemented");
}
v.append(x.toString());
}
else {
/* wrong return value */
throw Py.TypeError(
"character mapping must return integer, " +
"None or unicode");
}
}
return v.toString();
}
public boolean islower() {
return str_islower();
}
@ExposedMethod
final boolean str_islower() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isLowerCase(string.charAt(0));
boolean cased = false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (Character.isUpperCase(ch) || Character.isTitleCase(ch))
return false;
else if (!cased && Character.isLowerCase(ch))
cased = true;
}
return cased;
}
public boolean isupper() {
return str_isupper();
}
@ExposedMethod
final boolean str_isupper() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isUpperCase(string.charAt(0));
boolean cased = false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (Character.isLowerCase(ch) || Character.isTitleCase(ch))
return false;
else if (!cased && Character.isUpperCase(ch))
cased = true;
}
return cased;
}
public boolean isalpha() {
return str_isalpha();
}
@ExposedMethod
final boolean str_isalpha() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isLetter(string.charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (!Character.isLetter(ch))
return false;
}
return true;
}
public boolean isalnum() {
return str_isalnum();
}
@ExposedMethod
final boolean str_isalnum() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1)
return _isalnum(string.charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (!_isalnum(ch))
return false;
}
return true;
}
private boolean _isalnum(char ch) {
// This can ever be entirely compatible with CPython. In CPython
// The type is not used, the numeric property is determined from
// the presense of digit, decimal or numeric fields. These fields
// are not available in exactly the same way in java.
return Character.isLetterOrDigit(ch) ||
Character.getType(ch) == Character.LETTER_NUMBER;
}
public boolean isdecimal() {
return str_isdecimal();
}
@ExposedMethod
final boolean str_isdecimal() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1) {
char ch = string.charAt(0);
return _isdecimal(ch);
}
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (!_isdecimal(ch))
return false;
}
return true;
}
private boolean _isdecimal(char ch) {
// See the comment in _isalnum. Here it is even worse.
return Character.getType(ch) == Character.DECIMAL_DIGIT_NUMBER;
}
public boolean isdigit() {
return str_isdigit();
}
@ExposedMethod
final boolean str_isdigit() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isDigit(string.charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (!Character.isDigit(ch))
return false;
}
return true;
}
public boolean isnumeric() {
return str_isnumeric();
}
@ExposedMethod
final boolean str_isnumeric() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1)
return _isnumeric(string.charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (!_isnumeric(ch))
return false;
}
return true;
}
private boolean _isnumeric(char ch) {
int type = Character.getType(ch);
return type == Character.DECIMAL_DIGIT_NUMBER ||
type == Character.LETTER_NUMBER ||
type == Character.OTHER_NUMBER;
}
public boolean istitle() {
return str_istitle();
}
@ExposedMethod
final boolean str_istitle() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isTitleCase(string.charAt(0)) ||
Character.isUpperCase(string.charAt(0));
boolean cased = false;
boolean previous_is_cased = false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (Character.isUpperCase(ch) || Character.isTitleCase(ch)) {
if (previous_is_cased)
return false;
previous_is_cased = true;
cased = true;
}
else if (Character.isLowerCase(ch)) {
if (!previous_is_cased)
return false;
previous_is_cased = true;
cased = true;
}
else
previous_is_cased = false;
}
return cased;
}
public boolean isspace() {
return str_isspace();
}
@ExposedMethod
final boolean str_isspace() {
int n = string.length();
/* Shortcut for single character strings */
if (n == 1)
return Character.isWhitespace(string.charAt(0));
if (n == 0)
return false;
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (!Character.isWhitespace(ch))
return false;
}
return true;
}
public boolean isunicode() {
return str_isunicode();
}
@ExposedMethod
final boolean str_isunicode() {
int n = string.length();
for (int i = 0; i < n; i++) {
char ch = string.charAt(i);
if (ch > 255)
return true;
}
return false;
}
public String encode() {
return str_encode(null, null);
}
public String encode(String encoding) {
return str_encode(encoding, null);
}
public String encode(String encoding, String errors) {
return str_encode(encoding, errors);
}
@ExposedMethod(defaults = {"null", "null"})
final String str_encode(String encoding, String errors) {
return codecs.encode(this, encoding, errors);
}
public PyObject decode() {
return str_decode(null, null);
}
public PyObject decode(String encoding) {
return str_decode(encoding, null);
}
public PyObject decode(String encoding, String errors) {
return str_decode(encoding, errors);
}
@ExposedMethod(defaults = {"null", "null"})
final PyObject str_decode(String encoding, String errors) {
return codecs.decode(this, encoding, errors);
}
/* arguments' conversion helper */
public String asString(int index) throws PyObject.ConversionException {
return string;
}
@Override
public String asString() {
return string;
}
public String asName(int index) throws PyObject.ConversionException {
return internedString();
}
protected String unsupportedopMessage(String op, PyObject o2) {
if (op.equals("+")) {
return "cannot concatenate ''{1}'' and ''{2}'' objects";
}
return super.unsupportedopMessage(op, o2);
}
}
final class StringFormatter
{
int index;
String format;
StringBuilder buffer;
boolean negative;
int precision;
int argIndex;
PyObject args;
boolean unicodeCoercion;
final char pop() {
try {
return format.charAt(index++);
} catch (StringIndexOutOfBoundsException e) {
throw Py.ValueError("incomplete format");
}
}
final char peek() {
return format.charAt(index);
}
final void push() {
index--;
}
public StringFormatter(String format) {
this(format, false);
}
public StringFormatter(String format, boolean unicodeCoercion) {
index = 0;
this.format = format;
this.unicodeCoercion = unicodeCoercion;
buffer = new StringBuilder(format.length()+100);
}
PyObject getarg() {
PyObject ret = null;
switch(argIndex) {
// special index indicating a mapping
case -3:
return args;
// special index indicating a single item that has already been
// used
case -2:
break;
// special index indicating a single item that has not yet been
// used
case -1:
argIndex=-2;
return args;
default:
ret = args.__finditem__(argIndex++);
break;
}
if (ret == null)
throw Py.TypeError("not enough arguments for format string");
return ret;
}
int getNumber() {
char c = pop();
if (c == '*') {
PyObject o = getarg();
if (o instanceof PyInteger)
return ((PyInteger)o).getValue();
throw Py.TypeError("* wants int");
} else {
if (Character.isDigit(c)) {
int numStart = index-1;
while (Character.isDigit(c = pop()))
;
index -= 1;
Integer i = Integer.valueOf(
format.substring(numStart, index));
return i.intValue();
}
index -= 1;
return 0;
}
}
private void checkPrecision(String type) {
if(precision > 250) {
// A magic number. Larger than in CPython.
throw Py.OverflowError("formatted " + type + " is too long (precision too long?)");
}
}
private String formatLong(PyObject arg, char type, boolean altFlag) {
PyString argAsString;
switch (type) {
case 'o':
argAsString = arg.__oct__();
break;
case 'x':
case 'X':
argAsString = arg.__hex__();
break;
default:
argAsString = arg.__str__();
break;
}
checkPrecision("long");
String s = argAsString.toString();
int end = s.length();
int ptr = 0;
int numnondigits = 0;
if (type == 'x' || type == 'X')
numnondigits = 2;
if (s.endsWith("L"))
end--;
negative = s.charAt(0) == '-';
if (negative) {
ptr++;
}
int numdigits = end - numnondigits - ptr;
if (!altFlag) {
switch (type) {
case 'o' :
if (numdigits > 1) {
++ptr;
--numdigits;
}
break;
case 'x' :
case 'X' :
ptr += 2;
numnondigits -= 2;
break;
}
}
if (precision > numdigits) {
StringBuilder buf = new StringBuilder();
for (int i = 0; i < numnondigits; ++i)
buf.append(s.charAt(ptr++));
for (int i = 0; i < precision - numdigits; i++)
buf.append('0');
for (int i = 0; i < numdigits; i++)
buf.append(s.charAt(ptr++));
s = buf.toString();
} else if (end < s.length() || ptr > 0)
s = s.substring(ptr, end);
switch (type) {
case 'X' :
s = s.toUpperCase();
break;
}
return s;
}
/**
* Formats arg as an integer, with the specified radix
*
* type and altFlag are needed to be passed to {@link #formatLong(PyObject, char, boolean)}
* in case the result of <code>arg.__int__()</code> is a PyLong.
*/
private String formatInteger(PyObject arg, int radix, boolean unsigned, char type, boolean altFlag) {
PyObject argAsInt;
if (arg instanceof PyInteger || arg instanceof PyLong) {
argAsInt = arg;
} else {
// use __int__ to get an int (or long)
if (arg instanceof PyFloat) {
// safe to call __int__:
argAsInt = arg.__int__();
} else {
// Same case noted on formatFloatDecimal:
// We can't simply call arg.__int__() because PyString implements
// it without exposing it to python (i.e, str instances has no
// __int__ attribute). So, we would support strings as arguments
// for %d format, which is forbidden by CPython tests (on
// test_format.py).
try {
argAsInt = arg.__getattr__("__int__").__call__();
} catch (PyException e) {
// XXX: Swallow customs AttributeError throws from __float__ methods
// No better alternative for the moment
if (Py.matchException(e, Py.AttributeError)) {
throw Py.TypeError("int argument required");
}
throw e;
}
}
}
if (argAsInt instanceof PyInteger) {
return formatInteger(((PyInteger)argAsInt).getValue(), radix, unsigned);
} else { // must be a PyLong (as per __int__ contract)
return formatLong(argAsInt, type, altFlag);
}
}
private String formatInteger(long v, int radix, boolean unsigned) {
checkPrecision("integer");
if (unsigned) {
if (v < 0)
v = 0x100000000l + v;
} else {
if (v < 0) {
negative = true;
v = -v;
}
}
String s = Long.toString(v, radix);
while (s.length() < precision) {
s = "0"+s;
}
return s;
}
private String formatFloatDecimal(PyObject arg, boolean truncate) {
PyFloat argAsFloat;
if (arg instanceof PyFloat) {
// Fast path
argAsFloat = (PyFloat)arg;
} else {
// Use __float__
if (arg instanceof PyInteger || arg instanceof PyLong) {
// Typical cases, safe to call __float__:
argAsFloat = arg.__float__();
} else {
try {
// We can't simply call arg.__float__() because PyString implements
// it without exposing it to python (i.e, str instances has no
// __float__ attribute). So, we would support strings as arguments
// for %g format, which is forbidden by CPython tests (on
// test_format.py).
argAsFloat = (PyFloat)arg.__getattr__("__float__").__call__();
} catch (PyException e) {
// XXX: Swallow customs AttributeError throws from __float__ methods
// No better alternative for the moment
if (Py.matchException(e, Py.AttributeError)) {
throw Py.TypeError("float argument required");
}
throw e;
}
}
}
return formatFloatDecimal(argAsFloat.getValue(), truncate);
}
private String formatFloatDecimal(double v, boolean truncate) {
checkPrecision("decimal");
java.text.NumberFormat format = java.text.NumberFormat.getInstance(
java.util.Locale.US);
int prec = precision;
if (prec == -1)
prec = 6;
if (v < 0) {
v = -v;
negative = true;
}
format.setMaximumFractionDigits(prec);
format.setMinimumFractionDigits(truncate ? 0 : prec);
format.setGroupingUsed(false);
String ret = format.format(v);
// System.err.println("formatFloat: "+v+", prec="+prec+", ret="+ret);
// if (ret.indexOf('.') == -1) {
// return ret+'.';
// }
return ret;
}
private String formatFloatExponential(PyObject arg, char e,
boolean truncate)
{
StringBuilder buf = new StringBuilder();
double v = arg.__float__().getValue();
boolean isNegative = false;
if (v < 0) {
v = -v;
isNegative = true;
}
double power = 0.0;
if (v > 0)
power = ExtraMath.closeFloor(Math.log10(v));
//System.err.println("formatExp: "+v+", "+power);
int savePrecision = precision;
precision = 2;
String exp = formatInteger((long)power, 10, false);
if (negative) {
negative = false;
exp = '-'+exp;
}
else {
exp = '+' + exp;
}
precision = savePrecision;
double base = v/Math.pow(10, power);
buf.append(formatFloatDecimal(base, truncate));
buf.append(e);
buf.append(exp);
negative = isNegative;
return buf.toString();
}
public PyString format(PyObject args) {
PyObject dict = null;
this.args = args;
boolean needUnicode = unicodeCoercion;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
(!(args instanceof PySequence) &&
args.__findattr__("__getitem__") != null))
{
dict = args;
argIndex = -3;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
//System.out.println("( found");
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')')
parens--;
else if (c == '(')
parens++;
}
String tmp = format.substring(keyStart, index-1);
this.args = dict.__getitem__(new PyString(tmp));
//System.out.println("args: "+args+", "+argIndex);
} else {
push();
}
while (true) {
switch (c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
if (width < 0) {
width = -width;
ljustFlag = true;
}
c = pop();
if (c == '.') {
precision = getNumber();
if (precision < -1)
precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
//System.out.println("args: "+args+", "+argIndex+", "+arg);
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag)
fill = '0';
else
fill = ' ';
switch(c) {
case 's':
case 'r':
fill = ' ';
if (arg instanceof PyUnicode) {
needUnicode = true;
}
if (c == 's')
if (needUnicode)
string = arg.__unicode__().toString();
else
string = arg.__str__().toString();
else
string = arg.__repr__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else
string = formatInteger(arg, 10, false, c, altFlag);
break;
case 'u':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat)
string = formatInteger(arg, 10, false, c, altFlag);
else throw Py.TypeError("int argument required");
break;
case 'o':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 8, false, c, altFlag);
if (altFlag && string.charAt(0) != '0') {
string = "0" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'x':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toLowerCase();
if (altFlag) {
string = "0x" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'X':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toUpperCase();
if (altFlag) {
string = "0X" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
break;
case 'f':
case 'F':
string = formatFloatDecimal(arg, false);
// if (altFlag && string.indexOf('.') == -1)
// string += '.';
break;
case 'g':
case 'G':
int origPrecision = precision;
if (precision == -1) {
precision = 6;
}
double v = arg.__float__().getValue();
int exponent = (int)ExtraMath.closeFloor(Math.log10(Math.abs(v == 0 ? 1 : v)));
if (v == Double.POSITIVE_INFINITY) {
string = "inf";
} else if (v == Double.NEGATIVE_INFINITY) {
string = "-inf";
} else if (exponent >= -4 && exponent < precision) {
precision -= exponent + 1;
string = formatFloatDecimal(arg, !altFlag);
// XXX: this block may be unnecessary now
if (altFlag && string.indexOf('.') == -1) {
int zpad = origPrecision - string.length();
string += '.';
if (zpad > 0) {
char zeros[] = new char[zpad];
for (int ci=0; ci<zpad; zeros[ci++] = '0')
;
string += new String(zeros);
}
}
} else {
+ // Exponential precision is the number of digits after the decimal
+ // point, whereas 'g' precision is the number of significant digits --
+ // and expontential always provides one significant digit before the
+ // decimal point
+ precision--;
string = formatFloatExponential(arg, (char)(c-2), !altFlag);
}
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1) {
throw Py.TypeError("%c requires int or char");
}
if (arg instanceof PyUnicode) {
needUnicode = true;
}
break;
}
int val;
try {
val = ((PyInteger)arg.__int__()).getValue();
} catch (PyException e){
if (Py.matchException(e, Py.AttributeError)) {
throw Py.TypeError("%c requires int or char");
}
throw e;
}
if (val < 0) {
throw Py.OverflowError("unsigned byte integer is less than minimum");
} else if (val > 255) {
throw Py.OverflowError("unsigned byte integer is greater than maximum");
}
string = new Character((char)val).toString();
break;
default:
throw Py.ValueError("unsupported format character '" +
codecs.encode(Py.newString(c), null, "replace") +
"' (0x" + Integer.toHexString(c) + ") at index " +
(index-1));
}
int length = string.length();
int skip = 0;
String signString = null;
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
} else if (blankFlag) {
signString = " ";
}
}
if (width < length)
width = length;
if (signString != null) {
if (fill != ' ')
buffer.append(signString);
if (width > length)
width--;
}
if (altFlag && (c == 'x' || c == 'X')) {
if (fill != ' ') {
buffer.append('0');
buffer.append(c);
skip += 2;
}
width -= 2;
if (width < 0)
width = 0;
length -= 2;
}
if (width > length && !ljustFlag) {
do {
buffer.append(fill);
} while (--width > length);
}
if (fill == ' ') {
if (signString != null)
buffer.append(signString);
if (altFlag && (c == 'x' || c == 'X')) {
buffer.append('0');
buffer.append(c);
skip += 2;
}
}
if (skip > 0)
buffer.append(string.substring(skip));
else
buffer.append(string);
while (--width >= length) {
buffer.append(' ');
}
}
if (argIndex == -1 ||
(argIndex >= 0 && args.__finditem__(argIndex) != null))
{
throw Py.TypeError("not all arguments converted during string formatting");
}
if (needUnicode) {
return new PyUnicode(buffer);
}
return new PyString(buffer);
}
}
| true | true | public PyString format(PyObject args) {
PyObject dict = null;
this.args = args;
boolean needUnicode = unicodeCoercion;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
(!(args instanceof PySequence) &&
args.__findattr__("__getitem__") != null))
{
dict = args;
argIndex = -3;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
//System.out.println("( found");
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')')
parens--;
else if (c == '(')
parens++;
}
String tmp = format.substring(keyStart, index-1);
this.args = dict.__getitem__(new PyString(tmp));
//System.out.println("args: "+args+", "+argIndex);
} else {
push();
}
while (true) {
switch (c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
if (width < 0) {
width = -width;
ljustFlag = true;
}
c = pop();
if (c == '.') {
precision = getNumber();
if (precision < -1)
precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
//System.out.println("args: "+args+", "+argIndex+", "+arg);
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag)
fill = '0';
else
fill = ' ';
switch(c) {
case 's':
case 'r':
fill = ' ';
if (arg instanceof PyUnicode) {
needUnicode = true;
}
if (c == 's')
if (needUnicode)
string = arg.__unicode__().toString();
else
string = arg.__str__().toString();
else
string = arg.__repr__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else
string = formatInteger(arg, 10, false, c, altFlag);
break;
case 'u':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat)
string = formatInteger(arg, 10, false, c, altFlag);
else throw Py.TypeError("int argument required");
break;
case 'o':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 8, false, c, altFlag);
if (altFlag && string.charAt(0) != '0') {
string = "0" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'x':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toLowerCase();
if (altFlag) {
string = "0x" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'X':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toUpperCase();
if (altFlag) {
string = "0X" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
break;
case 'f':
case 'F':
string = formatFloatDecimal(arg, false);
// if (altFlag && string.indexOf('.') == -1)
// string += '.';
break;
case 'g':
case 'G':
int origPrecision = precision;
if (precision == -1) {
precision = 6;
}
double v = arg.__float__().getValue();
int exponent = (int)ExtraMath.closeFloor(Math.log10(Math.abs(v == 0 ? 1 : v)));
if (v == Double.POSITIVE_INFINITY) {
string = "inf";
} else if (v == Double.NEGATIVE_INFINITY) {
string = "-inf";
} else if (exponent >= -4 && exponent < precision) {
precision -= exponent + 1;
string = formatFloatDecimal(arg, !altFlag);
// XXX: this block may be unnecessary now
if (altFlag && string.indexOf('.') == -1) {
int zpad = origPrecision - string.length();
string += '.';
if (zpad > 0) {
char zeros[] = new char[zpad];
for (int ci=0; ci<zpad; zeros[ci++] = '0')
;
string += new String(zeros);
}
}
} else {
string = formatFloatExponential(arg, (char)(c-2), !altFlag);
}
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1) {
throw Py.TypeError("%c requires int or char");
}
if (arg instanceof PyUnicode) {
needUnicode = true;
}
break;
}
int val;
try {
val = ((PyInteger)arg.__int__()).getValue();
} catch (PyException e){
if (Py.matchException(e, Py.AttributeError)) {
throw Py.TypeError("%c requires int or char");
}
throw e;
}
if (val < 0) {
throw Py.OverflowError("unsigned byte integer is less than minimum");
} else if (val > 255) {
throw Py.OverflowError("unsigned byte integer is greater than maximum");
}
string = new Character((char)val).toString();
break;
default:
throw Py.ValueError("unsupported format character '" +
codecs.encode(Py.newString(c), null, "replace") +
"' (0x" + Integer.toHexString(c) + ") at index " +
(index-1));
}
int length = string.length();
int skip = 0;
String signString = null;
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
} else if (blankFlag) {
signString = " ";
}
}
if (width < length)
width = length;
if (signString != null) {
if (fill != ' ')
buffer.append(signString);
if (width > length)
width--;
}
if (altFlag && (c == 'x' || c == 'X')) {
if (fill != ' ') {
buffer.append('0');
buffer.append(c);
skip += 2;
}
width -= 2;
if (width < 0)
width = 0;
length -= 2;
}
if (width > length && !ljustFlag) {
do {
buffer.append(fill);
} while (--width > length);
}
if (fill == ' ') {
if (signString != null)
buffer.append(signString);
if (altFlag && (c == 'x' || c == 'X')) {
buffer.append('0');
buffer.append(c);
skip += 2;
}
}
if (skip > 0)
buffer.append(string.substring(skip));
else
buffer.append(string);
while (--width >= length) {
buffer.append(' ');
}
}
if (argIndex == -1 ||
(argIndex >= 0 && args.__finditem__(argIndex) != null))
{
throw Py.TypeError("not all arguments converted during string formatting");
}
if (needUnicode) {
return new PyUnicode(buffer);
}
return new PyString(buffer);
}
| public PyString format(PyObject args) {
PyObject dict = null;
this.args = args;
boolean needUnicode = unicodeCoercion;
if (args instanceof PyTuple) {
argIndex = 0;
} else {
// special index indicating a single item rather than a tuple
argIndex = -1;
if (args instanceof PyDictionary ||
args instanceof PyStringMap ||
(!(args instanceof PySequence) &&
args.__findattr__("__getitem__") != null))
{
dict = args;
argIndex = -3;
}
}
while (index < format.length()) {
boolean ljustFlag=false;
boolean signFlag=false;
boolean blankFlag=false;
boolean altFlag=false;
boolean zeroFlag=false;
int width = -1;
precision = -1;
char c = pop();
if (c != '%') {
buffer.append(c);
continue;
}
c = pop();
if (c == '(') {
//System.out.println("( found");
if (dict == null)
throw Py.TypeError("format requires a mapping");
int parens = 1;
int keyStart = index;
while (parens > 0) {
c = pop();
if (c == ')')
parens--;
else if (c == '(')
parens++;
}
String tmp = format.substring(keyStart, index-1);
this.args = dict.__getitem__(new PyString(tmp));
//System.out.println("args: "+args+", "+argIndex);
} else {
push();
}
while (true) {
switch (c = pop()) {
case '-': ljustFlag=true; continue;
case '+': signFlag=true; continue;
case ' ': blankFlag=true; continue;
case '#': altFlag=true; continue;
case '0': zeroFlag=true; continue;
}
break;
}
push();
width = getNumber();
if (width < 0) {
width = -width;
ljustFlag = true;
}
c = pop();
if (c == '.') {
precision = getNumber();
if (precision < -1)
precision = 0;
c = pop();
}
if (c == 'h' || c == 'l' || c == 'L') {
c = pop();
}
if (c == '%') {
buffer.append(c);
continue;
}
PyObject arg = getarg();
//System.out.println("args: "+args+", "+argIndex+", "+arg);
char fill = ' ';
String string=null;
negative = false;
if (zeroFlag)
fill = '0';
else
fill = ' ';
switch(c) {
case 's':
case 'r':
fill = ' ';
if (arg instanceof PyUnicode) {
needUnicode = true;
}
if (c == 's')
if (needUnicode)
string = arg.__unicode__().toString();
else
string = arg.__str__().toString();
else
string = arg.__repr__().toString();
if (precision >= 0 && string.length() > precision) {
string = string.substring(0, precision);
}
break;
case 'i':
case 'd':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else
string = formatInteger(arg, 10, false, c, altFlag);
break;
case 'u':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat)
string = formatInteger(arg, 10, false, c, altFlag);
else throw Py.TypeError("int argument required");
break;
case 'o':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 8, false, c, altFlag);
if (altFlag && string.charAt(0) != '0') {
string = "0" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'x':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toLowerCase();
if (altFlag) {
string = "0x" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'X':
if (arg instanceof PyLong)
string = formatLong(arg, c, altFlag);
else if (arg instanceof PyInteger || arg instanceof PyFloat) {
string = formatInteger(arg, 16, false, c, altFlag);
string = string.toUpperCase();
if (altFlag) {
string = "0X" + string;
}
}
else throw Py.TypeError("int argument required");
break;
case 'e':
case 'E':
string = formatFloatExponential(arg, c, false);
break;
case 'f':
case 'F':
string = formatFloatDecimal(arg, false);
// if (altFlag && string.indexOf('.') == -1)
// string += '.';
break;
case 'g':
case 'G':
int origPrecision = precision;
if (precision == -1) {
precision = 6;
}
double v = arg.__float__().getValue();
int exponent = (int)ExtraMath.closeFloor(Math.log10(Math.abs(v == 0 ? 1 : v)));
if (v == Double.POSITIVE_INFINITY) {
string = "inf";
} else if (v == Double.NEGATIVE_INFINITY) {
string = "-inf";
} else if (exponent >= -4 && exponent < precision) {
precision -= exponent + 1;
string = formatFloatDecimal(arg, !altFlag);
// XXX: this block may be unnecessary now
if (altFlag && string.indexOf('.') == -1) {
int zpad = origPrecision - string.length();
string += '.';
if (zpad > 0) {
char zeros[] = new char[zpad];
for (int ci=0; ci<zpad; zeros[ci++] = '0')
;
string += new String(zeros);
}
}
} else {
// Exponential precision is the number of digits after the decimal
// point, whereas 'g' precision is the number of significant digits --
// and expontential always provides one significant digit before the
// decimal point
precision--;
string = formatFloatExponential(arg, (char)(c-2), !altFlag);
}
break;
case 'c':
fill = ' ';
if (arg instanceof PyString) {
string = ((PyString)arg).toString();
if (string.length() != 1) {
throw Py.TypeError("%c requires int or char");
}
if (arg instanceof PyUnicode) {
needUnicode = true;
}
break;
}
int val;
try {
val = ((PyInteger)arg.__int__()).getValue();
} catch (PyException e){
if (Py.matchException(e, Py.AttributeError)) {
throw Py.TypeError("%c requires int or char");
}
throw e;
}
if (val < 0) {
throw Py.OverflowError("unsigned byte integer is less than minimum");
} else if (val > 255) {
throw Py.OverflowError("unsigned byte integer is greater than maximum");
}
string = new Character((char)val).toString();
break;
default:
throw Py.ValueError("unsupported format character '" +
codecs.encode(Py.newString(c), null, "replace") +
"' (0x" + Integer.toHexString(c) + ") at index " +
(index-1));
}
int length = string.length();
int skip = 0;
String signString = null;
if (negative) {
signString = "-";
} else {
if (signFlag) {
signString = "+";
} else if (blankFlag) {
signString = " ";
}
}
if (width < length)
width = length;
if (signString != null) {
if (fill != ' ')
buffer.append(signString);
if (width > length)
width--;
}
if (altFlag && (c == 'x' || c == 'X')) {
if (fill != ' ') {
buffer.append('0');
buffer.append(c);
skip += 2;
}
width -= 2;
if (width < 0)
width = 0;
length -= 2;
}
if (width > length && !ljustFlag) {
do {
buffer.append(fill);
} while (--width > length);
}
if (fill == ' ') {
if (signString != null)
buffer.append(signString);
if (altFlag && (c == 'x' || c == 'X')) {
buffer.append('0');
buffer.append(c);
skip += 2;
}
}
if (skip > 0)
buffer.append(string.substring(skip));
else
buffer.append(string);
while (--width >= length) {
buffer.append(' ');
}
}
if (argIndex == -1 ||
(argIndex >= 0 && args.__finditem__(argIndex) != null))
{
throw Py.TypeError("not all arguments converted during string formatting");
}
if (needUnicode) {
return new PyUnicode(buffer);
}
return new PyString(buffer);
}
|
diff --git a/src/main/java/com/ning/metrics/eventtracker/ScribeCollectorFactory.java b/src/main/java/com/ning/metrics/eventtracker/ScribeCollectorFactory.java
index cec7c2c..ce9ea01 100644
--- a/src/main/java/com/ning/metrics/eventtracker/ScribeCollectorFactory.java
+++ b/src/main/java/com/ning/metrics/eventtracker/ScribeCollectorFactory.java
@@ -1,129 +1,129 @@
/*
* Copyright 2010 Ning, Inc.
*
* Ning licenses this file to you under the Apache License, version 2.0
* (the "License"); you may not use this file except in compliance with the
* License. You may obtain a copy of the License at:
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
* WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
* License for the specific language governing permissions and limitations
* under the License.
*/
package com.ning.metrics.eventtracker;
import com.ning.metrics.serialization.event.Event;
import com.ning.metrics.serialization.util.FixedManagedJmxExport;
import com.ning.metrics.serialization.writer.DiskSpoolEventWriter;
import com.ning.metrics.serialization.writer.EventHandler;
import com.ning.metrics.serialization.writer.SyncType;
import com.ning.metrics.serialization.writer.ThresholdEventWriter;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledThreadPoolExecutor;
public class ScribeCollectorFactory
{
private static CollectorController singletonController;
private final CollectorController controller;
private static ScribeSender eventSender;
/**
* Initialize the Scribe controller without Guice
*
* @param scribeHost Scribe hostname or IP
* @param scribePort Scribe port
* @param scribeRefreshRate Number of messages to send to Scribe before refreshing the connection
* @param spoolDirectoryName Directory name for the spool queue
* @param isFlushEnabled Whether to send events to remote agent
* @param flushIntervalInSeconds Delay between flushes (in seconds) to remote agent
* @param syncType type of Sync (NONE, FLUSH or SYNC)
* @param rateWindowSizeMinutes event rate window size
* @param flushEventQueueSize Maximum queue size in the temporary spooling area
* @param refreshDelayInSeconds Number of seconds before promoting events from tmp to final spool queue
* @return Scribe controller
* @throws java.io.IOException if an Exception occurs while trying to create the directory
* @see com.ning.metrics.eventtracker.CollectorController
*/
@SuppressWarnings("unused")
public static synchronized CollectorController createScribeController(
String scribeHost,
int scribePort,
int scribeRefreshRate,
String spoolDirectoryName,
boolean isFlushEnabled,
long flushIntervalInSeconds,
String syncType,
int syncBatchSize,
int rateWindowSizeMinutes,
long flushEventQueueSize,
long refreshDelayInSeconds
) throws IOException
{
if (singletonController == null) {
singletonController = new ScribeCollectorFactory(scribeHost, scribePort, scribeRefreshRate, spoolDirectoryName, isFlushEnabled, flushIntervalInSeconds, syncType, syncBatchSize, rateWindowSizeMinutes, flushEventQueueSize, refreshDelayInSeconds).get();
}
return singletonController;
}
ScribeCollectorFactory(
String scribeHost,
int scribePort,
int scribeRefreshRate,
String spoolDirectoryName,
boolean isFlushEnabled,
long flushIntervalInSeconds,
String syncType,
int syncBatchSize,
int rateWindowSizeMinutes,
long flushEventQueueSize,
long refreshDelayInSeconds
) throws IOException
{
eventSender = new ScribeSender(new ScribeClientImpl(scribeHost, scribePort), scribeRefreshRate);
- FixedManagedJmxExport.export("eventtracker:name=ScribeSender", eventSender);
+ FixedManagedJmxExport.export("com.ning.metrics.eventtracker:name=ScribeSender", eventSender);
eventSender.createConnection();
DiskSpoolEventWriter eventWriter = new DiskSpoolEventWriter(new EventHandler()
{
@Override
public void handle(ObjectInputStream objectInputStream) throws ClassNotFoundException, IOException
{
while (objectInputStream.read() != -1) {
Event event = (Event) objectInputStream.readObject();
eventSender.send(event);
}
objectInputStream.close();
}
@Override
public void rollback() throws IOException
{
// no-op
}
}, spoolDirectoryName, isFlushEnabled, flushIntervalInSeconds, new ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory()), SyncType.valueOf(syncType), syncBatchSize, rateWindowSizeMinutes);
ThresholdEventWriter thresholdEventWriter = new ThresholdEventWriter(eventWriter, flushEventQueueSize, refreshDelayInSeconds);
controller = new CollectorController(thresholdEventWriter);
FixedManagedJmxExport.export("eventtracker:name=CollectorController", controller);
}
private CollectorController get()
{
return controller;
}
public static void shutdown()
{
eventSender.shutdown();
}
}
| true | true | ScribeCollectorFactory(
String scribeHost,
int scribePort,
int scribeRefreshRate,
String spoolDirectoryName,
boolean isFlushEnabled,
long flushIntervalInSeconds,
String syncType,
int syncBatchSize,
int rateWindowSizeMinutes,
long flushEventQueueSize,
long refreshDelayInSeconds
) throws IOException
{
eventSender = new ScribeSender(new ScribeClientImpl(scribeHost, scribePort), scribeRefreshRate);
FixedManagedJmxExport.export("eventtracker:name=ScribeSender", eventSender);
eventSender.createConnection();
DiskSpoolEventWriter eventWriter = new DiskSpoolEventWriter(new EventHandler()
{
@Override
public void handle(ObjectInputStream objectInputStream) throws ClassNotFoundException, IOException
{
while (objectInputStream.read() != -1) {
Event event = (Event) objectInputStream.readObject();
eventSender.send(event);
}
objectInputStream.close();
}
@Override
public void rollback() throws IOException
{
// no-op
}
}, spoolDirectoryName, isFlushEnabled, flushIntervalInSeconds, new ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory()), SyncType.valueOf(syncType), syncBatchSize, rateWindowSizeMinutes);
ThresholdEventWriter thresholdEventWriter = new ThresholdEventWriter(eventWriter, flushEventQueueSize, refreshDelayInSeconds);
controller = new CollectorController(thresholdEventWriter);
FixedManagedJmxExport.export("eventtracker:name=CollectorController", controller);
}
| ScribeCollectorFactory(
String scribeHost,
int scribePort,
int scribeRefreshRate,
String spoolDirectoryName,
boolean isFlushEnabled,
long flushIntervalInSeconds,
String syncType,
int syncBatchSize,
int rateWindowSizeMinutes,
long flushEventQueueSize,
long refreshDelayInSeconds
) throws IOException
{
eventSender = new ScribeSender(new ScribeClientImpl(scribeHost, scribePort), scribeRefreshRate);
FixedManagedJmxExport.export("com.ning.metrics.eventtracker:name=ScribeSender", eventSender);
eventSender.createConnection();
DiskSpoolEventWriter eventWriter = new DiskSpoolEventWriter(new EventHandler()
{
@Override
public void handle(ObjectInputStream objectInputStream) throws ClassNotFoundException, IOException
{
while (objectInputStream.read() != -1) {
Event event = (Event) objectInputStream.readObject();
eventSender.send(event);
}
objectInputStream.close();
}
@Override
public void rollback() throws IOException
{
// no-op
}
}, spoolDirectoryName, isFlushEnabled, flushIntervalInSeconds, new ScheduledThreadPoolExecutor(1, Executors.defaultThreadFactory()), SyncType.valueOf(syncType), syncBatchSize, rateWindowSizeMinutes);
ThresholdEventWriter thresholdEventWriter = new ThresholdEventWriter(eventWriter, flushEventQueueSize, refreshDelayInSeconds);
controller = new CollectorController(thresholdEventWriter);
FixedManagedJmxExport.export("eventtracker:name=CollectorController", controller);
}
|
diff --git a/mes-plugins/mes-plugins-orders/src/test/java/com/qcadoo/mes/orders/states/OrderStatesChangingServiceTest.java b/mes-plugins/mes-plugins-orders/src/test/java/com/qcadoo/mes/orders/states/OrderStatesChangingServiceTest.java
index 4d370c4096..160644811e 100644
--- a/mes-plugins/mes-plugins-orders/src/test/java/com/qcadoo/mes/orders/states/OrderStatesChangingServiceTest.java
+++ b/mes-plugins/mes-plugins-orders/src/test/java/com/qcadoo/mes/orders/states/OrderStatesChangingServiceTest.java
@@ -1,253 +1,252 @@
/**
* ***************************************************************************
* Copyright (c) 2010 Qcadoo Limited
* Project: Qcadoo MES
* Version: 1.1.0
*
* This file is part of Qcadoo.
*
* Qcadoo is free software; you can redistribute it and/or modify
* it under the terms of the GNU Affero General Public License as published
* by the Free Software Foundation; either version 3 of the License,
* or (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty
* of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.
* See the GNU Affero General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with this program; if not, write to the Free Software
* Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
* ***************************************************************************
*/
package com.qcadoo.mes.orders.states;
import static org.mockito.BDDMockito.given;
import static org.mockito.Mockito.mock;
import static org.mockito.Mockito.when;
import static org.springframework.test.util.ReflectionTestUtils.setField;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import org.junit.Before;
import org.junit.Test;
import com.qcadoo.localization.api.TranslationService;
import com.qcadoo.mes.orders.constants.OrderStates;
import com.qcadoo.model.api.Entity;
public class OrderStatesChangingServiceTest {
private OrderStatesChangingService orderStatesChangingService;
private OrderStateValidationService orderStateValidationService;
private OrderStateListener orderStateListener;
private TranslationService translationService;
private List<OrderStateListener> listeners = new LinkedList<OrderStateListener>();
private Entity newOrder, oldOrder;
private Iterator<OrderStateListener> listenersIterator;
@Before
public void init() {
orderStatesChangingService = new OrderStatesChangingService();
orderStateListener = mock(OrderStateListener.class);
listeners = mock(LinkedList.class);
newOrder = mock(Entity.class);
oldOrder = mock(Entity.class);
listenersIterator = mock(Iterator.class);
orderStateValidationService = mock(OrderStateValidationService.class);
translationService = mock(TranslationService.class);
when(listenersIterator.hasNext()).thenReturn(true, false);
when(listenersIterator.next()).thenReturn(orderStateListener);
when(listeners.iterator()).thenReturn(listenersIterator);
setField(orderStatesChangingService, "orderStateValidationService", orderStateValidationService);
setField(orderStatesChangingService, "listeners", listeners);
- setField(orderStatesChangingService, "translationService", translationService);
}
@Test
public void shouldAddOrderStateListener() throws Exception {
// given
given(listeners.add(orderStateListener)).willReturn(true);
// when
orderStatesChangingService.addOrderStateListener(orderStateListener);
}
@Test
public void shouldRemoveOrderStateListener() throws Exception {
// given
given(listeners.remove(orderStateListener)).willReturn(true);
// when
orderStatesChangingService.removeOrderStateListener(orderStateListener);
}
@Test
public void shouldFailChangeStateToAcceptedWhenNameFieldIsNull() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.ACCEPTED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.PENDING.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn(null);
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldFailChangeStateToAcceptedWhenTechnologyFieldValueIsNull() throws Exception {
// given
Entity product = mock(Entity.class);
given(newOrder.getStringField("state")).willReturn(OrderStates.ACCEPTED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.PENDING.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("order1");
given(newOrder.getField("product")).willReturn(product);
given(newOrder.getField("plannedQuantity")).willReturn(10L);
given(newOrder.getField("dateTo")).willReturn(null);
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToAccepted() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.ACCEPTED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.PENDING.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToDeclinedFromPending() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.DECLINED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.PENDING.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToInProgressFromAccepted() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.IN_PROGRESS.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.ACCEPTED.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToInProgressFromInterrupted() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.IN_PROGRESS.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.INTERRUPTED.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToCompleted() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.COMPLETED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.IN_PROGRESS.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToAbandonedFromInterrupted() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.ABANDONED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.INTERRUPTED.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToAbandonedFromInProgress() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.ABANDONED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.IN_PROGRESS.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToInterruptedFromInProgress() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.INTERRUPTED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.IN_PROGRESS.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
@Test
public void shouldPerformChangeStateToDeclinedFromAccepted() throws Exception {
// given
given(newOrder.getStringField("state")).willReturn(OrderStates.DECLINED.getStringValue());
given(oldOrder.getStringField("state")).willReturn(OrderStates.ACCEPTED.getStringValue());
given(newOrder.getStringField("number")).willReturn("00001");
given(newOrder.getStringField("name")).willReturn("Order1");
// when
orderStatesChangingService.performChangeState(newOrder, oldOrder);
// then
}
}
| true | true | public void init() {
orderStatesChangingService = new OrderStatesChangingService();
orderStateListener = mock(OrderStateListener.class);
listeners = mock(LinkedList.class);
newOrder = mock(Entity.class);
oldOrder = mock(Entity.class);
listenersIterator = mock(Iterator.class);
orderStateValidationService = mock(OrderStateValidationService.class);
translationService = mock(TranslationService.class);
when(listenersIterator.hasNext()).thenReturn(true, false);
when(listenersIterator.next()).thenReturn(orderStateListener);
when(listeners.iterator()).thenReturn(listenersIterator);
setField(orderStatesChangingService, "orderStateValidationService", orderStateValidationService);
setField(orderStatesChangingService, "listeners", listeners);
setField(orderStatesChangingService, "translationService", translationService);
}
| public void init() {
orderStatesChangingService = new OrderStatesChangingService();
orderStateListener = mock(OrderStateListener.class);
listeners = mock(LinkedList.class);
newOrder = mock(Entity.class);
oldOrder = mock(Entity.class);
listenersIterator = mock(Iterator.class);
orderStateValidationService = mock(OrderStateValidationService.class);
translationService = mock(TranslationService.class);
when(listenersIterator.hasNext()).thenReturn(true, false);
when(listenersIterator.next()).thenReturn(orderStateListener);
when(listeners.iterator()).thenReturn(listenersIterator);
setField(orderStatesChangingService, "orderStateValidationService", orderStateValidationService);
setField(orderStatesChangingService, "listeners", listeners);
}
|
diff --git a/src/ml/VisualTreeDiff.java b/src/ml/VisualTreeDiff.java
index 3eb658e..ce36c0c 100644
--- a/src/ml/VisualTreeDiff.java
+++ b/src/ml/VisualTreeDiff.java
@@ -1,205 +1,208 @@
package ml;
import java.io.File;
import java.io.PrintStream;
import java.util.Arrays;
import java.util.BitSet;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
class PimmxlPrinter {
public static Set<UnorderedPair<ANode, ANode>> auxSet;
static void printIndent( int indent, PrintStream s) {
for( int i = 0; i < indent; i++ ) {
s.print( " " );
}
}
static void printCladeTags( int indent, boolean open, PrintStream s ) {
printIndent(indent, s);
if( open ) {
s.println( "<clade>" );
} else {
s.println( "</clade>");
}
}
static void printColor( int indent, int[]c, PrintStream s ) {
printIndent(indent, s);
s.println( "<color>");
printIndent(indent+1, s);
s.printf( "<red>%d</red>\n", c[0]);
printIndent(indent+1, s);
s.printf( "<green>%d</green>\n", c[1]);
printIndent(indent+1, s);
s.printf( "<blue>%d</blue>\n", c[2]);
printIndent(indent, s);
s.println( "</color>");
}
static void printClade( int indent, LN n, PrintStream s ) {
printCladeTags(indent, true, s);
indent++;
int[] color = {255, 255, 255};
if( !PimmxlPrinter.auxSet.contains(new UnorderedPair<ANode, ANode>(n.back.data, n.data))) {
color[1] = 0;
color[2] = 0;
}
if( n.data.isTip ) {
printIndent(indent, s);
s.printf( "<name>%s</name>\n", n.data.getTipName());
printIndent(indent, s);
s.printf( "<branch_length>%f</branch_length>\n", n.backLen );
printColor( indent, color, s );
} else {
assert( n.next.back != null && n.next.next.back != null );
printIndent(indent, s);
s.printf( "<branch_length>%f</branch_length>\n", n.backLen );
printColor( indent, color, s );
printClade( indent + 1, n.next.back, s);
printClade( indent + 1, n.next.next.back, s);
}
printCladeTags(indent-1, false, s);
}
static void printPhyloxml( LN node, PrintStream s ) {
if( node.data.isTip ) {
if( node.back != null ) {
node = node.back;
} else if( node.next.back != null ) {
node = node.next.back;
} else if( node.next.next.back != null ) {
node = node.next.next.back;
} else {
throw new RuntimeException( "can not print single unlinked node");
}
if( node.data.isTip ) {
throw new RuntimeException( "could not find non-tip node for writing the three (this is a braindead limitation of this tree printer!)");
}
}
s.println( "<?xml version=\"1.0\" encoding=\"UTF-8\"?>" );
s.println( "<phyloxml xmlns:xsi=\"http://www.w3.org/2001/XMLSchema-instance\" xsi:schemaLocation=\"http://www.phyloxml.org http://www.phyloxml.org/1.10/phyloxml.xsd\" xmlns=\"http://www.phyloxml.org\">" );
s.println( "<phylogeny rooted=\"false\">");
int indent = 1;
printCladeTags(indent, true, s);
printClade( indent + 1, node.back, s );
printClade( indent + 1, node.next.back, s );
printClade( indent + 1, node.next.next.back, s );
printCladeTags(indent, false, s);
s.println("</phylogeny>\n</phyloxml>");
}
}
public class VisualTreeDiff {
public static void main(String[] args) {
File t1_name = new File( args[0] );
File t2_name = new File( args[1] );
LN t1 = TreeParser.parse(t1_name);
LN t2 = TreeParser.parse(t2_name);
final String[] t1_tips;
LN[] t1_list = LN.getAsList(t1);
LN[] t2_list = LN.getAsList(t2);
{
Set<String> t1_tipset = LN.getTipSet(t1_list);
Set<String> t2_tipset = LN.getTipSet(t2_list);
final boolean c12 = t1_tipset.containsAll(t2_tipset);
final boolean c21 = t2_tipset.containsAll(t1_tipset);
System.err.printf( "equal: %s\n", (c12 && c21) ? "true" : "false" );
+ if( !(c12 && c21) ) {
+ throw new RuntimeException( "tip set in trees is not equal");
+ }
t1_tips = t1_tipset.toArray(new String[t1_tipset.size()]);
Arrays.sort(t1_tips);
}
LN[][] t1_br = LN.getAllBranchList3(t1);
LN[][] t2_br = LN.getAllBranchList3(t2);
System.err.printf( "br: %d %d\n", t1_br.length, t2_br.length );
assert( t1_br.length == t2_br.length );
BitSet[] t1_splits = new BitSet[t1_br.length];
BitSet[] t2_splits = new BitSet[t2_br.length];
for( int i = 0; i < t1_br.length; i++ ) {
t1_splits[i] = splitToBitset( LN.getSmallerSplitSet(t1_br[i]), t1_tips);
t2_splits[i] = splitToBitset( LN.getSmallerSplitSet(t2_br[i]), t1_tips);
}
Set<UnorderedPair<ANode, ANode>> branchFound = new HashSet<UnorderedPair<ANode, ANode>>();
int nFound = 0;
for( int i = 0; i < t1_splits.length; i++ ) {
boolean found = false;
for( int j = 0; j < t2_splits.length; j++ ) {
if( t1_splits[i].equals(t2_splits[j]) ) {
nFound++;
found = true;
break;
}
}
if( found ) {
branchFound.add( new UnorderedPair<ANode, ANode>(t1_br[i][0].data, t1_br[i][1].data));
}
}
System.err.printf( "nFound: %d\n", nFound );
PimmxlPrinter.auxSet = branchFound;
PimmxlPrinter.printPhyloxml(t1, System.out);
}
private static BitSet splitToBitset(String[] splitSet,
String[] refOrder ) {
Arrays.sort( splitSet );
BitSet bs = new BitSet(refOrder.length);
for( int i = 0, j = 0; i < refOrder.length && j < splitSet.length; ++i ) {
if( refOrder[i].equals(splitSet[j] )) {
bs.set(i);
j++;
}
}
return bs;
}
}
| false | true | public static void main(String[] args) {
File t1_name = new File( args[0] );
File t2_name = new File( args[1] );
LN t1 = TreeParser.parse(t1_name);
LN t2 = TreeParser.parse(t2_name);
final String[] t1_tips;
LN[] t1_list = LN.getAsList(t1);
LN[] t2_list = LN.getAsList(t2);
{
Set<String> t1_tipset = LN.getTipSet(t1_list);
Set<String> t2_tipset = LN.getTipSet(t2_list);
final boolean c12 = t1_tipset.containsAll(t2_tipset);
final boolean c21 = t2_tipset.containsAll(t1_tipset);
System.err.printf( "equal: %s\n", (c12 && c21) ? "true" : "false" );
t1_tips = t1_tipset.toArray(new String[t1_tipset.size()]);
Arrays.sort(t1_tips);
}
LN[][] t1_br = LN.getAllBranchList3(t1);
LN[][] t2_br = LN.getAllBranchList3(t2);
System.err.printf( "br: %d %d\n", t1_br.length, t2_br.length );
assert( t1_br.length == t2_br.length );
BitSet[] t1_splits = new BitSet[t1_br.length];
BitSet[] t2_splits = new BitSet[t2_br.length];
for( int i = 0; i < t1_br.length; i++ ) {
t1_splits[i] = splitToBitset( LN.getSmallerSplitSet(t1_br[i]), t1_tips);
t2_splits[i] = splitToBitset( LN.getSmallerSplitSet(t2_br[i]), t1_tips);
}
Set<UnorderedPair<ANode, ANode>> branchFound = new HashSet<UnorderedPair<ANode, ANode>>();
int nFound = 0;
for( int i = 0; i < t1_splits.length; i++ ) {
boolean found = false;
for( int j = 0; j < t2_splits.length; j++ ) {
if( t1_splits[i].equals(t2_splits[j]) ) {
nFound++;
found = true;
break;
}
}
if( found ) {
branchFound.add( new UnorderedPair<ANode, ANode>(t1_br[i][0].data, t1_br[i][1].data));
}
}
System.err.printf( "nFound: %d\n", nFound );
PimmxlPrinter.auxSet = branchFound;
PimmxlPrinter.printPhyloxml(t1, System.out);
}
| public static void main(String[] args) {
File t1_name = new File( args[0] );
File t2_name = new File( args[1] );
LN t1 = TreeParser.parse(t1_name);
LN t2 = TreeParser.parse(t2_name);
final String[] t1_tips;
LN[] t1_list = LN.getAsList(t1);
LN[] t2_list = LN.getAsList(t2);
{
Set<String> t1_tipset = LN.getTipSet(t1_list);
Set<String> t2_tipset = LN.getTipSet(t2_list);
final boolean c12 = t1_tipset.containsAll(t2_tipset);
final boolean c21 = t2_tipset.containsAll(t1_tipset);
System.err.printf( "equal: %s\n", (c12 && c21) ? "true" : "false" );
if( !(c12 && c21) ) {
throw new RuntimeException( "tip set in trees is not equal");
}
t1_tips = t1_tipset.toArray(new String[t1_tipset.size()]);
Arrays.sort(t1_tips);
}
LN[][] t1_br = LN.getAllBranchList3(t1);
LN[][] t2_br = LN.getAllBranchList3(t2);
System.err.printf( "br: %d %d\n", t1_br.length, t2_br.length );
assert( t1_br.length == t2_br.length );
BitSet[] t1_splits = new BitSet[t1_br.length];
BitSet[] t2_splits = new BitSet[t2_br.length];
for( int i = 0; i < t1_br.length; i++ ) {
t1_splits[i] = splitToBitset( LN.getSmallerSplitSet(t1_br[i]), t1_tips);
t2_splits[i] = splitToBitset( LN.getSmallerSplitSet(t2_br[i]), t1_tips);
}
Set<UnorderedPair<ANode, ANode>> branchFound = new HashSet<UnorderedPair<ANode, ANode>>();
int nFound = 0;
for( int i = 0; i < t1_splits.length; i++ ) {
boolean found = false;
for( int j = 0; j < t2_splits.length; j++ ) {
if( t1_splits[i].equals(t2_splits[j]) ) {
nFound++;
found = true;
break;
}
}
if( found ) {
branchFound.add( new UnorderedPair<ANode, ANode>(t1_br[i][0].data, t1_br[i][1].data));
}
}
System.err.printf( "nFound: %d\n", nFound );
PimmxlPrinter.auxSet = branchFound;
PimmxlPrinter.printPhyloxml(t1, System.out);
}
|
diff --git a/clustermate-client-ahc/src/main/java/com/fasterxml/clustermate/client/ahc/AHCContentPutter.java b/clustermate-client-ahc/src/main/java/com/fasterxml/clustermate/client/ahc/AHCContentPutter.java
index 15ffeefb..40667b55 100644
--- a/clustermate-client-ahc/src/main/java/com/fasterxml/clustermate/client/ahc/AHCContentPutter.java
+++ b/clustermate-client-ahc/src/main/java/com/fasterxml/clustermate/client/ahc/AHCContentPutter.java
@@ -1,254 +1,254 @@
package com.fasterxml.clustermate.client.ahc;
import java.io.*;
import java.util.concurrent.ExecutionException;
import java.util.concurrent.TimeUnit;
import java.util.concurrent.TimeoutException;
import java.util.concurrent.atomic.AtomicInteger;
import com.fasterxml.clustermate.api.ClusterMateConstants;
import com.fasterxml.clustermate.api.EntryKey;
import com.fasterxml.clustermate.api.EntryKeyConverter;
import com.fasterxml.clustermate.client.CallFailure;
import com.fasterxml.clustermate.client.ClusterServerNode;
import com.fasterxml.clustermate.client.StoreClientConfig;
import com.fasterxml.clustermate.client.call.*;
import com.fasterxml.storemate.shared.ByteContainer;
import com.fasterxml.storemate.shared.compress.Compression;
import com.fasterxml.storemate.shared.util.IOUtil;
import com.fasterxml.storemate.shared.util.WithBytesCallback;
import com.ning.http.client.AsyncHttpClient;
import com.ning.http.client.AsyncHttpClient.BoundRequestBuilder;
import com.ning.http.client.Body;
import com.ning.http.client.BodyGenerator;
import com.ning.http.client.ListenableFuture;
import com.ning.http.client.Response;
/*
import org.apache.http.*;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.client.utils.URIBuilder;
import org.apache.http.entity.InputStreamEntity;
import org.apache.http.util.EntityUtils;
*/
/**
* Helper accessors class used for making a single PUT call to a single
* server node.
*/
public class AHCContentPutter<K extends EntryKey, P extends Enum<P>>
extends AHCBasedAccessor<K,P>
implements ContentPutter<K>
{
protected final ClusterServerNode _server;
public AHCContentPutter(StoreClientConfig<K,?> storeConfig, P endpoint,
AsyncHttpClient asyncHC, ClusterServerNode server)
{
super(storeConfig, endpoint, asyncHC);
_server = server;
_keyConverter = storeConfig.getKeyConverter();
}
@Override
public CallFailure tryPut(CallConfig config, PutCallParameters params,
long endOfTime, K contentId, PutContentProvider content)
{
// first: if we can't spend at least 10 msecs, let's give up:
final long startTime = System.currentTimeMillis();
final long timeout = Math.min(endOfTime - startTime, config.getPutCallTimeoutMsecs());
if (timeout < config.getMinimumTimeoutMsecs()) {
return CallFailure.timeout(_server, startTime, startTime);
}
try {
// return _tryPutBlocking
return _tryPutAsync
(config, params, endOfTime, contentId, content, startTime, timeout);
} catch (Exception e) {
return CallFailure.clientInternal(_server, startTime, System.currentTimeMillis(), e);
}
}
/*
/**********************************************************************
/* Implementation: blocking
/**********************************************************************
*/
/*
// With Apache HC:
public CallFailure _tryPutBlocking(CallConfig config, PutCallParameters params,
long endOfTime,
String contentId, PutContentProvider content,
final long startTime, final long timeout)
throws IOException, ExecutionException, InterruptedException, URISyntaxException
{
AHCPathBuilder path = _server.rootPath();
path = _pathFinder.appendPath(path, PathType.STORE_ENTRY);
path = _keyConverter.appendToPath(path, contentId);
if (params != null) {
path = params.appendToPath(path, contentId);
}
URIBuilder ub = new URIBuilder(path);
int checksum = content.getChecksum32();
addStandardParams(ub, checksum);
HttpPut put = new HttpPut(ub.build());
put.setEntity(new InputStreamEntity(content.asStream(), -1L));
HttpResponse response = _blockingHC.execute(put);
int statusCode = response.getStatusLine().getStatusCode();
HttpEntity entity = response.getEntity();
// one more thing: handle standard headers, if any?
// handleHeaders(_server, resp, startTime);
if (HttpUtil.isSuccess(statusCode)) {
EntityUtils.consume(entity);
// InputStream in = entity.getContent();
// while (in.skip(Integer.MAX_VALUE) > 0L) { }
// in.close();
return null;
}
// if not, why not? Any well-known problems?
// then the default fallback
String msg = HttpUtil.getExcerpt(EntityUtils.toByteArray(entity));
return CallFailure.general(_server, statusCode, startTime, System.currentTimeMillis(), msg);
}
// protected <T extends HttpRequest> T addStandardParams(T request)
protected URIBuilder addStandardParams(URIBuilder builder,
int checksum)
{
builder.addParameter(Constants.HTTP_QUERY_PARAM_CHECKSUM,
(checksum == 0) ? "0" : String.valueOf(checksum));
return builder;
}
*/
/*
/**********************************************************************
/* Call implementation
/**********************************************************************
*/
// And with async-http-client:
public CallFailure _tryPutAsync(CallConfig config, PutCallParameters params,
long endOfTime,
K contentId, PutContentProvider content,
final long startTime, final long timeout)
throws IOException, ExecutionException, InterruptedException
{
AHCPathBuilder path = _server.rootPath();
path = _pathFinder.appendPath(path, _endpoint);
path = _keyConverter.appendToPath(path, contentId);
if (params != null) {
path = params.appendToPath(path, contentId);
}
// Is compression known?
Compression comp = content.getExistingCompression();
if (comp != null) { // if so, must be indicated
- path = path.setHeader(ClusterMateConstants.HTTP_HEADER_COMPRESSION, comp.asContentEncoding());
+ path = path.addCompression(comp, content.uncompressedLength());
}
Generator<K> gen = new Generator<K>(content, _keyConverter);
int checksum = gen.getChecksum();
path = path.addParameter(ClusterMateConstants.QUERY_PARAM_CHECKSUM,
(checksum == 0) ? "0" : String.valueOf(checksum));
BoundRequestBuilder reqBuilder = path.putRequest(_httpClient);
reqBuilder = reqBuilder.setBody(gen);
ListenableFuture<Response> futurama = _httpClient.executeRequest(reqBuilder.build());
// First, see if we can get the answer without time out...
Response resp;
try {
resp = futurama.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
return CallFailure.timeout(_server, startTime, System.currentTimeMillis());
}
// and if so, is it successful?
int statusCode = resp.getStatusCode();
// one more thing: handle standard headers, if any?
handleHeaders(_server, resp, startTime);
if (IOUtil.isHTTPSuccess(statusCode)) {
drain(resp);
return null;
}
// if not, why not? Any well-known problems?
// then the default fallback
String msg = getExcerpt(resp, config.getMaxExcerptLength());
return CallFailure.general(_server, statusCode, startTime, System.currentTimeMillis(), msg);
}
/*
/**********************************************************************
/* Helper classes
/**********************************************************************
*/
protected final static class Generator<K extends EntryKey>
implements BodyGenerator
{
protected final PutContentProvider _content;
protected final EntryKeyConverter<K> _keyConverter;
protected final AtomicInteger _checksum;
public Generator(PutContentProvider content, EntryKeyConverter<K> keyConverter)
{
_content = content;
_keyConverter = keyConverter;
// Let's see if we can calculate content checksum early, for even the first request
int checksum = 0;
ByteContainer bytes = _content.contentAsBytes();
if (bytes != null) {
checksum = _keyConverter.contentHashFor(bytes);
}
_checksum = new AtomicInteger(checksum);
}
public int getChecksum() {
return _checksum.get();
}
@Override
public Body createBody() throws IOException
{
int checksum = _checksum.get();
ByteContainer bytes = _content.contentAsBytes();
if (bytes != null) {
if (checksum == 0) {
checksum = _keyConverter.contentHashFor(bytes);
_checksum.set(checksum);
}
return bytes.withBytes(BodyCallback.instance);
}
File f = _content.contentAsFile();
if (f != null) {
try {
return new BodyFileBacked(f, _content.length(), _checksum);
} catch (IOException ie) {
throw new IllegalStateException("Failed to open file '"+f.getAbsolutePath()+"': "
+ie.getMessage(), ie);
}
}
// sanity check; we'll never get here:
throw new IOException("No suitable body generation method found");
}
}
protected final static class BodyCallback implements WithBytesCallback<Body>
{
public final static BodyCallback instance = new BodyCallback();
@Override
public Body withBytes(byte[] buffer, int offset, int length) {
return new BodyByteBacked(buffer, offset, length);
}
}
}
| true | true | public CallFailure _tryPutAsync(CallConfig config, PutCallParameters params,
long endOfTime,
K contentId, PutContentProvider content,
final long startTime, final long timeout)
throws IOException, ExecutionException, InterruptedException
{
AHCPathBuilder path = _server.rootPath();
path = _pathFinder.appendPath(path, _endpoint);
path = _keyConverter.appendToPath(path, contentId);
if (params != null) {
path = params.appendToPath(path, contentId);
}
// Is compression known?
Compression comp = content.getExistingCompression();
if (comp != null) { // if so, must be indicated
path = path.setHeader(ClusterMateConstants.HTTP_HEADER_COMPRESSION, comp.asContentEncoding());
}
Generator<K> gen = new Generator<K>(content, _keyConverter);
int checksum = gen.getChecksum();
path = path.addParameter(ClusterMateConstants.QUERY_PARAM_CHECKSUM,
(checksum == 0) ? "0" : String.valueOf(checksum));
BoundRequestBuilder reqBuilder = path.putRequest(_httpClient);
reqBuilder = reqBuilder.setBody(gen);
ListenableFuture<Response> futurama = _httpClient.executeRequest(reqBuilder.build());
// First, see if we can get the answer without time out...
Response resp;
try {
resp = futurama.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
return CallFailure.timeout(_server, startTime, System.currentTimeMillis());
}
// and if so, is it successful?
int statusCode = resp.getStatusCode();
// one more thing: handle standard headers, if any?
handleHeaders(_server, resp, startTime);
if (IOUtil.isHTTPSuccess(statusCode)) {
drain(resp);
return null;
}
// if not, why not? Any well-known problems?
// then the default fallback
String msg = getExcerpt(resp, config.getMaxExcerptLength());
return CallFailure.general(_server, statusCode, startTime, System.currentTimeMillis(), msg);
}
| public CallFailure _tryPutAsync(CallConfig config, PutCallParameters params,
long endOfTime,
K contentId, PutContentProvider content,
final long startTime, final long timeout)
throws IOException, ExecutionException, InterruptedException
{
AHCPathBuilder path = _server.rootPath();
path = _pathFinder.appendPath(path, _endpoint);
path = _keyConverter.appendToPath(path, contentId);
if (params != null) {
path = params.appendToPath(path, contentId);
}
// Is compression known?
Compression comp = content.getExistingCompression();
if (comp != null) { // if so, must be indicated
path = path.addCompression(comp, content.uncompressedLength());
}
Generator<K> gen = new Generator<K>(content, _keyConverter);
int checksum = gen.getChecksum();
path = path.addParameter(ClusterMateConstants.QUERY_PARAM_CHECKSUM,
(checksum == 0) ? "0" : String.valueOf(checksum));
BoundRequestBuilder reqBuilder = path.putRequest(_httpClient);
reqBuilder = reqBuilder.setBody(gen);
ListenableFuture<Response> futurama = _httpClient.executeRequest(reqBuilder.build());
// First, see if we can get the answer without time out...
Response resp;
try {
resp = futurama.get(timeout, TimeUnit.MILLISECONDS);
} catch (TimeoutException e) {
return CallFailure.timeout(_server, startTime, System.currentTimeMillis());
}
// and if so, is it successful?
int statusCode = resp.getStatusCode();
// one more thing: handle standard headers, if any?
handleHeaders(_server, resp, startTime);
if (IOUtil.isHTTPSuccess(statusCode)) {
drain(resp);
return null;
}
// if not, why not? Any well-known problems?
// then the default fallback
String msg = getExcerpt(resp, config.getMaxExcerptLength());
return CallFailure.general(_server, statusCode, startTime, System.currentTimeMillis(), msg);
}
|
diff --git a/src/net/skyebook/DBActions.java b/src/net/skyebook/DBActions.java
index 0559b8e..91962ec 100644
--- a/src/net/skyebook/DBActions.java
+++ b/src/net/skyebook/DBActions.java
@@ -1,217 +1,217 @@
/**
*
*/
package net.skyebook;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.List;
import java.util.concurrent.atomic.AtomicBoolean;
import edu.poly.bxmc.betaville.osm.Node;
import edu.poly.bxmc.betaville.osm.Relation;
import edu.poly.bxmc.betaville.osm.RelationMemeber;
import edu.poly.bxmc.betaville.osm.tag.AbstractTag;
/**
* @author Skye Book
*
*/
public class DBActions {
private AtomicBoolean busy = new AtomicBoolean(false);
private Connection con = null;
private Statement statement = null;
private PreparedStatement insertNode;
private PreparedStatement insertNodeNullTags;
private PreparedStatement insertWay;
private PreparedStatement insertWayNullTags;
private PreparedStatement insertWayMember;
private PreparedStatement insertRelation;
private PreparedStatement insertRelationNullTags;
private PreparedStatement insertRelationMember;
/**
* Constructor - Creates (opens) the SQL connection
*/
public DBActions(String user, String pass, String dbName) {
try {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/"+dbName,
pass,
pass);
statement = con.createStatement();
System.out.println("Preparing statements");
insertNode = con.prepareStatement("INSERT INTO nodes (id, latitude, longitude, tags) VALUES (?, ?, ?, ?)");
insertNodeNullTags = con.prepareStatement("INSERT INTO nodes (id, latitude, longitude) VALUES (?, ?, ?)");
insertWay = con.prepareStatement("INSERT INTO ways (id, tags) VALUES (?, ?)");
insertWayNullTags = con.prepareStatement("INSERT INTO ways (id) VALUES (?)");
insertWayMember = con.prepareStatement("INSERT INTO way_members (way, node) VALUES (?, ?)");
- insertRelation = con.prepareStatement("INSERT INTO relation (id, tags) VALUES (?, ?)");
- insertRelationNullTags = con.prepareStatement("INSERT INTO relation (id) VALUES (?)");
+ insertRelation = con.prepareStatement("INSERT INTO relations (id, tags) VALUES (?, ?)");
+ insertRelationNullTags = con.prepareStatement("INSERT INTO relations (id) VALUES (?)");
insertRelationMember = con.prepareStatement("INSERT INTO relation_members (relation, way, type) VALUES (?, ?, ?)");
System.out.println("Statements Prepared");
} catch (ClassNotFoundException e) {
System.err.println("ClassNotFoundException: " + e.getMessage());
} catch (InstantiationException e) {
System.err.println("InstantiationException: " + e.getMessage());
} catch (IllegalAccessException e) {
System.err.println("IllegalAccessException: " + e.getMessage());
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
System.err.println("SQLState: " + e.getSQLState());
System.err.println("VendorError: " + e.getErrorCode());
}
}
public void addNode(Node node) throws SQLException{
busy.set(true);
if(node.getTags().size()==0){
insertNodeNullTags.setLong(1, node.getId());
insertNodeNullTags.setDouble(2, node.getLocation().getLatitude());
insertNodeNullTags.setDouble(3, node.getLocation().getLongitude());
insertNodeNullTags.execute();
}
else{
insertNode.setLong(1, node.getId());
insertNode.setDouble(2, node.getLocation().getLatitude());
insertNode.setDouble(3, node.getLocation().getLongitude());
insertNode.setString(4, createTagString(node.getTags()));
insertNode.execute();
}
busy.set(false);
}
public void addWay(ShallowWay way) throws SQLException{
busy.set(true);
if(way.getTags().size()==0){
insertWayNullTags.setLong(1, way.getId());
insertWayNullTags.execute();
}
else{
insertWay.setLong(1, way.getId());
insertWay.setString(2, createTagString(way.getTags()));
insertWay.execute();
}
for(long reference : way.getNodeReferences()){
addWayMember(way.getId(), reference);
}
busy.set(false);
}
public void addRelation(Relation relation) throws SQLException{
busy.set(true);
if(relation.getTags().size()==0){
insertRelationNullTags.setLong(1, relation.getId());
insertRelationNullTags.execute();
}
else{
insertRelation.setLong(1, relation.getId());
insertRelation.setString(2, createTagString(relation.getTags()));
insertRelation.execute();
}
for(RelationMemeber rm : relation.getMemebers()){
addRelationMember(relation.getId(), rm);
}
busy.set(false);
}
private void addRelationMember(long relationID, RelationMemeber rm) throws SQLException{
insertRelationMember.setLong(1, relationID);
insertRelationMember.setLong(2, rm.getObjectReference().getId());
insertRelationMember.setString(3, rm.getRole());
insertRelationMember.execute();
}
private void addWayMember(long wayID, long nodeID) throws SQLException{
insertWayMember.setLong(1, wayID);
insertWayMember.setLong(2, nodeID);
insertWayMember.execute();
}
private String createTagString(List<AbstractTag> tags){
// build the tag string
StringBuilder tagString = new StringBuilder();
//System.out.println("there are "+tags.size()+" tags");
for(AbstractTag tag : tags){
// if this is not the first tag, add a comma to separate it from the last pair
if(tagString.length()>0) tagString.append(",");
tagString.append(tag.getKey()+","+tag.getValue());
}
return tagString.toString();
}
public synchronized boolean isBusy(){
return busy.get();
}
/**
* Sends the SQL query to the database
*
* @param query
* Query to send to the database
* @return The set of results obtained after the execution of the query
* @throws SQLException
*/
public ResultSet sendQuery(String query) throws SQLException {
return con.createStatement().executeQuery(query);
}
public int sendUpdate(String update) throws SQLException{
return statement.executeUpdate(update, Statement.RETURN_GENERATED_KEYS);
}
public int getLastKey(){
try {
ResultSet rs = statement.getGeneratedKeys();
if(rs.next()){
int last = rs.getInt(1);
return last;
}
} catch (SQLException e) {
e.printStackTrace();
}
return -1;
}
/**
* Closes the connection with the database
*/
public void closeConnection() {
try {
if (con != null) {
con.close();
}
} catch (SQLException e) {
e.printStackTrace();
}
}
public Connection getConnection(){
return con;
}
}
| true | true | public DBActions(String user, String pass, String dbName) {
try {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/"+dbName,
pass,
pass);
statement = con.createStatement();
System.out.println("Preparing statements");
insertNode = con.prepareStatement("INSERT INTO nodes (id, latitude, longitude, tags) VALUES (?, ?, ?, ?)");
insertNodeNullTags = con.prepareStatement("INSERT INTO nodes (id, latitude, longitude) VALUES (?, ?, ?)");
insertWay = con.prepareStatement("INSERT INTO ways (id, tags) VALUES (?, ?)");
insertWayNullTags = con.prepareStatement("INSERT INTO ways (id) VALUES (?)");
insertWayMember = con.prepareStatement("INSERT INTO way_members (way, node) VALUES (?, ?)");
insertRelation = con.prepareStatement("INSERT INTO relation (id, tags) VALUES (?, ?)");
insertRelationNullTags = con.prepareStatement("INSERT INTO relation (id) VALUES (?)");
insertRelationMember = con.prepareStatement("INSERT INTO relation_members (relation, way, type) VALUES (?, ?, ?)");
System.out.println("Statements Prepared");
} catch (ClassNotFoundException e) {
System.err.println("ClassNotFoundException: " + e.getMessage());
} catch (InstantiationException e) {
System.err.println("InstantiationException: " + e.getMessage());
} catch (IllegalAccessException e) {
System.err.println("IllegalAccessException: " + e.getMessage());
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
System.err.println("SQLState: " + e.getSQLState());
System.err.println("VendorError: " + e.getErrorCode());
}
}
| public DBActions(String user, String pass, String dbName) {
try {
try {
Class.forName("com.mysql.jdbc.Driver").newInstance();
con = DriverManager.getConnection(
"jdbc:mysql://localhost:3306/"+dbName,
pass,
pass);
statement = con.createStatement();
System.out.println("Preparing statements");
insertNode = con.prepareStatement("INSERT INTO nodes (id, latitude, longitude, tags) VALUES (?, ?, ?, ?)");
insertNodeNullTags = con.prepareStatement("INSERT INTO nodes (id, latitude, longitude) VALUES (?, ?, ?)");
insertWay = con.prepareStatement("INSERT INTO ways (id, tags) VALUES (?, ?)");
insertWayNullTags = con.prepareStatement("INSERT INTO ways (id) VALUES (?)");
insertWayMember = con.prepareStatement("INSERT INTO way_members (way, node) VALUES (?, ?)");
insertRelation = con.prepareStatement("INSERT INTO relations (id, tags) VALUES (?, ?)");
insertRelationNullTags = con.prepareStatement("INSERT INTO relations (id) VALUES (?)");
insertRelationMember = con.prepareStatement("INSERT INTO relation_members (relation, way, type) VALUES (?, ?, ?)");
System.out.println("Statements Prepared");
} catch (ClassNotFoundException e) {
System.err.println("ClassNotFoundException: " + e.getMessage());
} catch (InstantiationException e) {
System.err.println("InstantiationException: " + e.getMessage());
} catch (IllegalAccessException e) {
System.err.println("IllegalAccessException: " + e.getMessage());
}
} catch (SQLException e) {
System.err.println("SQLException: " + e.getMessage());
System.err.println("SQLState: " + e.getSQLState());
System.err.println("VendorError: " + e.getErrorCode());
}
}
|
diff --git a/wikapidia-core/src/main/java/org/wikapidia/core/dao/ArticleDao.java b/wikapidia-core/src/main/java/org/wikapidia/core/dao/ArticleDao.java
index 2fac9a80..0d727c37 100644
--- a/wikapidia-core/src/main/java/org/wikapidia/core/dao/ArticleDao.java
+++ b/wikapidia-core/src/main/java/org/wikapidia/core/dao/ArticleDao.java
@@ -1,41 +1,42 @@
package org.wikapidia.core.dao;
import org.jooq.DSLContext;
import org.jooq.Record;
import org.jooq.Result;
import org.jooq.SQLDialect;
import org.jooq.impl.DSL;
import org.wikapidia.core.model.Article;
import java.sql.Connection;
import java.sql.DriverManager;
import org.wikapidia.core.jooq.Tables;
/**
*/
public class ArticleDao {
public Article get(int wpId) {
try{
Connection conn = connect();
DSLContext context = DSL.using(conn, SQLDialect.H2);
Record record = context.select().from(Tables.ARTICLE).where(Tables.ARTICLE.ID.equal(wpId)).fetchOne();
Article a = new Article(
record.getValue(Tables.ARTICLE.ID),
record.getValue(Tables.ARTICLE.TITLE),
Article.NameSpace.intToNS(record.getValue(Tables.ARTICLE.NS)),
Article.PageType.values()[record.getValue(Tables.ARTICLE.PTYPE)]
);
- return null;
+ conn.close();
+ return a;
}
catch (Exception e){
e.printStackTrace();
return null;
}
}
private Connection connect()throws Exception{
Class.forName("org.h2.Driver");
Connection conn = DriverManager.getConnection("tmp/maven-test");
return conn;
}
}
| true | true | public Article get(int wpId) {
try{
Connection conn = connect();
DSLContext context = DSL.using(conn, SQLDialect.H2);
Record record = context.select().from(Tables.ARTICLE).where(Tables.ARTICLE.ID.equal(wpId)).fetchOne();
Article a = new Article(
record.getValue(Tables.ARTICLE.ID),
record.getValue(Tables.ARTICLE.TITLE),
Article.NameSpace.intToNS(record.getValue(Tables.ARTICLE.NS)),
Article.PageType.values()[record.getValue(Tables.ARTICLE.PTYPE)]
);
return null;
}
catch (Exception e){
e.printStackTrace();
return null;
}
}
| public Article get(int wpId) {
try{
Connection conn = connect();
DSLContext context = DSL.using(conn, SQLDialect.H2);
Record record = context.select().from(Tables.ARTICLE).where(Tables.ARTICLE.ID.equal(wpId)).fetchOne();
Article a = new Article(
record.getValue(Tables.ARTICLE.ID),
record.getValue(Tables.ARTICLE.TITLE),
Article.NameSpace.intToNS(record.getValue(Tables.ARTICLE.NS)),
Article.PageType.values()[record.getValue(Tables.ARTICLE.PTYPE)]
);
conn.close();
return a;
}
catch (Exception e){
e.printStackTrace();
return null;
}
}
|
diff --git a/syncronizer/src/org/sync/GitImporter.java b/syncronizer/src/org/sync/GitImporter.java
index b6f48c6..68faf07 100644
--- a/syncronizer/src/org/sync/GitImporter.java
+++ b/syncronizer/src/org/sync/GitImporter.java
@@ -1,364 +1,372 @@
/*****************************************************************************
This file is part of Git-Starteam.
Git-Starteam 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.
Git-Starteam 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 Git-Starteam. If not, see <http://www.gnu.org/licenses/>.
******************************************************************************/
package org.sync;
import java.io.IOException;
import java.io.OutputStream;
import java.text.MessageFormat;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.Vector;
import org.ossnoize.git.fastimport.Commit;
import org.ossnoize.git.fastimport.Data;
import org.ossnoize.git.fastimport.FileDelete;
import org.ossnoize.git.fastimport.FileModification;
import org.ossnoize.git.fastimport.FileOperation;
import org.ossnoize.git.fastimport.enumeration.GitFileType;
import org.ossnoize.git.fastimport.exception.InvalidPathException;
import com.starbase.starteam.Folder;
import com.starbase.starteam.Item;
import com.starbase.starteam.Project;
import com.starbase.starteam.PropertyEnums;
import com.starbase.starteam.Server;
import com.starbase.starteam.View;
import com.starbase.starteam.File;
import com.starbase.starteam.CheckoutManager;
public class GitImporter {
private static final String revisionKeyFormat = "{0,number,000000000000000}|{1,number,000000}|{2}|{3}";
private Server server;
private Project project;
Folder folder;
int folderNameLength;
private long lastModifiedTime = 0;
private Map<String, File> sortedFileList = new TreeMap<String, File>();
private Map<String, File> AddedSortedFileList = new TreeMap<String, File>();
private Map<String, File> lastSortedFileList = new TreeMap<String, File>();
Commit lastcommit;
OutputStream exportStream;
private final String headFormat = "refs/heads/{0}";
private String alternateHead = null;
private boolean isResume = false;
private RepositoryHelper helper;
private PropertyEnums propertyEnums = null;
// Use these sets to find all the deleted files.
private Set<String> files = new HashSet<String>();
private Set<String> deletedFiles = new HashSet<String>();
private Set<String> lastFiles = new HashSet<String>();
public GitImporter(Server s, Project p) {
server = s;
project = p;
propertyEnums = server.getPropertyEnums();
}
public void openHelper() {
helper = RepositoryHelperFactory.getFactory().createHelper();
}
public void closeHelper() {
helper.gc();
RepositoryHelperFactory.getFactory().clearCachedHelper();
}
public long getLastModifiedTime() {
return lastModifiedTime;
}
public void setFolder(View view, String folderPath) {
if(null != folderPath) {
recursiveFolderPopulation(view.getRootFolder(), folderPath);
folderNameLength = folderPath.length();
} else {
folder = view.getRootFolder();
folderNameLength = 0;
}
}
public Folder getFolder() {
return folder;
}
public void recursiveLastModifiedTime(Folder f) {
for(Item i : f.getItems(f.getTypeNames().FILE)) {
if(i instanceof File) {
long modifiedTime = i.getModifiedTime().getLongValue();
if(modifiedTime > lastModifiedTime) {
lastModifiedTime = modifiedTime;
}
i.discard();
}
}
for(Folder subfolder : f.getSubFolders()) {
recursiveLastModifiedTime(subfolder);
}
f.discard();
}
public void setLastFilesLastSortedFileList(View view, String folderPath) {
folder = null;
setFolder(view, folderPath);
if(null == folder) {
return;
}
files.clear();
deletedFiles.clear();
deletedFiles.addAll(lastFiles);
sortedFileList.clear();
recursiveFilePopulation(folder);
lastFiles.clear();
lastFiles.addAll(files);
lastSortedFileList.clear();
lastSortedFileList.putAll(sortedFileList);
AddedSortedFileList.clear();
}
public void generateFastImportStream(View view, long vcTime, String folderPath, String domain) {
// http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html
// said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead."
CheckoutManager cm = new CheckoutManager(view);
cm.getOptions().setEOLConversionEnabled(false);
folder = null;
setFolder(view, folderPath);
if(null == folder) {
return;
}
files.clear();
deletedFiles.clear();
deletedFiles.addAll(lastFiles);
sortedFileList.clear();
recursiveFilePopulation(folder);
lastFiles.clear();
lastFiles.addAll(files);
lastSortedFileList.clear();
lastSortedFileList.putAll(sortedFileList);
recoverDeleteInformation(deletedFiles);
if(AddedSortedFileList.size() > 0 || deletedFiles.size() > 0) {
try {
exportStream = helper.getFastImportStream();
} catch (NullPointerException e) {
e.printStackTrace();
return;
}
}
String head = view.getName();
if(null != alternateHead) {
head = alternateHead;
}
String lastComment = "";
int lastUID = -1;
lastcommit = null;
Vector<java.io.File> lastFiles = new Vector<java.io.File>(10);
for(Map.Entry<String, File> e : AddedSortedFileList.entrySet()) {
File f = e.getValue();
String cmt = f.getComment();
String userName = server.getUser(f.getModifiedBy()).getName();
String userEmail = userName.replaceAll(" ", ".");
userEmail += "@" + domain;
String path = f.getParentFolderHierarchy() + f.getName();
path = path.replace('\\', '/');
// Strip the view name from the path
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1 + folderNameLength);
try {
java.io.File aFile = java.io.File.createTempFile("StarteamFile", ".tmp");
cm.checkoutTo(f, aFile);
FileModification fm = new FileModification(new Data(aFile));
if(aFile.canExecute()) {
fm.setFileType(GitFileType.Executable);
} else {
fm.setFileType(GitFileType.Normal);
}
fm.setPath(path);
if(null != lastcommit && lastComment.equalsIgnoreCase(cmt) && lastUID == f.getModifiedBy()) {
lastcommit.addFileOperation(fm);
lastFiles.add(aFile);
} else {
String ref = MessageFormat.format(headFormat, head);
Commit commit = new Commit(userName, userEmail, cmt, ref, new java.util.Date(f.getModifiedTime().getLongValue()));
commit.addFileOperation(fm);
if(null == lastcommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
lastcommit.writeTo(exportStream);
if(! isResume) {
isResume = true;
}
for(java.io.File old : lastFiles) {
old.delete();
}
lastFiles.clear();
commit.setFromCommit(lastcommit);
}
lastFiles.add(aFile);
/** Keep last for information **/
lastComment = cmt;
lastUID = f.getModifiedBy();
lastcommit = commit;
}
} catch (IOException io) {
io.printStackTrace();
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
f.discard();
}
// TODO: Simple hack to make deletion of disapered files. Since starteam does not carry some kind of
// TODO: delete event. (as known from now)
if(deletedFiles.size() > 0) {
try {
String ref = MessageFormat.format(headFormat, head);
Commit commit = new Commit("File Janitor", "janitor@" + domain, "Cleaning files move along", ref, new java.util.Date(vcTime));
if(null == lastcommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
lastcommit.writeTo(exportStream);
if(! isResume) {
isResume = true;
- }
+ }
+ for(java.io.File old : lastFiles) {
+ old.delete();
+ }
+ lastFiles.clear();
commit.setFromCommit(lastcommit);
}
for(String path : deletedFiles) {
if(!helper.isSpecialFile(path)) {
FileOperation fileDelete = new FileDelete();
try {
fileDelete.setPath(path);
commit.addFileOperation(fileDelete);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
}
}
lastcommit = commit;
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(null != lastcommit) {
try {
lastcommit.writeTo(exportStream);
+ for(java.io.File old : lastFiles) {
+ old.delete();
+ }
+ lastFiles.clear();
} catch (IOException e1) {
e1.printStackTrace();
}
if(! isResume) {
isResume = true;
}
} else {
if(AddedSortedFileList.size() > 0) {
System.err.println("There was no new revision in the starteam view.");
System.err.println("All the files in the repository are at theire lastest version");
} else {
// System.err.println("The starteam view specified was empty.");
}
}
if(AddedSortedFileList.size() > 0 || deletedFiles.size() > 0) {
try {
exportStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.gc();
while(helper.isGitFastImportRunning());
}
AddedSortedFileList.clear();
}
private void recoverDeleteInformation(Set<String> listOfFiles) {
for(String path : listOfFiles) {
//TODO: add delete information when figured out how.
}
}
public void setResume(boolean b) {
isResume = b;
}
private void recursiveFolderPopulation(Folder f, String folderPath) {
boolean first = true;
for(Folder subfolder : f.getSubFolders()) {
if(null != folder) {
subfolder.discard();
f.discard();
break;
}
String path = subfolder.getFolderHierarchy();
path = path.replace('\\', '/');
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1);
if(folderPath.equalsIgnoreCase(path)) {
folder = subfolder;
break;
}
recursiveFolderPopulation(subfolder, folderPath);
}
f.discard();
}
private void recursiveFilePopulation(Folder f) {
boolean first = true;
for(Item i : f.getItems(f.getTypeNames().FILE)) {
if(i instanceof File) {
File historyFile = (File) i;
long modifiedTime = i.getModifiedTime().getLongValue();
int userid = i.getModifiedBy();
String path = i.getParentFolderHierarchy() + historyFile.getName();
path = path.replace('\\', '/');
//path = path.substring(1);
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1 + folderNameLength);
if(deletedFiles.contains(path)) {
deletedFiles.remove(path);
}
files.add(path);
String comment = i.getComment();
i.discard();
String key = MessageFormat.format(revisionKeyFormat, modifiedTime, userid, comment, path);
if(! lastSortedFileList.containsKey(key)) {
AddedSortedFileList.put(key, historyFile);
// System.err.println("Found file marked as: " + key);
}
sortedFileList.put(key, historyFile);
}
}
for(Folder subfolder : f.getSubFolders()) {
recursiveFilePopulation(subfolder);
}
f.discard();
}
public void setHeadName(String head) {
alternateHead = head;
}
}
| false | true | public void generateFastImportStream(View view, long vcTime, String folderPath, String domain) {
// http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html
// said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead."
CheckoutManager cm = new CheckoutManager(view);
cm.getOptions().setEOLConversionEnabled(false);
folder = null;
setFolder(view, folderPath);
if(null == folder) {
return;
}
files.clear();
deletedFiles.clear();
deletedFiles.addAll(lastFiles);
sortedFileList.clear();
recursiveFilePopulation(folder);
lastFiles.clear();
lastFiles.addAll(files);
lastSortedFileList.clear();
lastSortedFileList.putAll(sortedFileList);
recoverDeleteInformation(deletedFiles);
if(AddedSortedFileList.size() > 0 || deletedFiles.size() > 0) {
try {
exportStream = helper.getFastImportStream();
} catch (NullPointerException e) {
e.printStackTrace();
return;
}
}
String head = view.getName();
if(null != alternateHead) {
head = alternateHead;
}
String lastComment = "";
int lastUID = -1;
lastcommit = null;
Vector<java.io.File> lastFiles = new Vector<java.io.File>(10);
for(Map.Entry<String, File> e : AddedSortedFileList.entrySet()) {
File f = e.getValue();
String cmt = f.getComment();
String userName = server.getUser(f.getModifiedBy()).getName();
String userEmail = userName.replaceAll(" ", ".");
userEmail += "@" + domain;
String path = f.getParentFolderHierarchy() + f.getName();
path = path.replace('\\', '/');
// Strip the view name from the path
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1 + folderNameLength);
try {
java.io.File aFile = java.io.File.createTempFile("StarteamFile", ".tmp");
cm.checkoutTo(f, aFile);
FileModification fm = new FileModification(new Data(aFile));
if(aFile.canExecute()) {
fm.setFileType(GitFileType.Executable);
} else {
fm.setFileType(GitFileType.Normal);
}
fm.setPath(path);
if(null != lastcommit && lastComment.equalsIgnoreCase(cmt) && lastUID == f.getModifiedBy()) {
lastcommit.addFileOperation(fm);
lastFiles.add(aFile);
} else {
String ref = MessageFormat.format(headFormat, head);
Commit commit = new Commit(userName, userEmail, cmt, ref, new java.util.Date(f.getModifiedTime().getLongValue()));
commit.addFileOperation(fm);
if(null == lastcommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
lastcommit.writeTo(exportStream);
if(! isResume) {
isResume = true;
}
for(java.io.File old : lastFiles) {
old.delete();
}
lastFiles.clear();
commit.setFromCommit(lastcommit);
}
lastFiles.add(aFile);
/** Keep last for information **/
lastComment = cmt;
lastUID = f.getModifiedBy();
lastcommit = commit;
}
} catch (IOException io) {
io.printStackTrace();
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
f.discard();
}
// TODO: Simple hack to make deletion of disapered files. Since starteam does not carry some kind of
// TODO: delete event. (as known from now)
if(deletedFiles.size() > 0) {
try {
String ref = MessageFormat.format(headFormat, head);
Commit commit = new Commit("File Janitor", "janitor@" + domain, "Cleaning files move along", ref, new java.util.Date(vcTime));
if(null == lastcommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
lastcommit.writeTo(exportStream);
if(! isResume) {
isResume = true;
}
commit.setFromCommit(lastcommit);
}
for(String path : deletedFiles) {
if(!helper.isSpecialFile(path)) {
FileOperation fileDelete = new FileDelete();
try {
fileDelete.setPath(path);
commit.addFileOperation(fileDelete);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
}
}
lastcommit = commit;
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(null != lastcommit) {
try {
lastcommit.writeTo(exportStream);
} catch (IOException e1) {
e1.printStackTrace();
}
if(! isResume) {
isResume = true;
}
} else {
if(AddedSortedFileList.size() > 0) {
System.err.println("There was no new revision in the starteam view.");
System.err.println("All the files in the repository are at theire lastest version");
} else {
// System.err.println("The starteam view specified was empty.");
}
}
if(AddedSortedFileList.size() > 0 || deletedFiles.size() > 0) {
try {
exportStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.gc();
while(helper.isGitFastImportRunning());
}
AddedSortedFileList.clear();
}
| public void generateFastImportStream(View view, long vcTime, String folderPath, String domain) {
// http://techpubs.borland.com/starteam/2009/en/sdk_documentation/api/com/starbase/starteam/CheckoutManager.html
// said old version (passed in /opt/StarTeamCP_2005r2/lib/starteam80.jar) "Deprecated. Use View.createCheckoutManager() instead."
CheckoutManager cm = new CheckoutManager(view);
cm.getOptions().setEOLConversionEnabled(false);
folder = null;
setFolder(view, folderPath);
if(null == folder) {
return;
}
files.clear();
deletedFiles.clear();
deletedFiles.addAll(lastFiles);
sortedFileList.clear();
recursiveFilePopulation(folder);
lastFiles.clear();
lastFiles.addAll(files);
lastSortedFileList.clear();
lastSortedFileList.putAll(sortedFileList);
recoverDeleteInformation(deletedFiles);
if(AddedSortedFileList.size() > 0 || deletedFiles.size() > 0) {
try {
exportStream = helper.getFastImportStream();
} catch (NullPointerException e) {
e.printStackTrace();
return;
}
}
String head = view.getName();
if(null != alternateHead) {
head = alternateHead;
}
String lastComment = "";
int lastUID = -1;
lastcommit = null;
Vector<java.io.File> lastFiles = new Vector<java.io.File>(10);
for(Map.Entry<String, File> e : AddedSortedFileList.entrySet()) {
File f = e.getValue();
String cmt = f.getComment();
String userName = server.getUser(f.getModifiedBy()).getName();
String userEmail = userName.replaceAll(" ", ".");
userEmail += "@" + domain;
String path = f.getParentFolderHierarchy() + f.getName();
path = path.replace('\\', '/');
// Strip the view name from the path
int indexOfFirstPath = path.indexOf('/');
path = path.substring(indexOfFirstPath + 1 + folderNameLength);
try {
java.io.File aFile = java.io.File.createTempFile("StarteamFile", ".tmp");
cm.checkoutTo(f, aFile);
FileModification fm = new FileModification(new Data(aFile));
if(aFile.canExecute()) {
fm.setFileType(GitFileType.Executable);
} else {
fm.setFileType(GitFileType.Normal);
}
fm.setPath(path);
if(null != lastcommit && lastComment.equalsIgnoreCase(cmt) && lastUID == f.getModifiedBy()) {
lastcommit.addFileOperation(fm);
lastFiles.add(aFile);
} else {
String ref = MessageFormat.format(headFormat, head);
Commit commit = new Commit(userName, userEmail, cmt, ref, new java.util.Date(f.getModifiedTime().getLongValue()));
commit.addFileOperation(fm);
if(null == lastcommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
lastcommit.writeTo(exportStream);
if(! isResume) {
isResume = true;
}
for(java.io.File old : lastFiles) {
old.delete();
}
lastFiles.clear();
commit.setFromCommit(lastcommit);
}
lastFiles.add(aFile);
/** Keep last for information **/
lastComment = cmt;
lastUID = f.getModifiedBy();
lastcommit = commit;
}
} catch (IOException io) {
io.printStackTrace();
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
f.discard();
}
// TODO: Simple hack to make deletion of disapered files. Since starteam does not carry some kind of
// TODO: delete event. (as known from now)
if(deletedFiles.size() > 0) {
try {
String ref = MessageFormat.format(headFormat, head);
Commit commit = new Commit("File Janitor", "janitor@" + domain, "Cleaning files move along", ref, new java.util.Date(vcTime));
if(null == lastcommit) {
if(isResume) {
commit.resumeOnTopOfRef();
}
} else {
lastcommit.writeTo(exportStream);
if(! isResume) {
isResume = true;
}
for(java.io.File old : lastFiles) {
old.delete();
}
lastFiles.clear();
commit.setFromCommit(lastcommit);
}
for(String path : deletedFiles) {
if(!helper.isSpecialFile(path)) {
FileOperation fileDelete = new FileDelete();
try {
fileDelete.setPath(path);
commit.addFileOperation(fileDelete);
} catch (InvalidPathException e1) {
e1.printStackTrace();
}
}
}
lastcommit = commit;
} catch (IOException e1) {
e1.printStackTrace();
}
}
if(null != lastcommit) {
try {
lastcommit.writeTo(exportStream);
for(java.io.File old : lastFiles) {
old.delete();
}
lastFiles.clear();
} catch (IOException e1) {
e1.printStackTrace();
}
if(! isResume) {
isResume = true;
}
} else {
if(AddedSortedFileList.size() > 0) {
System.err.println("There was no new revision in the starteam view.");
System.err.println("All the files in the repository are at theire lastest version");
} else {
// System.err.println("The starteam view specified was empty.");
}
}
if(AddedSortedFileList.size() > 0 || deletedFiles.size() > 0) {
try {
exportStream.close();
} catch (IOException e1) {
e1.printStackTrace();
}
System.gc();
while(helper.isGitFastImportRunning());
}
AddedSortedFileList.clear();
}
|
diff --git a/dbproject/src/my/triviagame/xmcd/XmcdDisc.java b/dbproject/src/my/triviagame/xmcd/XmcdDisc.java
index fa1cab9..e94a838 100644
--- a/dbproject/src/my/triviagame/xmcd/XmcdDisc.java
+++ b/dbproject/src/my/triviagame/xmcd/XmcdDisc.java
@@ -1,282 +1,282 @@
package my.triviagame.xmcd;
import com.google.common.base.Objects;
import com.google.common.collect.Lists;
import com.google.common.collect.Maps;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.TreeMap;
import java.util.regex.Matcher;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.text.WordUtils;
/**
* Work with a single XMCD file.
*/
public class XmcdDisc {
/**
* Initializes an {@link XmcdDisc} from the contents of an xmcd file.
* Parses the entire file with one pass.
*
* TODO: consider handling text broken down into multiple lines, e.g.
* DTITLE=Really really really really really really really really really ...
* DTITLE+really really long artist name that got broken / Crappy Album
*
* @param contents all the contents of an xmcd file
* @param freedbGenre the FreeDB genre (corresponds with the directory name)
*/
public static XmcdDisc fromXmcdFile(String contents, FreedbGenre freedbGenre)
throws XmcdFormatException, XmcdMissingInformationException {
XmcdDisc disc = new XmcdDisc();
disc.freedbGenre = freedbGenre;
// Validate xmcd signature
Matcher m = XmcdRegEx.SIGNATURE.matcher(contents);
if (!m.lookingAt()) {
throw new XmcdFormatException("Missing xmcd signature");
}
// Find track offsets
m.usePattern(XmcdRegEx.TRACK_FRAME_OFFSETS_START);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing track frame offsets");
}
List<Integer> trackFrameOffsets = Lists.newArrayList();
m.usePattern(XmcdRegEx.TRACK_FRAME_OFFSET);
while (m.find()) {
if (m.group(1) == null) {
// Found list terminator
break;
}
trackFrameOffsets.add(Integer.parseInt(m.group(1)));
}
// Find disc length
m.usePattern(XmcdRegEx.DISC_LENGTH);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing disc length");
}
disc.discLengthSeconds = Short.parseShort(m.group(1));
// Find revision
m.usePattern(XmcdRegEx.REVISION);
if (m.find()) {
disc.revision = Byte.parseByte(m.group(1));
}
// If no match found for revision, retain the default value
// Find disc ID
m.usePattern(XmcdRegEx.DISC_ID);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing FreeDB ID");
}
- disc.freedbId = Integer.parseInt(m.group(1), 16);
+ disc.freedbId = (int)Long.parseLong(m.group(1), 16);
// Find disc title
m.usePattern(XmcdRegEx.DISC_TITLE);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing disc title");
}
disc.discTitle = DiscTitle.fromXmcdTitle(m.group(1));
// Find disc year
m.usePattern(XmcdRegEx.YEAR);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing year");
}
if (m.group(1).isEmpty()) {
disc.year = -1;
} else {
disc.year = Short.parseShort(m.group(1));
}
// Find disc genre
m.usePattern(XmcdRegEx.GENRE);
if (!m.find()) {
// Use the FreeDB genre (converted to titlecase, e.g. "Pop")
disc.genre = WordUtils.capitalize(disc.freedbGenre.name());
} else {
disc.genre = m.group(1);
}
// Find track titles
m.usePattern(XmcdRegEx.TRACK_TITLE);
TreeMap<Integer, TrackTitle> trackTitles = Maps.newTreeMap();
while (m.find()) {
TrackTitle trackTitle = TrackTitle.fromXmcdTitle(m.group(2), disc.getDiscArtist());
trackTitles.put(Integer.parseInt(m.group(1)), trackTitle);
}
if (trackTitles.isEmpty()) {
throw new XmcdMissingInformationException("Missing track titles");
}
// Build tracks out of titles and lengths
if (trackTitles.size() > trackFrameOffsets.size()) {
throw new XmcdFormatException(
String.format("%d tracks but only %d frame offsets", trackTitles.size(), trackFrameOffsets.size()));
}
FrameOffsetsToTrackDurationsSeconds durations =
new FrameOffsetsToTrackDurationsSeconds(trackFrameOffsets.iterator(), disc.discLengthSeconds);
Iterator<TrackTitle> trackTitlesIter = trackTitles.values().iterator();
while (durations.hasNext()) {
// Adds tracks by their correct order
disc.tracks.add(new Track(trackTitlesIter.next(), durations.next()));
}
return disc;
}
public XmcdDisc(FreedbGenre freedbGenre, short discLengthSeconds, byte revision, int freeDbId, DiscTitle discTitle,
short year, String genre, List<Track> trackTitles) {
this.freedbGenre = freedbGenre;
this.discLengthSeconds = discLengthSeconds;
this.revision = revision;
this.freedbId = freeDbId;
this.discTitle = discTitle;
this.year = year;
this.genre = genre;
this.tracks = trackTitles;
}
public FreedbGenre getFreedbGenre() {
return freedbGenre;
}
public int getDiscLengthSeconds() {
return discLengthSeconds;
}
public byte getRevision() {
return revision;
}
public int getFreeDbId() {
return freedbId;
}
public String getDiscTitle() {
return discTitle.title;
}
public String getDiscArtist() {
return discTitle.artist;
}
/**
* Returns the disc's year or -1 if no year was specified.
*/
public int getYear() {
return year;
}
public String genre() {
return genre;
}
/**
* Display name for the genre, i.e. "Jazz".
* Not limited to the 11 FreeDB genres.
*/
public String getGenre() {
return genre;
}
/**
* Returns a read-only view of the tracks.
*/
public List<Track> getTracks() {
return Collections.unmodifiableList(tracks);
}
@Override
public boolean equals(Object obj) {
if (this == obj) {
return true;
}
if (obj == null) {
return false;
}
if (!(obj instanceof XmcdDisc)) {
return false;
}
XmcdDisc other = (XmcdDisc) obj;
return (Objects.equal(freedbGenre, other.freedbGenre) &&
Objects.equal(discLengthSeconds, other.discLengthSeconds) &&
Objects.equal(revision, other.revision) &&
Objects.equal(freedbId, other.freedbId) &&
Objects.equal(discTitle, other.discTitle) &&
Objects.equal(year, other.year) &&
Objects.equal(genre, other.genre) &&
Objects.equal(tracks, other.tracks));
}
@Override
public int hashCode() {
return Objects.hashCode(freedbId);
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this);
}
/**
* Constructs a new disc with default values.
* Used while building a disc from xmcd data.
* Don't return the returned object before setting its fields or it won't make sense to anyone outside this class.
* Visible for testing.
*/
XmcdDisc() {
// Assign default value to revision
revision = 0;
// Empty tracks list
tracks = Lists.newArrayList();
// Assign invalid values to the rest of the fields
discLengthSeconds = Short.MIN_VALUE;
discTitle = null;
freedbId = 0;
freedbGenre = null;
genre = null;
year = Short.MIN_VALUE;
}
/**
* Verifies that a disc is valid.
* This method is not public because all {@link XmcdDisc}s returned by public methods should always be valid.
* Visible for testing.
*/
void validate() throws XmcdMissingInformationException {
if (discLengthSeconds == Short.MIN_VALUE) {
throw new XmcdMissingInformationException("Missing disc length");
}
if (discTitle == null) {
throw new XmcdMissingInformationException("Missing disc title");
}
if (freedbId == 0) {
throw new XmcdMissingInformationException("Missing FreeDB ID");
}
if (freedbGenre == null) {
throw new XmcdMissingInformationException("Missing FreeDB genre");
}
if (genre == null) {
throw new XmcdMissingInformationException("Missing genre");
}
if (tracks == null || tracks.isEmpty()) {
throw new XmcdMissingInformationException("Missing track titles");
}
if (year == Integer.MIN_VALUE) {
throw new XmcdMissingInformationException("Missing disc year");
}
}
private FreedbGenre freedbGenre;
private short discLengthSeconds;
private byte revision;
private int freedbId;
private DiscTitle discTitle;
private short year;
private String genre;
private List<Track> tracks;
}
| true | true | public static XmcdDisc fromXmcdFile(String contents, FreedbGenre freedbGenre)
throws XmcdFormatException, XmcdMissingInformationException {
XmcdDisc disc = new XmcdDisc();
disc.freedbGenre = freedbGenre;
// Validate xmcd signature
Matcher m = XmcdRegEx.SIGNATURE.matcher(contents);
if (!m.lookingAt()) {
throw new XmcdFormatException("Missing xmcd signature");
}
// Find track offsets
m.usePattern(XmcdRegEx.TRACK_FRAME_OFFSETS_START);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing track frame offsets");
}
List<Integer> trackFrameOffsets = Lists.newArrayList();
m.usePattern(XmcdRegEx.TRACK_FRAME_OFFSET);
while (m.find()) {
if (m.group(1) == null) {
// Found list terminator
break;
}
trackFrameOffsets.add(Integer.parseInt(m.group(1)));
}
// Find disc length
m.usePattern(XmcdRegEx.DISC_LENGTH);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing disc length");
}
disc.discLengthSeconds = Short.parseShort(m.group(1));
// Find revision
m.usePattern(XmcdRegEx.REVISION);
if (m.find()) {
disc.revision = Byte.parseByte(m.group(1));
}
// If no match found for revision, retain the default value
// Find disc ID
m.usePattern(XmcdRegEx.DISC_ID);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing FreeDB ID");
}
disc.freedbId = Integer.parseInt(m.group(1), 16);
// Find disc title
m.usePattern(XmcdRegEx.DISC_TITLE);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing disc title");
}
disc.discTitle = DiscTitle.fromXmcdTitle(m.group(1));
// Find disc year
m.usePattern(XmcdRegEx.YEAR);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing year");
}
if (m.group(1).isEmpty()) {
disc.year = -1;
} else {
disc.year = Short.parseShort(m.group(1));
}
// Find disc genre
m.usePattern(XmcdRegEx.GENRE);
if (!m.find()) {
// Use the FreeDB genre (converted to titlecase, e.g. "Pop")
disc.genre = WordUtils.capitalize(disc.freedbGenre.name());
} else {
disc.genre = m.group(1);
}
// Find track titles
m.usePattern(XmcdRegEx.TRACK_TITLE);
TreeMap<Integer, TrackTitle> trackTitles = Maps.newTreeMap();
while (m.find()) {
TrackTitle trackTitle = TrackTitle.fromXmcdTitle(m.group(2), disc.getDiscArtist());
trackTitles.put(Integer.parseInt(m.group(1)), trackTitle);
}
if (trackTitles.isEmpty()) {
throw new XmcdMissingInformationException("Missing track titles");
}
// Build tracks out of titles and lengths
if (trackTitles.size() > trackFrameOffsets.size()) {
throw new XmcdFormatException(
String.format("%d tracks but only %d frame offsets", trackTitles.size(), trackFrameOffsets.size()));
}
FrameOffsetsToTrackDurationsSeconds durations =
new FrameOffsetsToTrackDurationsSeconds(trackFrameOffsets.iterator(), disc.discLengthSeconds);
Iterator<TrackTitle> trackTitlesIter = trackTitles.values().iterator();
while (durations.hasNext()) {
// Adds tracks by their correct order
disc.tracks.add(new Track(trackTitlesIter.next(), durations.next()));
}
return disc;
}
| public static XmcdDisc fromXmcdFile(String contents, FreedbGenre freedbGenre)
throws XmcdFormatException, XmcdMissingInformationException {
XmcdDisc disc = new XmcdDisc();
disc.freedbGenre = freedbGenre;
// Validate xmcd signature
Matcher m = XmcdRegEx.SIGNATURE.matcher(contents);
if (!m.lookingAt()) {
throw new XmcdFormatException("Missing xmcd signature");
}
// Find track offsets
m.usePattern(XmcdRegEx.TRACK_FRAME_OFFSETS_START);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing track frame offsets");
}
List<Integer> trackFrameOffsets = Lists.newArrayList();
m.usePattern(XmcdRegEx.TRACK_FRAME_OFFSET);
while (m.find()) {
if (m.group(1) == null) {
// Found list terminator
break;
}
trackFrameOffsets.add(Integer.parseInt(m.group(1)));
}
// Find disc length
m.usePattern(XmcdRegEx.DISC_LENGTH);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing disc length");
}
disc.discLengthSeconds = Short.parseShort(m.group(1));
// Find revision
m.usePattern(XmcdRegEx.REVISION);
if (m.find()) {
disc.revision = Byte.parseByte(m.group(1));
}
// If no match found for revision, retain the default value
// Find disc ID
m.usePattern(XmcdRegEx.DISC_ID);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing FreeDB ID");
}
disc.freedbId = (int)Long.parseLong(m.group(1), 16);
// Find disc title
m.usePattern(XmcdRegEx.DISC_TITLE);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing disc title");
}
disc.discTitle = DiscTitle.fromXmcdTitle(m.group(1));
// Find disc year
m.usePattern(XmcdRegEx.YEAR);
if (!m.find()) {
throw new XmcdMissingInformationException("Missing year");
}
if (m.group(1).isEmpty()) {
disc.year = -1;
} else {
disc.year = Short.parseShort(m.group(1));
}
// Find disc genre
m.usePattern(XmcdRegEx.GENRE);
if (!m.find()) {
// Use the FreeDB genre (converted to titlecase, e.g. "Pop")
disc.genre = WordUtils.capitalize(disc.freedbGenre.name());
} else {
disc.genre = m.group(1);
}
// Find track titles
m.usePattern(XmcdRegEx.TRACK_TITLE);
TreeMap<Integer, TrackTitle> trackTitles = Maps.newTreeMap();
while (m.find()) {
TrackTitle trackTitle = TrackTitle.fromXmcdTitle(m.group(2), disc.getDiscArtist());
trackTitles.put(Integer.parseInt(m.group(1)), trackTitle);
}
if (trackTitles.isEmpty()) {
throw new XmcdMissingInformationException("Missing track titles");
}
// Build tracks out of titles and lengths
if (trackTitles.size() > trackFrameOffsets.size()) {
throw new XmcdFormatException(
String.format("%d tracks but only %d frame offsets", trackTitles.size(), trackFrameOffsets.size()));
}
FrameOffsetsToTrackDurationsSeconds durations =
new FrameOffsetsToTrackDurationsSeconds(trackFrameOffsets.iterator(), disc.discLengthSeconds);
Iterator<TrackTitle> trackTitlesIter = trackTitles.values().iterator();
while (durations.hasNext()) {
// Adds tracks by their correct order
disc.tracks.add(new Track(trackTitlesIter.next(), durations.next()));
}
return disc;
}
|
diff --git a/test/src/com/socialize/test/ui/integrationtest/actionbutton/LikeButtonManualTest.java b/test/src/com/socialize/test/ui/integrationtest/actionbutton/LikeButtonManualTest.java
index f4f89ad1..ec976208 100644
--- a/test/src/com/socialize/test/ui/integrationtest/actionbutton/LikeButtonManualTest.java
+++ b/test/src/com/socialize/test/ui/integrationtest/actionbutton/LikeButtonManualTest.java
@@ -1,169 +1,169 @@
/*
* Copyright (c) 2012 Socialize Inc.
*
* 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 com.socialize.test.ui.integrationtest.actionbutton;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.TimeUnit;
import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.test.ActivityInstrumentationTestCase2;
import com.google.android.testing.mocking.AndroidMock;
import com.google.android.testing.mocking.UsesMocks;
import com.socialize.SocializeAccess;
import com.socialize.android.ioc.IOCContainer;
import com.socialize.android.ioc.ProxyObject;
import com.socialize.api.action.EntitySystem;
import com.socialize.api.action.LikeSystem;
import com.socialize.entity.Entity;
import com.socialize.entity.EntityStats;
import com.socialize.entity.Like;
import com.socialize.entity.SocializeAction;
import com.socialize.error.SocializeException;
import com.socialize.listener.SocializeInitListener;
import com.socialize.sample.EmptyActivity;
import com.socialize.sample.mocks.MockEntitySystem;
import com.socialize.sample.mocks.MockLikeSystem;
import com.socialize.sample.ui.ActionButtonActivity;
import com.socialize.test.ui.util.TestUtils;
import com.socialize.ui.actionbutton.ActionButtonHandler;
import com.socialize.ui.actionbutton.ActionButtonHandlers;
import com.socialize.ui.actionbutton.ActionButtonLayoutView;
import com.socialize.ui.actionbutton.SocializeActionButton;
import com.socialize.ui.actionbutton.SocializeActionButtonAccess;
/**
* @author Jason Polites
*
*/
public class LikeButtonManualTest extends ActivityInstrumentationTestCase2<EmptyActivity> {
public LikeButtonManualTest() {
super("com.socialize.sample.ui", EmptyActivity.class);
}
@Override
protected void setUp() throws Exception {
TestUtils.setUp(this);
super.setUp();
}
@Override
protected void tearDown() throws Exception {
TestUtils.tearDown();
super.tearDown();
}
@SuppressWarnings("unchecked")
@UsesMocks ({Entity.class, EntityStats.class, ActionButtonHandlers.class, ActionButtonHandler.class})
- public void testListButtonRenderAndClick() throws Throwable {
+ public void testLikeButtonRenderAndClick() throws Throwable {
TestUtils.setupSocializeOverrides(true, true);
TestUtils.setUpActivityMonitor(ActionButtonActivity.class);
final int likes = 69;
final Like action = new Like();
action.setId(100L);
final Entity entity = AndroidMock.createMock(Entity.class);
final EntityStats stats = AndroidMock.createMock(EntityStats.class);
- AndroidMock.expect(entity.getKey()).andReturn("foobar");
+ AndroidMock.expect(entity.getKey()).andReturn("foobar").times(2);
AndroidMock.expect(entity.getEntityStats()).andReturn(stats).times(2);
AndroidMock.expect(stats.getLikes()).andReturn(likes).times(2);
AndroidMock.replay(entity, stats);
action.setEntity(entity);
final MockLikeSystem mockLikeSystem = new MockLikeSystem();
final MockEntitySystem mockEntitySystem = new MockEntitySystem();
mockLikeSystem.setAction(action);
mockEntitySystem.setEntity(entity);
SocializeAccess.setInitListener(new SocializeInitListener() {
@Override
public void onError(SocializeException error) {
error.printStackTrace();
fail();
}
@Override
public void onInit(Context context, IOCContainer container) {
ProxyObject<LikeSystem> likeSystemProxy = container.getProxy("likeSystem");
ProxyObject<EntitySystem> entitySystemProxy = container.getProxy("entitySystem");
if(likeSystemProxy != null) {
likeSystemProxy.setDelegate(mockLikeSystem);
}
else {
System.err.println("likeSystemProxy is null!!");
}
if(entitySystemProxy != null) {
entitySystemProxy.setDelegate(mockEntitySystem);
}
else {
System.err.println("entitySystemProxy is null!!");
}
}
});
Intent intent = new Intent(getActivity(), ActionButtonActivity.class);
intent.putExtra("manual", true);
getActivity().startActivity(intent);
Activity activity = TestUtils.waitForActivity(5000);
assertNotNull(activity);
SocializeActionButton<SocializeAction> button = TestUtils.findViewWithText(activity, SocializeActionButton.class, "Superman (69)", 5000);
assertNotNull(button);
final ActionButtonLayoutView<SocializeAction> layoutView = SocializeActionButtonAccess.getLayoutView(button);
final CountDownLatch latch = new CountDownLatch(1);
// Click it
runTestOnUiThread(new Runnable() {
@Override
public void run() {
assertTrue(layoutView.performClick());
latch.countDown();
}
});
latch.await(5, TimeUnit.SECONDS);
button = TestUtils.findViewWithText(activity, SocializeActionButton.class, "Bizzaro (69)", 5000); // should be 68 but 69 because entity mock is the same
assertNotNull(button);
AndroidMock.verify(entity, stats);
}
}
| false | true | public void testListButtonRenderAndClick() throws Throwable {
TestUtils.setupSocializeOverrides(true, true);
TestUtils.setUpActivityMonitor(ActionButtonActivity.class);
final int likes = 69;
final Like action = new Like();
action.setId(100L);
final Entity entity = AndroidMock.createMock(Entity.class);
final EntityStats stats = AndroidMock.createMock(EntityStats.class);
AndroidMock.expect(entity.getKey()).andReturn("foobar");
AndroidMock.expect(entity.getEntityStats()).andReturn(stats).times(2);
AndroidMock.expect(stats.getLikes()).andReturn(likes).times(2);
AndroidMock.replay(entity, stats);
action.setEntity(entity);
final MockLikeSystem mockLikeSystem = new MockLikeSystem();
final MockEntitySystem mockEntitySystem = new MockEntitySystem();
mockLikeSystem.setAction(action);
mockEntitySystem.setEntity(entity);
SocializeAccess.setInitListener(new SocializeInitListener() {
@Override
public void onError(SocializeException error) {
error.printStackTrace();
fail();
}
@Override
public void onInit(Context context, IOCContainer container) {
ProxyObject<LikeSystem> likeSystemProxy = container.getProxy("likeSystem");
ProxyObject<EntitySystem> entitySystemProxy = container.getProxy("entitySystem");
if(likeSystemProxy != null) {
likeSystemProxy.setDelegate(mockLikeSystem);
}
else {
System.err.println("likeSystemProxy is null!!");
}
if(entitySystemProxy != null) {
entitySystemProxy.setDelegate(mockEntitySystem);
}
else {
System.err.println("entitySystemProxy is null!!");
}
}
});
Intent intent = new Intent(getActivity(), ActionButtonActivity.class);
intent.putExtra("manual", true);
getActivity().startActivity(intent);
Activity activity = TestUtils.waitForActivity(5000);
assertNotNull(activity);
SocializeActionButton<SocializeAction> button = TestUtils.findViewWithText(activity, SocializeActionButton.class, "Superman (69)", 5000);
assertNotNull(button);
final ActionButtonLayoutView<SocializeAction> layoutView = SocializeActionButtonAccess.getLayoutView(button);
final CountDownLatch latch = new CountDownLatch(1);
// Click it
runTestOnUiThread(new Runnable() {
@Override
public void run() {
assertTrue(layoutView.performClick());
latch.countDown();
}
});
latch.await(5, TimeUnit.SECONDS);
button = TestUtils.findViewWithText(activity, SocializeActionButton.class, "Bizzaro (69)", 5000); // should be 68 but 69 because entity mock is the same
assertNotNull(button);
AndroidMock.verify(entity, stats);
}
| public void testLikeButtonRenderAndClick() throws Throwable {
TestUtils.setupSocializeOverrides(true, true);
TestUtils.setUpActivityMonitor(ActionButtonActivity.class);
final int likes = 69;
final Like action = new Like();
action.setId(100L);
final Entity entity = AndroidMock.createMock(Entity.class);
final EntityStats stats = AndroidMock.createMock(EntityStats.class);
AndroidMock.expect(entity.getKey()).andReturn("foobar").times(2);
AndroidMock.expect(entity.getEntityStats()).andReturn(stats).times(2);
AndroidMock.expect(stats.getLikes()).andReturn(likes).times(2);
AndroidMock.replay(entity, stats);
action.setEntity(entity);
final MockLikeSystem mockLikeSystem = new MockLikeSystem();
final MockEntitySystem mockEntitySystem = new MockEntitySystem();
mockLikeSystem.setAction(action);
mockEntitySystem.setEntity(entity);
SocializeAccess.setInitListener(new SocializeInitListener() {
@Override
public void onError(SocializeException error) {
error.printStackTrace();
fail();
}
@Override
public void onInit(Context context, IOCContainer container) {
ProxyObject<LikeSystem> likeSystemProxy = container.getProxy("likeSystem");
ProxyObject<EntitySystem> entitySystemProxy = container.getProxy("entitySystem");
if(likeSystemProxy != null) {
likeSystemProxy.setDelegate(mockLikeSystem);
}
else {
System.err.println("likeSystemProxy is null!!");
}
if(entitySystemProxy != null) {
entitySystemProxy.setDelegate(mockEntitySystem);
}
else {
System.err.println("entitySystemProxy is null!!");
}
}
});
Intent intent = new Intent(getActivity(), ActionButtonActivity.class);
intent.putExtra("manual", true);
getActivity().startActivity(intent);
Activity activity = TestUtils.waitForActivity(5000);
assertNotNull(activity);
SocializeActionButton<SocializeAction> button = TestUtils.findViewWithText(activity, SocializeActionButton.class, "Superman (69)", 5000);
assertNotNull(button);
final ActionButtonLayoutView<SocializeAction> layoutView = SocializeActionButtonAccess.getLayoutView(button);
final CountDownLatch latch = new CountDownLatch(1);
// Click it
runTestOnUiThread(new Runnable() {
@Override
public void run() {
assertTrue(layoutView.performClick());
latch.countDown();
}
});
latch.await(5, TimeUnit.SECONDS);
button = TestUtils.findViewWithText(activity, SocializeActionButton.class, "Bizzaro (69)", 5000); // should be 68 but 69 because entity mock is the same
assertNotNull(button);
AndroidMock.verify(entity, stats);
}
|
diff --git a/src/main/java/com/heroku/gyoza/Main.java b/src/main/java/com/heroku/gyoza/Main.java
index 200625c..2ff1e21 100644
--- a/src/main/java/com/heroku/gyoza/Main.java
+++ b/src/main/java/com/heroku/gyoza/Main.java
@@ -1,26 +1,24 @@
package com.heroku.gyoza;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import com.sun.grizzly.http.SelectorThread;
import com.sun.jersey.api.container.grizzly.GrizzlyWebContainerFactory;
public class Main {
public static void main(String[] args) throws IOException {
final String baseUri = "http://localhost:"+(System.getenv("PORT")!=null?System.getenv("PORT"):"9998")+"/";
final Map<String, String> initParams = new HashMap<String, String>();
- initParams.put("com.sun.jersey.config.property.packages",
- "com.heroku.gyoza.resources");
+ initParams.put("com.sun.jersey.config.property.packages","com.heroku.gyoza.resources");
System.out.println("Starting grizzly...");
- SelectorThread threadSelector = GrizzlyWebContainerFactory.create(
- baseUri, initParams);
+ SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(
String.format(
- "Jersey started with WADL available at %sapplication.wadl. Try out %shelloworld",
- baseUri, baseUri));
+ "Jersey started with WADL available at %sapplication.wadl. Try out %shelloworld",
+ baseUri, baseUri));
}
}
| false | true | public static void main(String[] args) throws IOException {
final String baseUri = "http://localhost:"+(System.getenv("PORT")!=null?System.getenv("PORT"):"9998")+"/";
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages",
"com.heroku.gyoza.resources");
System.out.println("Starting grizzly...");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(
baseUri, initParams);
System.out.println(
String.format(
"Jersey started with WADL available at %sapplication.wadl. Try out %shelloworld",
baseUri, baseUri));
}
| public static void main(String[] args) throws IOException {
final String baseUri = "http://localhost:"+(System.getenv("PORT")!=null?System.getenv("PORT"):"9998")+"/";
final Map<String, String> initParams = new HashMap<String, String>();
initParams.put("com.sun.jersey.config.property.packages","com.heroku.gyoza.resources");
System.out.println("Starting grizzly...");
SelectorThread threadSelector = GrizzlyWebContainerFactory.create(baseUri, initParams);
System.out.println(
String.format(
"Jersey started with WADL available at %sapplication.wadl. Try out %shelloworld",
baseUri, baseUri));
}
|
diff --git a/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/RAStreamBufferMgr.java b/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/RAStreamBufferMgr.java
index 86bc0fd..001aafe 100644
--- a/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/RAStreamBufferMgr.java
+++ b/plugins/org.eclipse.birt.core/src/org/eclipse/birt/core/archive/RAStreamBufferMgr.java
@@ -1,136 +1,137 @@
/*******************************************************************************
* Copyright (c) 2004 Actuate Corporation.
* 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:
* Actuate Corporation - initial API and implementation
*******************************************************************************/
package org.eclipse.birt.core.archive;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.eclipse.birt.core.util.IOUtil;
public class RAStreamBufferMgr {
private RandomAccessFile randomFile;
// The total number of buffer has been allocated.
private int totalBuffer;
// An arraylist to keep the buffer in order.
// When MAX_NUMBER_OF_STREAM_BUFFER has been reached, we reuse the
// buffer from the beginning of the list. There is less chance they
// are going to be visited again.
private List bufferList = new ArrayList( IOUtil.MAX_NUMBER_OF_STREAM_BUFFER );
// A hash table to map between offset and buffer
private Map bufferMap = new HashMap();
// The buffer will be used for next operation
private RAStreamBuffer currentBuffer;
public RAStreamBufferMgr( RandomAccessFile randomFile ) throws IOException
{
this.randomFile = randomFile;
this.totalBuffer = 0;
this.currentBuffer = getBuffer( 0 );
}
/*
* The file pointer in the underlying file if no buffer is used.
*/
public long getFilePointer( )
{
return currentBuffer.getOffset() + currentBuffer.getBufCur();
}
/*
* Write the data in array b[], if current buffer is not enough to hold
* all the data, a new buffer will be allocated or an old buffer will
* be reused.
*/
public void write (byte b[], int off, int len ) throws IOException
{
while ( len > 0 )
{
int ret = currentBuffer.write( b, off, len );
len -= ret;
off += ret;
if ( len > 0)
currentBuffer = getBuffer( currentBuffer.getOffset()
+ IOUtil.RA_STREAM_BUFFER_LENGTH);
}
}
public void seek( long localPos ) throws IOException
{
long offset = ( localPos / IOUtil.RA_STREAM_BUFFER_LENGTH )
* IOUtil.RA_STREAM_BUFFER_LENGTH;
if ( currentBuffer.getOffset() != offset )
currentBuffer = getBuffer( offset );
currentBuffer.setBufCur( (int)(localPos - offset) );
}
/*
* Flush all the buffers
*/
public void flushBuffer() throws IOException
{
for ( int i = 0; i < totalBuffer; i++ )
{
RAStreamBuffer buffer = (RAStreamBuffer)bufferList.get(i);
buffer.flushBuffer();
}
}
/**
* Get next available buffer for the data from position offset.
* @param offset
* @return
* @throws IOException
*/
private RAStreamBuffer getBuffer( long offset ) throws IOException
{
// If we already have a buffer allocated for that offset, just
// return it.
- RAStreamBuffer buffer = (RAStreamBuffer)bufferMap.get( offset );
+ Long offsetKey = new Long(offset);
+ RAStreamBuffer buffer = (RAStreamBuffer)bufferMap.get( offsetKey );
if ( buffer != null )
return buffer;
// If not, and MAX_NUMBER_OF_STREAM_BUFFER has not been reached,
// allocate a new buffer for it.
if ( totalBuffer < IOUtil.MAX_NUMBER_OF_STREAM_BUFFER )
{
buffer = new RAStreamBuffer( this.randomFile );
buffer.resetBuffer( offset );
totalBuffer ++;
bufferList.add( buffer );
- bufferMap.put(offset, buffer);
+ bufferMap.put(offsetKey, buffer);
return buffer;
}
// If no buffer has been found, and MAX_NUMBER_OF_STREAM_BUFFER has
// been reached, reuse the buffer from the beginning of the list and
// put the buffer to the end of the list.
buffer = (RAStreamBuffer)bufferList.get( 0 );
buffer.flushBuffer();
- bufferMap.remove( buffer.getOffset());
+ bufferMap.remove( new Long(buffer.getOffset()) );
buffer.resetBuffer( offset );
- bufferMap.put( offset, buffer);
+ bufferMap.put( offsetKey, buffer);
bufferList.remove( 0 );
bufferList.add( buffer );
return buffer;
}
}
| false | true | private RAStreamBuffer getBuffer( long offset ) throws IOException
{
// If we already have a buffer allocated for that offset, just
// return it.
RAStreamBuffer buffer = (RAStreamBuffer)bufferMap.get( offset );
if ( buffer != null )
return buffer;
// If not, and MAX_NUMBER_OF_STREAM_BUFFER has not been reached,
// allocate a new buffer for it.
if ( totalBuffer < IOUtil.MAX_NUMBER_OF_STREAM_BUFFER )
{
buffer = new RAStreamBuffer( this.randomFile );
buffer.resetBuffer( offset );
totalBuffer ++;
bufferList.add( buffer );
bufferMap.put(offset, buffer);
return buffer;
}
// If no buffer has been found, and MAX_NUMBER_OF_STREAM_BUFFER has
// been reached, reuse the buffer from the beginning of the list and
// put the buffer to the end of the list.
buffer = (RAStreamBuffer)bufferList.get( 0 );
buffer.flushBuffer();
bufferMap.remove( buffer.getOffset());
buffer.resetBuffer( offset );
bufferMap.put( offset, buffer);
bufferList.remove( 0 );
bufferList.add( buffer );
return buffer;
}
| private RAStreamBuffer getBuffer( long offset ) throws IOException
{
// If we already have a buffer allocated for that offset, just
// return it.
Long offsetKey = new Long(offset);
RAStreamBuffer buffer = (RAStreamBuffer)bufferMap.get( offsetKey );
if ( buffer != null )
return buffer;
// If not, and MAX_NUMBER_OF_STREAM_BUFFER has not been reached,
// allocate a new buffer for it.
if ( totalBuffer < IOUtil.MAX_NUMBER_OF_STREAM_BUFFER )
{
buffer = new RAStreamBuffer( this.randomFile );
buffer.resetBuffer( offset );
totalBuffer ++;
bufferList.add( buffer );
bufferMap.put(offsetKey, buffer);
return buffer;
}
// If no buffer has been found, and MAX_NUMBER_OF_STREAM_BUFFER has
// been reached, reuse the buffer from the beginning of the list and
// put the buffer to the end of the list.
buffer = (RAStreamBuffer)bufferList.get( 0 );
buffer.flushBuffer();
bufferMap.remove( new Long(buffer.getOffset()) );
buffer.resetBuffer( offset );
bufferMap.put( offsetKey, buffer);
bufferList.remove( 0 );
bufferList.add( buffer );
return buffer;
}
|
diff --git a/play-platformservices-core/src/main/java/eu/play_project/play_platformservices/PlayPlatformservices.java b/play-platformservices-core/src/main/java/eu/play_project/play_platformservices/PlayPlatformservices.java
index deb200ad..2e1296af 100644
--- a/play-platformservices-core/src/main/java/eu/play_project/play_platformservices/PlayPlatformservices.java
+++ b/play-platformservices-core/src/main/java/eu/play_project/play_platformservices/PlayPlatformservices.java
@@ -1,287 +1,291 @@
package eu.play_project.play_platformservices;
import java.io.Serializable;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import javax.jws.WebService;
import javax.ws.rs.ProcessingException;
import javax.xml.ws.Endpoint;
import org.objectweb.fractal.api.NoSuchInterfaceException;
import org.objectweb.fractal.api.control.BindingController;
import org.objectweb.fractal.api.control.IllegalBindingException;
import org.objectweb.fractal.api.control.IllegalLifeCycleException;
import org.objectweb.proactive.Body;
import org.objectweb.proactive.core.component.body.ComponentEndActive;
import org.objectweb.proactive.core.component.body.ComponentInitActive;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.hp.hpl.jena.query.Query;
import com.hp.hpl.jena.query.QueryException;
import com.hp.hpl.jena.query.QueryFactory;
import com.hp.hpl.jena.query.Syntax;
import com.hp.hpl.jena.sparql.serializer.PlaySerializer;
import eu.play_platform.platformservices.bdpl.syntax.windows.visitor.ElementWindowVisitor;
import eu.play_project.dcep.api.DcepManagementException;
import eu.play_project.dcep.api.DcepManagmentApi;
import eu.play_project.play_commons.constants.Constants;
import eu.play_project.play_platformservices.api.BdplQuery;
import eu.play_project.play_platformservices.api.QueryDetails;
import eu.play_project.play_platformservices.api.QueryDispatchApi;
import eu.play_project.play_platformservices.api.QueryDispatchException;
import eu.play_project.play_platformservices_querydispatcher.api.EleGenerator;
import eu.play_project.play_platformservices_querydispatcher.bdpl.code_generator.realtime.EleGeneratorForConstructQuery;
import eu.play_project.play_platformservices_querydispatcher.bdpl.visitor.historic.QueryTemplateGenerator;
import eu.play_project.play_platformservices_querydispatcher.bdpl.visitor.realtime.ComplexTypeFinder;
import eu.play_project.play_platformservices_querydispatcher.bdpl.visitor.realtime.StreamIdCollector;
import eu.play_project.play_platformservices_querydispatcher.bdpl.visitor.realtime.WindowVisitor;
@WebService(
serviceName = "QueryDispatchApi",
portName = "QueryDispatchApiPort",
endpointInterface = "eu.play_project.play_platformservices.api.QueryDispatchApi")
public class PlayPlatformservices implements QueryDispatchApi,
ComponentInitActive, ComponentEndActive, BindingController,
Serializable {
private static final long serialVersionUID = 100L;
private EleGenerator eleGenerator;
private DcepManagmentApi dcepManagmentApi;
private boolean init = false;
private Logger logger;
private Endpoint soapServer;
private PlayPlatformservicesRest restServer;
@Override
public String[] listFc() {
return new String[] { "DcepManagmentApi" };
}
@Override
public Object lookupFc(String clientItfName) throws NoSuchInterfaceException {
if ("DcepManagmentApi".equals(clientItfName)) {
return dcepManagmentApi;
} else {
throw new NoSuchInterfaceException("DcepManagmentApi");
}
}
@Override
public void bindFc(String clientItfName, Object serverItf) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException {
if (clientItfName.equals("DcepManagmentApi")) {
dcepManagmentApi = (DcepManagmentApi) serverItf;
}
else {
throw new NoSuchInterfaceException(String.format("Interface '%s' not available at '%s'.", clientItfName, this.getClass().getSimpleName()));
}
}
@Override
public void unbindFc(String clientItfName) throws NoSuchInterfaceException, IllegalBindingException, IllegalLifeCycleException {
if (clientItfName.equals("DcepManagmentApi")) {
// do nothing, currently
}
else {
throw new NoSuchInterfaceException(String.format("Interface '%s' not available at '%s'.", clientItfName, this.getClass().getSimpleName()));
}
}
@Override
public void initComponentActivity(Body body) {
if (!init) {
this.logger = LoggerFactory.getLogger(this.getClass());
logger.info("Initialising {} component.", this.getClass().getSimpleName());
eleGenerator = new EleGeneratorForConstructQuery();
- // Provide PublishApi as SOAP Webservice
+ /*
+ * Provide PublishApi as SOAP Webservice
+ */
try {
String address = Constants.getProperties().getProperty("platfomservices.querydispatchapi.endpoint");
soapServer = Endpoint.publish(address, this);
logger.info("QueryDispatch SOAP service started at {}.", address);
} catch (Exception e) {
logger.error("Exception while publishing QueryDispatch SOAP Service", e);
}
- // Provide PublishApi as REST Webservice
+ /*
+ * Provide PublishApi as REST Webservice
+ */
try {
restServer = new PlayPlatformservicesRest(this);
- logger.info(String.format("QueryDispatch REST service started with WADL available at "
- + "%sapplication.wadl\n", PlayPlatformservicesRest.BASE_URI));
+ logger.info(String.format("QueryDispatch REST service started at %s with WADL remotely available at "
+ + "%sapplication.wadl\n", PlayPlatformservicesRest.BASE_URI, Constants.getProperties().getProperty("platfomservices.querydispatchapi.rest")));
} catch (ProcessingException e) {
logger.error("Exception while publishing QueryDispatch REST Service", e);
}
this.init = true;
}
}
@Override
public void endComponentActivity(Body arg0) {
logger.info("Terminating {} component.", this.getClass().getSimpleName());
if (this.soapServer != null) {
this.soapServer.stop();
}
if (this.restServer != null) {
this.restServer.destroy();
}
this.init = false;
}
@Override
public synchronized String registerQuery(String queryId, String query) throws QueryDispatchException {
if (!init) {
throw new IllegalStateException("Component not initialized: "
+ this.getClass().getSimpleName());
}
BdplQuery epQuery = createCepQuery(queryId, query);
try {
dcepManagmentApi.registerEventPattern(epQuery);
} catch (Exception e) {
logger.error("Error while registering query: " + queryId, e);
throw new QueryDispatchException(String.format("Error while registering query ID '%s': %s", queryId, e.getMessage()));
}
return queryId;
}
private BdplQuery createCepQuery(String queryId, String query)
throws QueryDispatchException {
// Parse query
Query q;
try {
q = QueryFactory.create(query, Syntax.syntaxBDPL);
} catch (com.hp.hpl.jena.query.QueryException e) {
throw new QueryDispatchException(e.getMessage());
}
// Generate CEP-language
eleGenerator.setPatternId(queryId);
eleGenerator.generateQuery(q);
logger.info("Registering query with ID " + queryId);
// Add queryDetails
QueryDetails qd = this.createQueryDetails(queryId, q);
qd.setRdfDbQueries(eleGenerator.getRdfDbQueries());
BdplQuery bdpl = BdplQuery.builder()
.details(qd)
.ele(eleGenerator.getEle())
.historicalQueries(PlaySerializer.serializeToMultipleSelectQueries(q))
.constructTemplate(new QueryTemplateGenerator().createQueryTemplate(q))
.bdpl(query)
.build();
return bdpl;
}
@Override
public void unregisterQuery(String queryId) {
if (!init) {
throw new IllegalStateException("Component not initialized: "
+ this.getClass().getSimpleName());
}
logger.info("Unregistering query " + queryId);
this.dcepManagmentApi.unregisterEventPattern(queryId);
}
@Override
public QueryDetails analyseQuery(String queryId, String query) throws QueryDispatchException {
if (!init) {
throw new IllegalStateException("Component not initialized: "
+ this.getClass().getSimpleName());
}
// Parse query
try {
Query q = QueryFactory.create(query, com.hp.hpl.jena.query.Syntax.syntaxBDPL);
return createQueryDetails(queryId, q);
}
catch (QueryException e) {
throw new QueryDispatchException(e.getMessage());
}
}
private QueryDetails createQueryDetails(String queryId, Query query) throws QueryDispatchException {
if (!init) {
throw new IllegalStateException("Component not initialized: " + this.getClass().getSimpleName());
}
logger.info("Analysing query with ID " + queryId);
QueryDetails qd = new QueryDetails(queryId);
// Set properties for windows in QueryDetails
ElementWindowVisitor windowVisitor = new WindowVisitor(qd);
query.getWindow().accept(windowVisitor);
// Check if id is alredy used.
if (dcepManagmentApi != null && dcepManagmentApi.getRegisteredEventPatterns().containsKey(queryId)) {
throw new QueryDispatchException("Query ID is alread used: " + queryId);
}
// Set stream ids in QueryDetails.
StreamIdCollector streamIdCollector = new StreamIdCollector();
streamIdCollector.getStreamIds(query, qd);
// Set complex event type.
qd.setComplexType((new ComplexTypeFinder()).visit(query.getConstructTemplate()));
return qd;
}
@Override
public eu.play_project.play_platformservices.jaxb.Query getRegisteredQuery(String queryId)
throws QueryDispatchException {
if (!init) {
throw new IllegalStateException("Component not initialized: "
+ this.getClass().getSimpleName());
}
try {
return new eu.play_project.play_platformservices.jaxb.Query(
this.dcepManagmentApi.getRegisteredEventPattern(queryId));
} catch (DcepManagementException e) {
throw new QueryDispatchException(e.getMessage());
}
}
@Override
public List<eu.play_project.play_platformservices.jaxb.Query> getRegisteredQueries() {
if (!init) {
throw new IllegalStateException("Component not initialized: "
+ this.getClass().getSimpleName());
}
List<eu.play_project.play_platformservices.jaxb.Query> results = new ArrayList<eu.play_project.play_platformservices.jaxb.Query>();
Map<String, BdplQuery> queries = dcepManagmentApi
.getRegisteredEventPatterns();
for (String queryId : queries.keySet()) {
results.add(new eu.play_project.play_platformservices.jaxb.Query(queries.get(queryId)));
}
return results;
}
}
| false | true | public void initComponentActivity(Body body) {
if (!init) {
this.logger = LoggerFactory.getLogger(this.getClass());
logger.info("Initialising {} component.", this.getClass().getSimpleName());
eleGenerator = new EleGeneratorForConstructQuery();
// Provide PublishApi as SOAP Webservice
try {
String address = Constants.getProperties().getProperty("platfomservices.querydispatchapi.endpoint");
soapServer = Endpoint.publish(address, this);
logger.info("QueryDispatch SOAP service started at {}.", address);
} catch (Exception e) {
logger.error("Exception while publishing QueryDispatch SOAP Service", e);
}
// Provide PublishApi as REST Webservice
try {
restServer = new PlayPlatformservicesRest(this);
logger.info(String.format("QueryDispatch REST service started with WADL available at "
+ "%sapplication.wadl\n", PlayPlatformservicesRest.BASE_URI));
} catch (ProcessingException e) {
logger.error("Exception while publishing QueryDispatch REST Service", e);
}
this.init = true;
}
}
| public void initComponentActivity(Body body) {
if (!init) {
this.logger = LoggerFactory.getLogger(this.getClass());
logger.info("Initialising {} component.", this.getClass().getSimpleName());
eleGenerator = new EleGeneratorForConstructQuery();
/*
* Provide PublishApi as SOAP Webservice
*/
try {
String address = Constants.getProperties().getProperty("platfomservices.querydispatchapi.endpoint");
soapServer = Endpoint.publish(address, this);
logger.info("QueryDispatch SOAP service started at {}.", address);
} catch (Exception e) {
logger.error("Exception while publishing QueryDispatch SOAP Service", e);
}
/*
* Provide PublishApi as REST Webservice
*/
try {
restServer = new PlayPlatformservicesRest(this);
logger.info(String.format("QueryDispatch REST service started at %s with WADL remotely available at "
+ "%sapplication.wadl\n", PlayPlatformservicesRest.BASE_URI, Constants.getProperties().getProperty("platfomservices.querydispatchapi.rest")));
} catch (ProcessingException e) {
logger.error("Exception while publishing QueryDispatch REST Service", e);
}
this.init = true;
}
}
|
diff --git a/src/evolution/binPacking/Checker.java b/src/evolution/binPacking/Checker.java
index 72351b3..4a13d59 100644
--- a/src/evolution/binPacking/Checker.java
+++ b/src/evolution/binPacking/Checker.java
@@ -1,49 +1,49 @@
package evolution.binPacking;
import java.io.BufferedReader;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.util.Scanner;
public class Checker {
public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
double[] vahy = new double[10];
String line;
while ((line = in.readLine()) != null) {
- Scanner lineScanner = new Scanner(line);
- lineScanner.useDelimiter(" ");
+ String[] nums = line.split(" ");
- double weight = lineScanner.nextDouble();
- int bin = lineScanner.nextInt();
+ double weight = Double.parseDouble(nums[0]);
+ int bin = Integer.parseInt(nums[1]);
vahy[bin] += weight;
}
double min = Integer.MAX_VALUE;
double max = Integer.MIN_VALUE;
for (int i = 0; i < 10; i++) {
min = Math.min(vahy[i], min);
max = Math.max(vahy[i], max);
System.out.println("" + i + ": " + vahy[i]);
}
System.out.println("difference: " + (max - min));
+ in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
| false | true | public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
double[] vahy = new double[10];
String line;
while ((line = in.readLine()) != null) {
Scanner lineScanner = new Scanner(line);
lineScanner.useDelimiter(" ");
double weight = lineScanner.nextDouble();
int bin = lineScanner.nextInt();
vahy[bin] += weight;
}
double min = Integer.MAX_VALUE;
double max = Integer.MIN_VALUE;
for (int i = 0; i < 10; i++) {
min = Math.min(vahy[i], min);
max = Math.max(vahy[i], max);
System.out.println("" + i + ": " + vahy[i]);
}
System.out.println("difference: " + (max - min));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
| public static void main(String[] args) {
try {
BufferedReader in = new BufferedReader(new FileReader(args[0]));
double[] vahy = new double[10];
String line;
while ((line = in.readLine()) != null) {
String[] nums = line.split(" ");
double weight = Double.parseDouble(nums[0]);
int bin = Integer.parseInt(nums[1]);
vahy[bin] += weight;
}
double min = Integer.MAX_VALUE;
double max = Integer.MIN_VALUE;
for (int i = 0; i < 10; i++) {
min = Math.min(vahy[i], min);
max = Math.max(vahy[i], max);
System.out.println("" + i + ": " + vahy[i]);
}
System.out.println("difference: " + (max - min));
in.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
|
diff --git a/src/org/eclipse/core/internal/resources/WorkManager.java b/src/org/eclipse/core/internal/resources/WorkManager.java
index 9dd0edc4..83dea1de 100644
--- a/src/org/eclipse/core/internal/resources/WorkManager.java
+++ b/src/org/eclipse/core/internal/resources/WorkManager.java
@@ -1,278 +1,278 @@
/*******************************************************************************
* Copyright (c) 2000, 2002 IBM Corporation and others.
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Common Public License v0.5
* which accompanies this distribution, and is available at
* http://www.eclipse.org/legal/cpl-v05.html
*
* Contributors:
* IBM - Initial API and implementation
******************************************************************************/
package org.eclipse.core.internal.resources;
import java.util.Hashtable;
import org.eclipse.core.resources.WorkspaceLock;
import org.eclipse.core.runtime.CoreException;
import org.eclipse.core.runtime.IProgressMonitor;
import org.eclipse.core.internal.utils.*;
//
public class WorkManager implements IManager {
protected int currentOperationId;
// we use a Hashtable for the identifiers to avoid concurrency problems
protected Hashtable identifiers;
protected int nextId;
protected Workspace workspace;
protected WorkspaceLock workspaceLock;
protected Queue operations;
protected Thread currentOperationThread;
class Identifier {
int operationId = OPERATION_EMPTY;
int preparedOperations = 0;
int nestedOperations = 0;
// Indication for running auto build. It is computated based
// on the parameters passed to Workspace.endOperation().
boolean shouldBuild = false;
// Enables or disables a condition based on the shouldBuild field.
boolean avoidAutoBuild = false;
boolean operationCanceled = false;
}
public static final int OPERATION_NONE = -1;
public static final int OPERATION_EMPTY = 0;
public WorkManager(Workspace workspace) {
currentOperationId = OPERATION_NONE;
identifiers = new Hashtable(10);
nextId = 0;
this.workspace = workspace;
operations = new Queue();
}
/**
* Returns null if acquired and a Semaphore object otherwise.
*/
public synchronized Semaphore acquire() {
if (isCurrentOperation())
return null;
if (currentOperationId == OPERATION_NONE && operations.isEmpty()) {
updateCurrentOperation(getOperationId());
return null;
}
return enqueue(new Semaphore(Thread.currentThread()));
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void avoidAutoBuild() {
getIdentifier(currentOperationThread).avoidAutoBuild = true;
}
/**
* An operation calls this method and it only returns when the operation
* is free to run.
*/
public void checkIn() throws CoreException {
try {
- boolean acquired = false;
- while (!acquired) {
+ while (true) {
try {
- acquired = getWorkspaceLock().acquire();
+ if (getWorkspaceLock().acquire())
+ return;
//above call should block, but sleep just in case it doesn't behave
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
/**
* Inform that an operation has finished.
*/
public synchronized void checkOut() throws CoreException {
decrementPreparedOperations();
rebalanceNestedOperations();
// if this is a nested operation, just return
// and do not release the lock
if (getPreparedOperationDepth() > 0)
return;
getWorkspaceLock().release();
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
private void decrementPreparedOperations() {
getIdentifier(currentOperationThread).preparedOperations--;
}
/**
* If there is another semaphore with the same runnable in the
* queue, the other is returned and the new one is not added.
*/
private synchronized Semaphore enqueue(Semaphore newSemaphore) {
Semaphore semaphore = (Semaphore) operations.get(newSemaphore);
if (semaphore == null) {
operations.add(newSemaphore);
return newSemaphore;
}
return semaphore;
}
public synchronized Thread getCurrentOperationThread() {
return currentOperationThread;
}
private Identifier getIdentifier(Thread key) {
Assert.isNotNull(key, "The thread should never be null.");//$NON-NLS-1$
Identifier identifier = (Identifier) identifiers.get(key);
if (identifier == null) {
identifier = getNewIdentifier();
identifiers.put(key, identifier);
}
return identifier;
}
private Identifier getNewIdentifier() {
Identifier identifier = new Identifier();
identifier.operationId = getNextOperationId();
return identifier;
}
private int getNextOperationId() {
return ++nextId;
}
private int getOperationId() {
return getIdentifier(Thread.currentThread()).operationId;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public int getPreparedOperationDepth() {
return getIdentifier(currentOperationThread).preparedOperations;
}
private WorkspaceLock getWorkspaceLock() throws CoreException {
if (workspaceLock == null)
workspaceLock = workspaceLock = new WorkspaceLock(workspace);
return workspaceLock;
}
/**
* Returns true if the nested operation depth is the same
* as the prepared operation depth, and false otherwise.
*
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
boolean isBalanced() {
Identifier identifier = getIdentifier(currentOperationThread);
return identifier.nestedOperations == identifier.preparedOperations;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
void incrementNestedOperations() {
getIdentifier(currentOperationThread).nestedOperations++;
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
private void incrementPreparedOperations() {
getIdentifier(currentOperationThread).preparedOperations++;
}
/**
* This method is synchronized with checkIn() and checkOut() that use blocks
* like synchronized (this) { ... }.
*/
public synchronized boolean isCurrentOperation() {
return currentOperationId == getOperationId();
}
public synchronized boolean isNextOperation(Runnable runnable) {
Semaphore next = (Semaphore) operations.peek();
return (next != null) && (next.getRunnable() == runnable);
}
/**
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void operationCanceled() {
getIdentifier(currentOperationThread).operationCanceled = true;
}
/**
* Used to make things stable again after an operation has failed between
* a workspace.prepareOperation() and workspace.beginOperation().
*
* This method can only be safelly called from inside a workspace
* operation. Should NOT be called from outside a
* prepareOperation/endOperation block.
*/
public void rebalanceNestedOperations() {
Identifier identifier = getIdentifier(currentOperationThread);
identifier.nestedOperations = identifier.preparedOperations;
}
public synchronized void release() {
resetOperationId();
Semaphore next = (Semaphore) operations.peek();
updateCurrentOperation(OPERATION_NONE);
if (next != null)
next.release();
}
private void resetOperationId() {
// ensure the operation cache on this thread is null
identifiers.remove(currentOperationThread);
}
/**
* This method can only be safely called from inside a workspace operation.
* Should NOT be called from outside a prepareOperation/endOperation block.
*/
public void setBuild(boolean build) {
Identifier identifier = getIdentifier(currentOperationThread);
if (identifier.preparedOperations == identifier.nestedOperations)
identifier.shouldBuild = (identifier.shouldBuild || build);
}
public void setWorkspaceLock(WorkspaceLock lock) {
//if (workspaceLock != null)
//return;
Assert.isNotNull(lock);
workspaceLock = lock;
}
/**
* This method can only be safely called from inside a workspace operation.
* Should NOT be called from outside a prepareOperation/endOperation block.
*/
public boolean shouldBuild() {
Identifier identifier = getIdentifier(currentOperationThread);
if (!identifier.avoidAutoBuild && identifier.shouldBuild) {
if (identifier.operationCanceled)
return Policy.buildOnCancel;
return true;
}
return false;
}
public void shutdown(IProgressMonitor monitor) {
currentOperationId = OPERATION_NONE;
identifiers = null;
nextId = 0;
}
public void startup(IProgressMonitor monitor) {
}
public synchronized void updateCurrentOperation() {
operations.remove();
updateCurrentOperation(getOperationId());
}
private void updateCurrentOperation(int newID) {
currentOperationId = newID;
if (newID == OPERATION_NONE)
currentOperationThread = null;
else
currentOperationThread = Thread.currentThread();
}
public boolean isTreeLocked() {
return workspace.isTreeLocked();
}
}
| false | true | public void checkIn() throws CoreException {
try {
boolean acquired = false;
while (!acquired) {
try {
acquired = getWorkspaceLock().acquire();
//above call should block, but sleep just in case it doesn't behave
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
| public void checkIn() throws CoreException {
try {
while (true) {
try {
if (getWorkspaceLock().acquire())
return;
//above call should block, but sleep just in case it doesn't behave
Thread.sleep(50);
} catch (InterruptedException e) {
}
}
} finally {
incrementPreparedOperations();
}
}
|
diff --git a/src/main/java/net/aufdemrand/denizen/tags/TagManager.java b/src/main/java/net/aufdemrand/denizen/tags/TagManager.java
index 21f16cfd6..3e7c70c51 100644
--- a/src/main/java/net/aufdemrand/denizen/tags/TagManager.java
+++ b/src/main/java/net/aufdemrand/denizen/tags/TagManager.java
@@ -1,201 +1,201 @@
package net.aufdemrand.denizen.tags;
import net.aufdemrand.denizen.Denizen;
import net.aufdemrand.denizen.events.bukkit.ReplaceableTagEvent;
import net.aufdemrand.denizen.objects.ObjectFetcher;
import net.aufdemrand.denizen.objects.dNPC;
import net.aufdemrand.denizen.objects.dObject;
import net.aufdemrand.denizen.objects.dPlayer;
import net.aufdemrand.denizen.scripts.ScriptEntry;
import net.aufdemrand.denizen.tags.core.*;
import net.aufdemrand.denizen.utilities.debugging.dB;
import org.bukkit.Bukkit;
import org.bukkit.event.EventHandler;
import org.bukkit.event.Listener;
import java.util.ArrayList;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
/**
* Calls a bukkit event for replaceable tags.
*
* @author Jeremy Schroeder
*
*/
public class TagManager implements Listener {
public Denizen denizen;
public TagManager(Denizen denizen) {
this.denizen = denizen;
}
public void registerCoreTags() {
new PlayerTags(denizen);
new NPCTags(denizen);
new LocationTags(denizen);
new UtilTags(denizen);
new ProcedureScriptTag(denizen);
new ContextTags(denizen);
new TextTags(denizen);
// For compatibility
new AnchorTags(denizen);
new FlagTags(denizen);
new ConstantTags(denizen);
new NotableLocationTags(denizen);
denizen.getServer().getPluginManager().registerEvents(this, denizen);
}
@EventHandler
public void fetchObject(ReplaceableTagEvent event) {
if (!event.getName().contains("@")) return;
String object_type = event.getName().split("@")[0].toLowerCase();
Class object_class = ObjectFetcher.getObjectClass(object_type);
if (object_class == null) {
dB.echoError("Invalid object type! Could not fetch '" + object_type + "'!");
event.setReplaced("null");
return;
}
dObject arg;
try {
if (!ObjectFetcher.checkMatch(object_class, event.hasNameContext() ? event.getName() + '[' + event.getNameContext() + ']'
: event.getName())) {
dB.echoDebug(event.getScriptEntry(), "Returning null. '" + event.getName()
+ "' is an invalid " + object_class.getSimpleName() + ".");
event.setReplaced("null");
return;
}
arg = ObjectFetcher.getObjectFrom(object_class, event.hasNameContext() ? event.getName() + '[' + event.getNameContext() + ']'
: event.getName());
if (arg == null) {
dB.echoError((event.hasNameContext() ? event.getName() + '[' + event.getNameContext() + ']'
: event.getName() + " is an invalid dObject!"));
return;
}
Attribute attribute = new Attribute(event.raw_tag, event.getScriptEntry());
event.setReplaced(arg.getAttribute(attribute.fulfill(1)));
} catch (Exception e) {
dB.echoError("Uh oh! Report this to aufdemrand! Err: TagManagerObjectReflection");
e.printStackTrace();
}
}
public static String tag(dPlayer player, dNPC npc, String arg) {
return tag(player, npc, arg, false, null);
}
public static String tag(dPlayer player, dNPC npc, String arg, boolean instant) {
return tag(player, npc, arg, instant, null);
}
public static String tag(dPlayer player, dNPC npc, String arg, boolean instant, ScriptEntry scriptEntry) {
if (arg == null) return null;
// confirm there are/is a replaceable TAG(s), if not, return the arg.
if (arg.indexOf('>') == -1 || arg.length() < 3) return arg;
// Find location of the first tag
int[] positions = locateTag(arg);
if (positions == null) {
// Un-escape \<, \>
if (!instant) arg = arg.replace("\\<", "<").replace("\\>", ">");
return arg;
}
int failsafe = 0;
do {
// Just in case, do-loops make me nervous, but does implement a limit of 25 tags per argument.
failsafe++;
ReplaceableTagEvent event;
if (positions == null) break;
else {
event = new ReplaceableTagEvent(player, npc, arg.substring(positions[0] + 1, positions[1]), scriptEntry);
if (event.isInstant() != instant) {
// Not the right type of tag, change out brackets so it doesn't get parsed again
arg = arg.substring(0, positions[0]) + String.valueOf((char)0x01)
- + event.getReplaced() + String.valueOf((char)0x02) + arg.substring(positions[1] + 1, arg.length());
+ + event.getReplaced().replace('|', (char)0x05) + String.valueOf((char)0x02) + arg.substring(positions[1] + 1, arg.length());
} else {
// Call Event
Bukkit.getServer().getPluginManager().callEvent(event);
if ((!event.replaced() && event.getAlternative() != null)
|| (event.getReplaced().equals("null") && event.getAlternative() != null))
event.setReplaced(event.getAlternative());
- arg = arg.substring(0, positions[0]) + event.getReplaced() + arg.substring(positions[1] + 1, arg.length());
+ arg = arg.substring(0, positions[0]) + event.getReplaced().replace('|', (char)0x05) + arg.substring(positions[1] + 1, arg.length());
}
}
// Find new TAG
positions = locateTag(arg);
} while (positions != null || failsafe < 50);
// Return argument with replacements
- arg = arg.replace((char)0x01, '<').replace((char)0x02, '>');
+ arg = arg.replace((char)0x01, '<').replace((char)0x02, '>').replace((char)0x05, '|');
// Un-escape \< \>'s
if (!instant) arg = arg.replace("\\<", "<").replace("\\>", ">");
return arg;
}
// Match all < > brackets that don't contain < > inside them
private static Pattern tagRegex = Pattern.compile("<([^<>]+)>");
private static int[] locateTag(String arg) {
// find escaped brackets
arg = arg.replace("\\<", " ")
.replace("\\>", " ");
// find tag brackets pattern
Matcher tagMatcher = tagRegex.matcher(arg);
if (tagMatcher.find())
return new int[]{tagMatcher.start(), tagMatcher.end() - 1};
// no matching brackets pattern, return null
else return null;
}
public static List<String> fillArguments(List<String> args, ScriptEntry scriptEntry) {
return fillArguments(args, scriptEntry, false);
}
public static List<String> fillArguments(List<String> args, ScriptEntry scriptEntry, boolean instant) {
List<String> filledArgs = new ArrayList<String>();
int nested_level = 0;
if (args != null) {
for (String argument : args) {
// Check nested level to avoid filling tags prematurely.
if (argument.equals("{")) nested_level++;
if (argument.equals("}")) nested_level--;
// If this argument isn't nested, fill the tag.
if (nested_level < 1) {
filledArgs.add(tag(scriptEntry.getPlayer(), scriptEntry.getNPC(), argument, instant, scriptEntry));
}
else filledArgs.add(argument);
}
}
return filledArgs;
}
public static List<String> fillArguments(String[] args, dPlayer player, dNPC npc) {
List<String> filledArgs = new ArrayList<String>();
if (args != null) {
for (String argument : args) {
filledArgs.add(tag(player, npc, argument, false));
}
}
return filledArgs;
}
}
| false | true | public static String tag(dPlayer player, dNPC npc, String arg, boolean instant, ScriptEntry scriptEntry) {
if (arg == null) return null;
// confirm there are/is a replaceable TAG(s), if not, return the arg.
if (arg.indexOf('>') == -1 || arg.length() < 3) return arg;
// Find location of the first tag
int[] positions = locateTag(arg);
if (positions == null) {
// Un-escape \<, \>
if (!instant) arg = arg.replace("\\<", "<").replace("\\>", ">");
return arg;
}
int failsafe = 0;
do {
// Just in case, do-loops make me nervous, but does implement a limit of 25 tags per argument.
failsafe++;
ReplaceableTagEvent event;
if (positions == null) break;
else {
event = new ReplaceableTagEvent(player, npc, arg.substring(positions[0] + 1, positions[1]), scriptEntry);
if (event.isInstant() != instant) {
// Not the right type of tag, change out brackets so it doesn't get parsed again
arg = arg.substring(0, positions[0]) + String.valueOf((char)0x01)
+ event.getReplaced() + String.valueOf((char)0x02) + arg.substring(positions[1] + 1, arg.length());
} else {
// Call Event
Bukkit.getServer().getPluginManager().callEvent(event);
if ((!event.replaced() && event.getAlternative() != null)
|| (event.getReplaced().equals("null") && event.getAlternative() != null))
event.setReplaced(event.getAlternative());
arg = arg.substring(0, positions[0]) + event.getReplaced() + arg.substring(positions[1] + 1, arg.length());
}
}
// Find new TAG
positions = locateTag(arg);
} while (positions != null || failsafe < 50);
// Return argument with replacements
arg = arg.replace((char)0x01, '<').replace((char)0x02, '>');
// Un-escape \< \>'s
if (!instant) arg = arg.replace("\\<", "<").replace("\\>", ">");
return arg;
}
| public static String tag(dPlayer player, dNPC npc, String arg, boolean instant, ScriptEntry scriptEntry) {
if (arg == null) return null;
// confirm there are/is a replaceable TAG(s), if not, return the arg.
if (arg.indexOf('>') == -1 || arg.length() < 3) return arg;
// Find location of the first tag
int[] positions = locateTag(arg);
if (positions == null) {
// Un-escape \<, \>
if (!instant) arg = arg.replace("\\<", "<").replace("\\>", ">");
return arg;
}
int failsafe = 0;
do {
// Just in case, do-loops make me nervous, but does implement a limit of 25 tags per argument.
failsafe++;
ReplaceableTagEvent event;
if (positions == null) break;
else {
event = new ReplaceableTagEvent(player, npc, arg.substring(positions[0] + 1, positions[1]), scriptEntry);
if (event.isInstant() != instant) {
// Not the right type of tag, change out brackets so it doesn't get parsed again
arg = arg.substring(0, positions[0]) + String.valueOf((char)0x01)
+ event.getReplaced().replace('|', (char)0x05) + String.valueOf((char)0x02) + arg.substring(positions[1] + 1, arg.length());
} else {
// Call Event
Bukkit.getServer().getPluginManager().callEvent(event);
if ((!event.replaced() && event.getAlternative() != null)
|| (event.getReplaced().equals("null") && event.getAlternative() != null))
event.setReplaced(event.getAlternative());
arg = arg.substring(0, positions[0]) + event.getReplaced().replace('|', (char)0x05) + arg.substring(positions[1] + 1, arg.length());
}
}
// Find new TAG
positions = locateTag(arg);
} while (positions != null || failsafe < 50);
// Return argument with replacements
arg = arg.replace((char)0x01, '<').replace((char)0x02, '>').replace((char)0x05, '|');
// Un-escape \< \>'s
if (!instant) arg = arg.replace("\\<", "<").replace("\\>", ">");
return arg;
}
|
diff --git a/src/program/main/Robot.java b/src/program/main/Robot.java
index ba0dfbb..f22aa52 100644
--- a/src/program/main/Robot.java
+++ b/src/program/main/Robot.java
@@ -1,187 +1,178 @@
package program.main;
import java.util.ArrayList;
import lejos.nxt.Motor;
import lejos.nxt.NXTRegulatedMotor;
import lejos.nxt.addon.ColorHTSensor;
import lejos.robotics.Color;
import lejos.robotics.navigation.DifferentialPilot;
import program.control.PIDControllerX;
import program.mapping.Direction;
import program.mapping.Park;
import program.mapping.Step;
public class Robot {
private final float MAXSPEED = 2 * 360; // 2 RPS
private final double WHEELDIAMETER = 4;
private final double TRACKWIDTH = 4;
private final int TURN_TIME_MS = 400;
private final NXTRegulatedMotor leftMotor, rightMotor;
public ColorHTSensor leftColorSensor, midColorSensor, rightColorSensor;
public DifferentialPilot pilot;
public PIDControllerX pid;
public Robot() {
leftMotor = new NXTRegulatedMotor(RoboMap.LEFT_MOTOR_PORT);
rightMotor = new NXTRegulatedMotor(RoboMap.RIGHT_MOTOR_PORT);
pilot = new DifferentialPilot(WHEELDIAMETER, TRACKWIDTH, leftMotor, rightMotor);
leftColorSensor = new ColorHTSensor(RoboMap.LEFT_COLOR_SENSOR_PORT);
midColorSensor = new ColorHTSensor(RoboMap.MID_COLOR_SENSOR_PORT);
rightColorSensor = new ColorHTSensor(RoboMap.RIGHT_COLOR_SENSOR_PORT);
pid = new PIDControllerX((1.0/200.0), 0.0, 5.0, 60.0);
pid.setOutputCaps(-.5, .5);
}
public Color getLeftColor() { return leftColorSensor.getColor(); }
public Color getMidColor() { return midColorSensor.getColor(); }
public Color getRightColor() { return rightColorSensor.getColor(); }
public boolean checkForStop() {
if (midColorSensor.getColor().getColor() == ColorHTSensor.RED) {
return true;
}
else {
return false;
}
}
public double getLTacoCount() {
return leftMotor.getTachoCount();
}
public double getRTacoCount() {
return rightMotor.getTachoCount();
}
public double getAveTacoCount() {
return (getLTacoCount() + getRTacoCount()) / 2;
}
public double runPID (boolean leftPID) {
ColorHTSensor colorSensor = leftPID ? this.leftColorSensor : this.rightColorSensor;
int colorID = colorSensor.getColorID();
int colorValue = colorSensor.getRGBComponent(ColorHTSensor.BLACK);
if (colorID == Color.WHITE) {
return this.pid.getOutput(colorValue, RoboMap.PID_WHITE_SETPOINT);
}
else if (colorID == Color.YELLOW) {
return this.pid.getOutput(colorValue, RoboMap.PID_YELLOW_SETPOINT);
}
else if (colorID == Color.BLUE) {
return this.pid.getOutput(colorValue, RoboMap.PID_BLUE_SETPOINT);
}
else if (colorID == Color.GREEN) {
return -.2;
}
return .05;
}
public void followLeftLine(boolean isCircle) {
double speed = .5;
double value = runPID(true);
if(isCircle) {
value *= 1.5;
tankDrive(.35 - value, .65 + value);
return;
}
//System.out.println(value);
//System.out.println((speed - (speed * value)) + ", " + (speed + (speed * value)));
//tankDrive(speed - (speed * value), speed + (speed * value));
tankDrive(speed - value, speed + value);
}
public void followRightLine(boolean isCircle) {
double speed = .5;
double value = runPID(false);
if (isCircle) {
value *= 1.5;
tankDrive(.65 + value, .35-value);
return;
}
//System.out.println(value);mine
//System.out.println((speed + (speed * value)) + ", " + (speed - (speed * value)));
//tankDrive(speed + (speed * value), speed - (speed * value));
tankDrive(speed + value, speed - value);
}
public void turnLeft() {
stop();
waitOneSecond();
pilot.travel(25);
pilot.arc(0, 450);
}
public void turnRight() {
stop();
waitOneSecond();
pilot.travel(25);
pilot.arc(0, -450);
}
public void followSteps(ArrayList<Step> steps) {
Step currentStep, nextStep;
while (steps.size() > 1) {
currentStep = steps.get(0);
nextStep = steps.get(1);
+ boolean circle = currentStep.getRoad().isCircle();
if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Right) {
- do followRightLine(false); while (!checkForStop());
+ do followRightLine(circle); while (!checkForStop());
waitOneSecond();
turnRight();
}
else if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Left) {
- do followLeftLine(false); while (!checkForStop());
+ do followLeftLine(circle); while (!checkForStop());
waitOneSecond();
turnLeft();
- }
- else if (currentStep.getRoad().isCircle() && nextStep.getDirection() == Direction.Left) {
- do followRightLine(true); while (!checkForStop());
- waitOneSecond();
- turnLeft();
- }
- else if (currentStep.getRoad().isCircle() && nextStep.getDirection() == Direction.Right) {
- do followLeftLine(true); while (!checkForStop());
- waitOneSecond();
- turnRight();
- }
+ }
else if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Straight) {
do followLeftLine(false); while(!checkForStop());
waitOneSecond();
pilot.travel(6);
}
else if (currentStep.getDirection() == Direction.Straight && nextStep instanceof Park) {
Park nextPark = (Park) nextStep;
if (nextPark.getDirection() == Direction.Left) {
}
else if (nextPark.getDirection() == Direction.Right) {
}
}
steps.remove(0);
}
}
public void tankDrive(double left, double right) {
//clamp values between [-1, 1]
left = MathUtils.clamp(left, -1, 1);
right = MathUtils.clamp(right, -1, 1);
float leftDrive = (float) left;
float rightDrive = (float) right;
leftMotor.setSpeed(MAXSPEED * leftDrive);
rightMotor.setSpeed(MAXSPEED * rightDrive);
leftMotor.forward();
rightMotor.forward();
}
public void stop() {
pilot.stop();
}
public void waitOneSecond() {
try {
Thread.sleep(1000);
} catch (InterruptedException ex) {
ex.printStackTrace();
}
}
}
| false | true | public void followSteps(ArrayList<Step> steps) {
Step currentStep, nextStep;
while (steps.size() > 1) {
currentStep = steps.get(0);
nextStep = steps.get(1);
if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Right) {
do followRightLine(false); while (!checkForStop());
waitOneSecond();
turnRight();
}
else if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Left) {
do followLeftLine(false); while (!checkForStop());
waitOneSecond();
turnLeft();
}
else if (currentStep.getRoad().isCircle() && nextStep.getDirection() == Direction.Left) {
do followRightLine(true); while (!checkForStop());
waitOneSecond();
turnLeft();
}
else if (currentStep.getRoad().isCircle() && nextStep.getDirection() == Direction.Right) {
do followLeftLine(true); while (!checkForStop());
waitOneSecond();
turnRight();
}
else if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Straight) {
do followLeftLine(false); while(!checkForStop());
waitOneSecond();
pilot.travel(6);
}
else if (currentStep.getDirection() == Direction.Straight && nextStep instanceof Park) {
Park nextPark = (Park) nextStep;
if (nextPark.getDirection() == Direction.Left) {
}
else if (nextPark.getDirection() == Direction.Right) {
}
}
steps.remove(0);
}
}
| public void followSteps(ArrayList<Step> steps) {
Step currentStep, nextStep;
while (steps.size() > 1) {
currentStep = steps.get(0);
nextStep = steps.get(1);
boolean circle = currentStep.getRoad().isCircle();
if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Right) {
do followRightLine(circle); while (!checkForStop());
waitOneSecond();
turnRight();
}
else if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Left) {
do followLeftLine(circle); while (!checkForStop());
waitOneSecond();
turnLeft();
}
else if (currentStep.getDirection() == Direction.Straight && nextStep.getDirection() == Direction.Straight) {
do followLeftLine(false); while(!checkForStop());
waitOneSecond();
pilot.travel(6);
}
else if (currentStep.getDirection() == Direction.Straight && nextStep instanceof Park) {
Park nextPark = (Park) nextStep;
if (nextPark.getDirection() == Direction.Left) {
}
else if (nextPark.getDirection() == Direction.Right) {
}
}
steps.remove(0);
}
}
|
diff --git a/src/com/android/gallery3d/filtershow/category/CategoryAdapter.java b/src/com/android/gallery3d/filtershow/category/CategoryAdapter.java
index 4dfaa7fe5..cfa64bc3c 100644
--- a/src/com/android/gallery3d/filtershow/category/CategoryAdapter.java
+++ b/src/com/android/gallery3d/filtershow/category/CategoryAdapter.java
@@ -1,180 +1,180 @@
/*
* Copyright (C) 2013 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.gallery3d.filtershow.category;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.android.gallery3d.R;
import com.android.gallery3d.filtershow.filters.FilterRepresentation;
import com.android.gallery3d.filtershow.filters.ImageFilterTinyPlanet;
import com.android.gallery3d.filtershow.imageshow.MasterImage;
import com.android.gallery3d.filtershow.presets.ImagePreset;
import com.android.gallery3d.filtershow.ui.FilterIconButton;
public class CategoryAdapter extends ArrayAdapter<Action> {
private static final String LOGTAG = "CategoryAdapter";
private int mItemHeight;
private View mContainer;
private int mItemWidth = ListView.LayoutParams.MATCH_PARENT;
private boolean mUseFilterIconButton = false;
private int mSelectedPosition;
int mCategory;
public CategoryAdapter(Context context, int textViewResourceId) {
super(context, textViewResourceId);
mItemHeight = (int) (context.getResources().getDisplayMetrics().density * 100);
}
public CategoryAdapter(Context context) {
this(context, 0);
}
public void setItemHeight(int height) {
mItemHeight = height;
}
public void setItemWidth(int width) {
mItemWidth = width;
}
@Override
public void add(Action action) {
super.add(action);
action.setAdapter(this);
}
public void initializeSelection(int category) {
mCategory = category;
if (category == MainPanel.LOOKS || category == MainPanel.BORDERS) {
ImagePreset preset = MasterImage.getImage().getPreset();
if (preset != null) {
for (int i = 0; i < getCount(); i++) {
if (preset.historyName().equals(getItem(i).getRepresentation().getName())) {
mSelectedPosition = i;
}
}
}
} else {
mSelectedPosition = -1;
}
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
if (mUseFilterIconButton) {
if (convertView == null) {
LayoutInflater inflater =
(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.filtericonbutton, parent, false);
}
FilterIconButton view = (FilterIconButton) convertView;
Action action = getItem(position);
view.setAction(action);
view.setup(action.getName(), null, this);
view.setLayoutParams(
new ListView.LayoutParams(mItemWidth, mItemHeight));
view.setTag(position);
if (mCategory == MainPanel.LOOKS || mCategory == MainPanel.BORDERS) {
- view.setBackground(null);
+ view.setBackgroundResource(0);
}
return view;
}
if (convertView == null) {
convertView = new CategoryView(getContext());
}
CategoryView view = (CategoryView) convertView;
view.setAction(getItem(position), this);
view.setLayoutParams(
new ListView.LayoutParams(mItemWidth, mItemHeight));
view.setTag(position);
return view;
}
public void setSelected(View v) {
int old = mSelectedPosition;
mSelectedPosition = (Integer) v.getTag();
if (old != -1) {
invalidateView(old);
}
invalidateView(mSelectedPosition);
}
public boolean isSelected(View v) {
return (Integer) v.getTag() == mSelectedPosition;
}
private void invalidateView(int position) {
View child = null;
if (mContainer instanceof ListView) {
ListView lv = (ListView) mContainer;
child = lv.getChildAt(position - lv.getFirstVisiblePosition());
} else {
CategoryTrack ct = (CategoryTrack) mContainer;
child = ct.getChildAt(position);
}
if (child != null) {
child.invalidate();
}
}
public void setContainer(View container) {
mContainer = container;
}
public void imageLoaded() {
notifyDataSetChanged();
}
public void setUseFilterIconButton(boolean useFilterIconButton) {
mUseFilterIconButton = useFilterIconButton;
}
public boolean isUseFilterIconButton() {
return mUseFilterIconButton;
}
public FilterRepresentation getTinyPlanet() {
for (int i = 0; i < getCount(); i++) {
Action action = getItem(i);
if (action.getRepresentation() != null
&& action.getRepresentation().getFilterClass()
== ImageFilterTinyPlanet.class) {
return action.getRepresentation();
}
}
return null;
}
public void removeTinyPlanet() {
for (int i = 0; i < getCount(); i++) {
Action action = getItem(i);
if (action.getRepresentation() != null
&& action.getRepresentation().getFilterClass()
== ImageFilterTinyPlanet.class) {
remove(action);
return;
}
}
}
}
| true | true | public View getView(int position, View convertView, ViewGroup parent) {
if (mUseFilterIconButton) {
if (convertView == null) {
LayoutInflater inflater =
(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.filtericonbutton, parent, false);
}
FilterIconButton view = (FilterIconButton) convertView;
Action action = getItem(position);
view.setAction(action);
view.setup(action.getName(), null, this);
view.setLayoutParams(
new ListView.LayoutParams(mItemWidth, mItemHeight));
view.setTag(position);
if (mCategory == MainPanel.LOOKS || mCategory == MainPanel.BORDERS) {
view.setBackground(null);
}
return view;
}
if (convertView == null) {
convertView = new CategoryView(getContext());
}
CategoryView view = (CategoryView) convertView;
view.setAction(getItem(position), this);
view.setLayoutParams(
new ListView.LayoutParams(mItemWidth, mItemHeight));
view.setTag(position);
return view;
}
| public View getView(int position, View convertView, ViewGroup parent) {
if (mUseFilterIconButton) {
if (convertView == null) {
LayoutInflater inflater =
(LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.filtericonbutton, parent, false);
}
FilterIconButton view = (FilterIconButton) convertView;
Action action = getItem(position);
view.setAction(action);
view.setup(action.getName(), null, this);
view.setLayoutParams(
new ListView.LayoutParams(mItemWidth, mItemHeight));
view.setTag(position);
if (mCategory == MainPanel.LOOKS || mCategory == MainPanel.BORDERS) {
view.setBackgroundResource(0);
}
return view;
}
if (convertView == null) {
convertView = new CategoryView(getContext());
}
CategoryView view = (CategoryView) convertView;
view.setAction(getItem(position), this);
view.setLayoutParams(
new ListView.LayoutParams(mItemWidth, mItemHeight));
view.setTag(position);
return view;
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.